blob: 28062456ccbe9d21f0b62fc5e6b3f1eef4bbba13 [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
Lang Hamesbe9af122012-10-02 04:45:10 +000048 bool FPContractable;
Chris Lattner9a207232010-06-26 21:48:21 +000049 const Expr *E; // Entire expr, for error unsupported. May not be binop.
Chris Lattner7f02f722007-08-24 05:35:26 +000050};
51
John McCall404cd162010-11-13 01:35:44 +000052static bool MustVisitNullValue(const Expr *E) {
53 // If a null pointer expression's type is the C++0x nullptr_t, then
54 // it's not necessarily a simple constant and it must be evaluated
55 // for its potential side effects.
56 return E->getType()->isNullPtrType();
57}
58
Benjamin Kramer85b45212009-11-28 19:45:26 +000059class ScalarExprEmitter
Chris Lattner7f02f722007-08-24 05:35:26 +000060 : public StmtVisitor<ScalarExprEmitter, Value*> {
61 CodeGenFunction &CGF;
Daniel Dunbar45d196b2008-11-01 01:53:16 +000062 CGBuilderTy &Builder;
Mike Stump7f79f9b2009-05-29 15:46:01 +000063 bool IgnoreResultAssign;
Owen Andersona1cf15f2009-07-14 23:10:40 +000064 llvm::LLVMContext &VMContext;
Chris Lattner7f02f722007-08-24 05:35:26 +000065public:
66
Mike Stump7f79f9b2009-05-29 15:46:01 +000067 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
Mike Stumpdb52dcd2009-09-09 13:00:44 +000068 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
Owen Andersona1cf15f2009-07-14 23:10:40 +000069 VMContext(cgf.getLLVMContext()) {
Chris Lattner7f02f722007-08-24 05:35:26 +000070 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +000071
Chris Lattner7f02f722007-08-24 05:35:26 +000072 //===--------------------------------------------------------------------===//
73 // Utilities
74 //===--------------------------------------------------------------------===//
75
Mike Stump7f79f9b2009-05-29 15:46:01 +000076 bool TestAndClearIgnoreResultAssign() {
Chris Lattner9c10fcf2009-07-08 01:08:03 +000077 bool I = IgnoreResultAssign;
78 IgnoreResultAssign = false;
79 return I;
80 }
Mike Stump7f79f9b2009-05-29 15:46:01 +000081
Chris Lattner2acc6e32011-07-18 04:24:23 +000082 llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
Chris Lattner7f02f722007-08-24 05:35:26 +000083 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
Richard Smith7ac9ef12012-09-08 02:08:36 +000084 LValue EmitCheckedLValue(const Expr *E, CodeGenFunction::TypeCheckKind TCK) {
85 return CGF.EmitCheckedLValue(E, TCK);
Richard Smith2c9f87c2012-08-24 00:54:33 +000086 }
Chris Lattner7f02f722007-08-24 05:35:26 +000087
John McCall545d9962011-06-25 02:11:03 +000088 Value *EmitLoadOfLValue(LValue LV) {
89 return CGF.EmitLoadOfLValue(LV).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +000090 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +000091
Chris Lattner7f02f722007-08-24 05:35:26 +000092 /// EmitLoadOfLValue - Given an expression with complex type that represents a
93 /// value l-value, this method emits the address of the l-value, then loads
94 /// and returns the result.
95 Value *EmitLoadOfLValue(const Expr *E) {
Richard Smith7ac9ef12012-09-08 02:08:36 +000096 return EmitLoadOfLValue(EmitCheckedLValue(E, CodeGenFunction::TCK_Load));
Chris Lattner7f02f722007-08-24 05:35:26 +000097 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +000098
Chris Lattner9abc84e2007-08-26 16:42:57 +000099 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +0000100 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +0000101 Value *EmitConversionToBool(Value *Src, QualType DstTy);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000102
Chris Lattner3707b252007-08-26 06:48:56 +0000103 /// EmitScalarConversion - Emit a conversion from the specified type to the
104 /// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000105 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
106
107 /// EmitComplexToScalarConversion - Emit a conversion from the specified
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000108 /// complex type to the specified destination type, where the destination type
109 /// is an LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000110 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
111 QualType SrcTy, QualType DstTy);
Mike Stumpdf6b68c2009-02-12 18:29:15 +0000112
Anders Carlssona40a9f32010-05-22 17:45:10 +0000113 /// EmitNullValue - Emit a value that corresponds to null for the given type.
114 Value *EmitNullValue(QualType Ty);
115
John McCalldaa8e4e2010-11-15 09:13:47 +0000116 /// EmitFloatToBoolConversion - Perform an FP to boolean conversion.
117 Value *EmitFloatToBoolConversion(Value *V) {
118 // Compare against 0.0 for fp scalars.
119 llvm::Value *Zero = llvm::Constant::getNullValue(V->getType());
120 return Builder.CreateFCmpUNE(V, Zero, "tobool");
121 }
122
123 /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion.
124 Value *EmitPointerToBoolConversion(Value *V) {
125 Value *Zero = llvm::ConstantPointerNull::get(
126 cast<llvm::PointerType>(V->getType()));
127 return Builder.CreateICmpNE(V, Zero, "tobool");
128 }
129
130 Value *EmitIntToBoolConversion(Value *V) {
131 // Because of the type rules of C, we often end up computing a
132 // logical value, then zero extending it to int, then wanting it
133 // as a logical value again. Optimize this common case.
134 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) {
135 if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) {
136 Value *Result = ZI->getOperand(0);
137 // If there aren't any more uses, zap the instruction to save space.
138 // Note that there can be more uses, for example if this
139 // is the result of an assignment.
140 if (ZI->use_empty())
141 ZI->eraseFromParent();
142 return Result;
143 }
144 }
145
Chris Lattner48431f92011-04-19 22:55:03 +0000146 return Builder.CreateIsNotNull(V, "tobool");
John McCalldaa8e4e2010-11-15 09:13:47 +0000147 }
148
Chris Lattner7f02f722007-08-24 05:35:26 +0000149 //===--------------------------------------------------------------------===//
150 // Visitor Methods
151 //===--------------------------------------------------------------------===//
152
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +0000153 Value *Visit(Expr *E) {
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +0000154 return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
155 }
156
Chris Lattner7f02f722007-08-24 05:35:26 +0000157 Value *VisitStmt(Stmt *S) {
Ted Kremenek7a9d49f2007-12-11 21:27:55 +0000158 S->dump(CGF.getContext().getSourceManager());
David Blaikieb219cfc2011-09-23 05:06:16 +0000159 llvm_unreachable("Stmt can't have complex result type!");
Chris Lattner7f02f722007-08-24 05:35:26 +0000160 }
161 Value *VisitExpr(Expr *S);
Fariborz Jahanianf51dc642009-10-21 23:45:42 +0000162
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +0000163 Value *VisitParenExpr(ParenExpr *PE) {
164 return Visit(PE->getSubExpr());
165 }
John McCall91a57552011-07-15 05:09:51 +0000166 Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
167 return Visit(E->getReplacement());
168 }
Peter Collingbournef111d932011-04-15 00:35:48 +0000169 Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
170 return Visit(GE->getResultExpr());
171 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000172
173 // Leaves.
174 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000175 return Builder.getInt(E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000176 }
177 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Owen Andersonbc0a2222009-07-27 21:00:51 +0000178 return llvm::ConstantFP::get(VMContext, E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000179 }
180 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000181 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000182 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000183 Value *VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
184 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
185 }
Nate Begemane7579b52007-11-15 05:40:03 +0000186 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000187 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Nate Begemane7579b52007-11-15 05:40:03 +0000188 }
Douglas Gregored8abf12010-07-08 06:14:04 +0000189 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000190 return EmitNullValue(E->getType());
Argyrios Kyrtzidis7267f782008-08-23 19:35:47 +0000191 }
Anders Carlsson3f704562008-12-21 22:39:40 +0000192 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000193 return EmitNullValue(E->getType());
Anders Carlsson3f704562008-12-21 22:39:40 +0000194 }
Eli Friedman0027d2b2010-08-05 09:58:49 +0000195 Value *VisitOffsetOfExpr(OffsetOfExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +0000196 Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000197 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
Chris Lattnerd9becd12009-10-28 23:59:40 +0000198 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
199 return Builder.CreateBitCast(V, ConvertType(E->getType()));
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000200 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000201
Douglas Gregor9370c8f2011-01-12 22:11:34 +0000202 Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000203 return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength());
Douglas Gregor9370c8f2011-01-12 22:11:34 +0000204 }
John McCalle996ffd2011-02-16 08:02:54 +0000205
John McCall4b9c2d22011-11-06 09:01:30 +0000206 Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) {
207 return CGF.EmitPseudoObjectRValue(E).getScalarVal();
208 }
209
John McCalle996ffd2011-02-16 08:02:54 +0000210 Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
John McCall56ca35d2011-02-17 10:25:35 +0000211 if (E->isGLValue())
John McCall545d9962011-06-25 02:11:03 +0000212 return EmitLoadOfLValue(CGF.getOpaqueLValueMapping(E));
John McCalle996ffd2011-02-16 08:02:54 +0000213
214 // Otherwise, assume the mapping is the scalar directly.
John McCall56ca35d2011-02-17 10:25:35 +0000215 return CGF.getOpaqueRValueMapping(E).getScalarVal();
John McCalle996ffd2011-02-16 08:02:54 +0000216 }
John McCalldd2ecee2012-03-10 03:05:10 +0000217
Chris Lattner7f02f722007-08-24 05:35:26 +0000218 // l-values.
John McCallf4b88a42012-03-10 09:33:50 +0000219 Value *VisitDeclRefExpr(DeclRefExpr *E) {
220 if (CodeGenFunction::ConstantEmission result = CGF.tryEmitAsConstant(E)) {
John McCalldd2ecee2012-03-10 03:05:10 +0000221 if (result.isReference())
John McCallf4b88a42012-03-10 09:33:50 +0000222 return EmitLoadOfLValue(result.getReferenceLValue(CGF, E));
John McCalldd2ecee2012-03-10 03:05:10 +0000223 return result.getValue();
Richard Smitha3ca41f2012-03-02 23:27:11 +0000224 }
John McCallf4b88a42012-03-10 09:33:50 +0000225 return EmitLoadOfLValue(E);
John McCalldd2ecee2012-03-10 03:05:10 +0000226 }
227
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000228 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
229 return CGF.EmitObjCSelectorExpr(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000230 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000231 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
232 return CGF.EmitObjCProtocolExpr(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000233 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000234 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000235 return EmitLoadOfLValue(E);
236 }
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000237 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
Fariborz Jahanian180ff3a2011-03-02 20:09:49 +0000238 if (E->getMethodDecl() &&
239 E->getMethodDecl()->getResultType()->isReferenceType())
240 return EmitLoadOfLValue(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000241 return CGF.EmitObjCMessageExpr(E).getScalarVal();
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000242 }
243
Fariborz Jahanian83dc3252009-12-09 19:05:56 +0000244 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
Fariborz Jahanian820bca42009-12-09 23:35:29 +0000245 LValue LV = CGF.EmitObjCIsaExpr(E);
John McCall545d9962011-06-25 02:11:03 +0000246 Value *V = CGF.EmitLoadOfLValue(LV).getScalarVal();
Fariborz Jahanian83dc3252009-12-09 19:05:56 +0000247 return V;
248 }
249
Chris Lattner7f02f722007-08-24 05:35:26 +0000250 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmand38617c2008-05-14 19:38:39 +0000251 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Eli Friedman28665272009-11-26 03:22:21 +0000252 Value *VisitMemberExpr(MemberExpr *E);
Nate Begeman213541a2008-04-18 23:10:10 +0000253 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Chris Lattnerbe20bb52008-10-26 23:53:12 +0000254 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
255 return EmitLoadOfLValue(E);
256 }
Devang Patel35634f52007-10-24 17:18:43 +0000257
Nate Begeman0533b302009-10-18 20:10:40 +0000258 Value *VisitInitListExpr(InitListExpr *E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000259
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000260 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Anders Carlsson3cb18bc2010-05-14 15:05:19 +0000261 return CGF.CGM.EmitNullConstant(E->getType());
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000262 }
John McCallbc8d40d2011-06-24 21:55:10 +0000263 Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000264 if (E->getType()->isVariablyModifiedType())
John McCallbc8d40d2011-06-24 21:55:10 +0000265 CGF.EmitVariablyModifiedType(E->getType());
266 return VisitCastExpr(E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000267 }
John McCallbc8d40d2011-06-24 21:55:10 +0000268 Value *VisitCastExpr(CastExpr *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000269
270 Value *VisitCallExpr(const CallExpr *E) {
Anders Carlssone9f2f452009-05-27 03:37:57 +0000271 if (E->getCallReturnType()->isReferenceType())
272 return EmitLoadOfLValue(E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000273
Chris Lattner9b655512007-08-31 22:49:20 +0000274 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +0000275 }
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000276
Chris Lattner33793202007-08-31 22:09:40 +0000277 Value *VisitStmtExpr(const StmtExpr *E);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000278
Chris Lattner7f02f722007-08-24 05:35:26 +0000279 // Unary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000280 Value *VisitUnaryPostDec(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000281 LValue LV = EmitLValue(E->getSubExpr());
282 return EmitScalarPrePostIncDec(E, LV, false, false);
Chris Lattner7f02f722007-08-24 05:35:26 +0000283 }
284 Value *VisitUnaryPostInc(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000285 LValue LV = EmitLValue(E->getSubExpr());
286 return EmitScalarPrePostIncDec(E, LV, true, false);
Chris Lattner7f02f722007-08-24 05:35:26 +0000287 }
288 Value *VisitUnaryPreDec(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000289 LValue LV = EmitLValue(E->getSubExpr());
290 return EmitScalarPrePostIncDec(E, LV, false, true);
Chris Lattner7f02f722007-08-24 05:35:26 +0000291 }
292 Value *VisitUnaryPreInc(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000293 LValue LV = EmitLValue(E->getSubExpr());
294 return EmitScalarPrePostIncDec(E, LV, true, true);
Chris Lattner7f02f722007-08-24 05:35:26 +0000295 }
Chris Lattner8c11a652010-06-26 22:09:34 +0000296
Anton Yartsev683564a2011-02-07 02:17:30 +0000297 llvm::Value *EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
298 llvm::Value *InVal,
299 llvm::Value *NextVal,
300 bool IsInc);
301
Chris Lattner8c11a652010-06-26 22:09:34 +0000302 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
303 bool isInc, bool isPre);
304
305
Chris Lattner7f02f722007-08-24 05:35:26 +0000306 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
John McCall5808ce42011-02-03 08:15:49 +0000307 if (isa<MemberPointerType>(E->getType())) // never sugared
308 return CGF.CGM.getMemberPointerConstant(E);
309
Chris Lattner7f02f722007-08-24 05:35:26 +0000310 return EmitLValue(E->getSubExpr()).getAddress();
311 }
John McCallfd569002010-12-04 12:43:24 +0000312 Value *VisitUnaryDeref(const UnaryOperator *E) {
313 if (E->getType()->isVoidType())
314 return Visit(E->getSubExpr()); // the actual value should be unused
315 return EmitLoadOfLValue(E);
316 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000317 Value *VisitUnaryPlus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000318 // This differs from gcc, though, most likely due to a bug in gcc.
319 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +0000320 return Visit(E->getSubExpr());
321 }
322 Value *VisitUnaryMinus (const UnaryOperator *E);
323 Value *VisitUnaryNot (const UnaryOperator *E);
324 Value *VisitUnaryLNot (const UnaryOperator *E);
Chris Lattner46f93d02007-08-24 21:20:17 +0000325 Value *VisitUnaryReal (const UnaryOperator *E);
326 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000327 Value *VisitUnaryExtension(const UnaryOperator *E) {
328 return Visit(E->getSubExpr());
329 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000330
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000331 // C++
Douglas Gregor3f86ce12011-08-09 00:37:14 +0000332 Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) {
Eli Friedmanec24b0e2011-08-14 04:50:34 +0000333 return EmitLoadOfLValue(E);
Douglas Gregor3f86ce12011-08-09 00:37:14 +0000334 }
335
Chris Lattner04421082008-04-08 04:40:51 +0000336 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
337 return Visit(DAE->getExpr());
338 }
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000339 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
340 return CGF.LoadCXXThis();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000341 }
342
John McCall4765fa02010-12-06 08:20:24 +0000343 Value *VisitExprWithCleanups(ExprWithCleanups *E) {
John McCall1a343eb2011-11-10 08:15:53 +0000344 CGF.enterFullExpression(E);
345 CodeGenFunction::RunCleanupsScope Scope(CGF);
346 return Visit(E->getSubExpr());
Anders Carlsson7f6ad152009-05-19 04:48:36 +0000347 }
Anders Carlssona00703d2009-05-31 01:40:14 +0000348 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
349 return CGF.EmitCXXNewExpr(E);
350 }
Anders Carlsson60e282c2009-08-16 21:13:42 +0000351 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
352 CGF.EmitCXXDeleteExpr(E);
353 return 0;
354 }
Eli Friedman9dfebdc2009-12-10 22:40:32 +0000355 Value *VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000356 return Builder.getInt1(E->getValue());
Eli Friedman9dfebdc2009-12-10 22:40:32 +0000357 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000358
Francois Pichet6ad6f282010-12-07 00:08:36 +0000359 Value *VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
Francois Pichetf1872372010-12-08 22:35:30 +0000360 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Francois Pichet6ad6f282010-12-07 00:08:36 +0000361 }
362
John Wiegley21ff2e52011-04-28 00:16:57 +0000363 Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
364 return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue());
365 }
366
John Wiegley55262202011-04-25 06:54:41 +0000367 Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
368 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
369 }
370
Douglas Gregora71d8192009-09-04 17:36:40 +0000371 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
372 // C++ [expr.pseudo]p1:
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000373 // The result shall only be used as the operand for the function call
Douglas Gregora71d8192009-09-04 17:36:40 +0000374 // operator (), and the result of such a call has type void. The only
375 // effect is the evaluation of the postfix-expression before the dot or
376 // arrow.
377 CGF.EmitScalarExpr(E->getBase());
378 return 0;
379 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000380
Anders Carlssonc1eb14a2009-09-15 04:39:46 +0000381 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000382 return EmitNullValue(E->getType());
Anders Carlssonc1eb14a2009-09-15 04:39:46 +0000383 }
Anders Carlsson756b5c42009-10-30 01:42:31 +0000384
385 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
386 CGF.EmitCXXThrowExpr(E);
387 return 0;
388 }
389
Sebastian Redl98294de2010-09-10 21:04:00 +0000390 Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000391 return Builder.getInt1(E->getValue());
Sebastian Redl98294de2010-09-10 21:04:00 +0000392 }
393
Chris Lattner7f02f722007-08-24 05:35:26 +0000394 // Binary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000395 Value *EmitMul(const BinOpInfo &Ops) {
Douglas Gregor575a1c92011-05-20 16:38:50 +0000396 if (Ops.Ty->isSignedIntegerOrEnumerationType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000397 switch (CGF.getContext().getLangOpts().getSignedOverflowBehavior()) {
Chris Lattnera4d71452010-06-26 21:25:03 +0000398 case LangOptions::SOB_Defined:
399 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
Richard Smith9d3e2262012-08-25 00:32:28 +0000400 case LangOptions::SOB_Undefined:
401 if (!CGF.CatchUndefined)
402 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
403 // Fall through.
Chris Lattnera4d71452010-06-26 21:25:03 +0000404 case LangOptions::SOB_Trapping:
405 return EmitOverflowCheckedBinOp(Ops);
406 }
407 }
408
Duncan Sandsf177d9d2010-02-15 16:14:01 +0000409 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner87415d22009-06-17 06:36:24 +0000410 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
Chris Lattner7f02f722007-08-24 05:35:26 +0000411 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
412 }
Chris Lattner80230302010-09-11 21:47:09 +0000413 bool isTrapvOverflowBehavior() {
Richard Smith9d3e2262012-08-25 00:32:28 +0000414 return CGF.getContext().getLangOpts().getSignedOverflowBehavior()
415 == LangOptions::SOB_Trapping || CGF.CatchUndefined;
Chris Lattner80230302010-09-11 21:47:09 +0000416 }
Mike Stump2add4732009-04-01 20:28:16 +0000417 /// Create a binary op that checks for overflow.
418 /// Currently only supports +, - and *.
419 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
Richard Smith7ac9ef12012-09-08 02:08:36 +0000420
Chris Lattner80230302010-09-11 21:47:09 +0000421 // Check for undefined division and modulus behaviors.
422 void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
423 llvm::Value *Zero,bool isDiv);
Chris Lattner7f02f722007-08-24 05:35:26 +0000424 Value *EmitDiv(const BinOpInfo &Ops);
425 Value *EmitRem(const BinOpInfo &Ops);
426 Value *EmitAdd(const BinOpInfo &Ops);
427 Value *EmitSub(const BinOpInfo &Ops);
428 Value *EmitShl(const BinOpInfo &Ops);
429 Value *EmitShr(const BinOpInfo &Ops);
430 Value *EmitAnd(const BinOpInfo &Ops) {
431 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
432 }
433 Value *EmitXor(const BinOpInfo &Ops) {
434 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
435 }
436 Value *EmitOr (const BinOpInfo &Ops) {
437 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
438 }
439
Chris Lattner1f1ded92007-08-24 21:00:35 +0000440 BinOpInfo EmitBinOps(const BinaryOperator *E);
Douglas Gregor6a03e342010-04-23 04:16:32 +0000441 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
442 Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
Daniel Dunbard7f7d082010-06-29 22:00:45 +0000443 Value *&Result);
Douglas Gregor6a03e342010-04-23 04:16:32 +0000444
Chris Lattner3ccf7742007-08-26 21:41:21 +0000445 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner1f1ded92007-08-24 21:00:35 +0000446 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
447
448 // Binary operators and binary compound assignment operators.
449#define HANDLEBINOP(OP) \
Chris Lattner3ccf7742007-08-26 21:41:21 +0000450 Value *VisitBin ## OP(const BinaryOperator *E) { \
451 return Emit ## OP(EmitBinOps(E)); \
452 } \
453 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
454 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner1f1ded92007-08-24 21:00:35 +0000455 }
Daniel Dunbar7177dee2009-12-19 17:50:07 +0000456 HANDLEBINOP(Mul)
457 HANDLEBINOP(Div)
458 HANDLEBINOP(Rem)
459 HANDLEBINOP(Add)
460 HANDLEBINOP(Sub)
461 HANDLEBINOP(Shl)
462 HANDLEBINOP(Shr)
463 HANDLEBINOP(And)
464 HANDLEBINOP(Xor)
465 HANDLEBINOP(Or)
Chris Lattner1f1ded92007-08-24 21:00:35 +0000466#undef HANDLEBINOP
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000467
Chris Lattner7f02f722007-08-24 05:35:26 +0000468 // Comparisons.
469 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
470 unsigned SICmpOpc, unsigned FCmpOpc);
471#define VISITCOMP(CODE, UI, SI, FP) \
472 Value *VisitBin##CODE(const BinaryOperator *E) { \
473 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
474 llvm::FCmpInst::FP); }
Daniel Dunbar7177dee2009-12-19 17:50:07 +0000475 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT)
476 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT)
477 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE)
478 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE)
479 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ)
480 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE)
Chris Lattner7f02f722007-08-24 05:35:26 +0000481#undef VISITCOMP
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000482
Chris Lattner7f02f722007-08-24 05:35:26 +0000483 Value *VisitBinAssign (const BinaryOperator *E);
484
485 Value *VisitBinLAnd (const BinaryOperator *E);
486 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000487 Value *VisitBinComma (const BinaryOperator *E);
488
Eli Friedman25b825d2009-11-18 09:41:26 +0000489 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
490 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
491
Chris Lattner7f02f722007-08-24 05:35:26 +0000492 // Other Operators.
Mike Stumpdf6b68c2009-02-12 18:29:15 +0000493 Value *VisitBlockExpr(const BlockExpr *BE);
John McCall56ca35d2011-02-17 10:25:35 +0000494 Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
Chris Lattner7f02f722007-08-24 05:35:26 +0000495 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000496 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000497 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
498 return CGF.EmitObjCStringLiteral(E);
499 }
Patrick Beardeb382ec2012-04-19 00:25:12 +0000500 Value *VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
501 return CGF.EmitObjCBoxedExpr(E);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000502 }
503 Value *VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
504 return CGF.EmitObjCArrayLiteral(E);
505 }
506 Value *VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
507 return CGF.EmitObjCDictionaryLiteral(E);
508 }
Tanya Lattner61eee0c2011-06-04 00:47:47 +0000509 Value *VisitAsTypeExpr(AsTypeExpr *CE);
Eli Friedman276b0612011-10-11 02:20:01 +0000510 Value *VisitAtomicExpr(AtomicExpr *AE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000511};
512} // end anonymous namespace.
513
514//===----------------------------------------------------------------------===//
515// Utilities
516//===----------------------------------------------------------------------===//
517
Chris Lattner9abc84e2007-08-26 16:42:57 +0000518/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +0000519/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +0000520Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
John McCall467b27b2009-10-22 20:10:53 +0000521 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000522
John McCalldaa8e4e2010-11-15 09:13:47 +0000523 if (SrcType->isRealFloatingType())
524 return EmitFloatToBoolConversion(Src);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000525
John McCall0bab0cd2010-08-23 01:21:21 +0000526 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
527 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000528
Daniel Dunbard1d66bc2008-08-25 10:38:11 +0000529 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
Chris Lattner9abc84e2007-08-26 16:42:57 +0000530 "Unknown scalar type to convert");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000531
John McCalldaa8e4e2010-11-15 09:13:47 +0000532 if (isa<llvm::IntegerType>(Src->getType()))
533 return EmitIntToBoolConversion(Src);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000534
John McCalldaa8e4e2010-11-15 09:13:47 +0000535 assert(isa<llvm::PointerType>(Src->getType()));
536 return EmitPointerToBoolConversion(Src);
Chris Lattner9abc84e2007-08-26 16:42:57 +0000537}
538
Chris Lattner3707b252007-08-26 06:48:56 +0000539/// EmitScalarConversion - Emit a conversion from the specified type to the
540/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000541Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
542 QualType DstType) {
Chris Lattner96196622008-07-26 22:37:01 +0000543 SrcType = CGF.getContext().getCanonicalType(SrcType);
544 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner3707b252007-08-26 06:48:56 +0000545 if (SrcType == DstType) return Src;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000546
Chris Lattnercf289082007-08-26 07:21:11 +0000547 if (DstType->isVoidType()) return 0;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000548
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000549 llvm::Type *SrcTy = Src->getType();
550
551 // Floating casts might be a bit special: if we're doing casts to / from half
552 // FP, we should go via special intrinsics.
553 if (SrcType->isHalfType()) {
554 Src = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16), Src);
555 SrcType = CGF.getContext().FloatTy;
Chris Lattner8b418682012-02-07 00:39:47 +0000556 SrcTy = CGF.FloatTy;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000557 }
558
Chris Lattner3707b252007-08-26 06:48:56 +0000559 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnered70f0a2007-08-26 16:52:28 +0000560 if (DstType->isBooleanType())
561 return EmitConversionToBool(Src, SrcType);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000562
Chris Lattner2acc6e32011-07-18 04:24:23 +0000563 llvm::Type *DstTy = ConvertType(DstType);
Chris Lattner3707b252007-08-26 06:48:56 +0000564
565 // Ignore conversions like int -> uint.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000566 if (SrcTy == DstTy)
Chris Lattner3707b252007-08-26 06:48:56 +0000567 return Src;
568
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000569 // Handle pointer conversions next: pointers can only be converted to/from
570 // other pointers and integers. Check for pointer types in terms of LLVM, as
571 // some native types (like Obj-C id) may map to a pointer type.
Daniel Dunbar270cc662008-08-25 09:51:32 +0000572 if (isa<llvm::PointerType>(DstTy)) {
Chris Lattner3707b252007-08-26 06:48:56 +0000573 // The source value may be an integer, or a pointer.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000574 if (isa<llvm::PointerType>(SrcTy))
Chris Lattner3707b252007-08-26 06:48:56 +0000575 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson191dfe92009-09-12 04:57:16 +0000576
Chris Lattner3707b252007-08-26 06:48:56 +0000577 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Eli Friedman25615422009-03-04 04:02:35 +0000578 // First, convert to the correct width so that we control the kind of
579 // extension.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000580 llvm::Type *MiddleTy = CGF.IntPtrTy;
Douglas Gregor575a1c92011-05-20 16:38:50 +0000581 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
Eli Friedman25615422009-03-04 04:02:35 +0000582 llvm::Value* IntResult =
583 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
584 // Then, cast to pointer.
585 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000586 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000587
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000588 if (isa<llvm::PointerType>(SrcTy)) {
Chris Lattner3707b252007-08-26 06:48:56 +0000589 // Must be an ptr to int cast.
590 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson50b5a302007-10-31 23:18:02 +0000591 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000592 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000593
Nate Begeman213541a2008-04-18 23:10:10 +0000594 // A scalar can be splatted to an extended vector of the same element type
Nate Begeman2ef13e52009-08-10 23:49:36 +0000595 if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000596 // Cast the scalar to element type
John McCall183700f2009-09-21 23:43:11 +0000597 QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType();
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000598 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
599
600 // Insert the element in element zero of an undef vector
Owen Anderson03e20502009-07-30 23:11:26 +0000601 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
Chris Lattner48431f92011-04-19 22:55:03 +0000602 llvm::Value *Idx = Builder.getInt32(0);
Benjamin Kramer578faa82011-09-27 21:06:10 +0000603 UnV = Builder.CreateInsertElement(UnV, Elt, Idx);
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000604
605 // Splat the element across to all elements
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000606 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
Chris Lattner2ce88422012-01-25 05:34:41 +0000607 llvm::Constant *Mask = llvm::ConstantVector::getSplat(NumElements,
608 Builder.getInt32(0));
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000609 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
610 return Yay;
611 }
Nate Begeman4119d1a2007-12-30 02:59:45 +0000612
Chris Lattner3b1ae002008-02-02 04:51:41 +0000613 // Allow bitcast from vector to integer/fp of the same size.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000614 if (isa<llvm::VectorType>(SrcTy) ||
Chris Lattner3b1ae002008-02-02 04:51:41 +0000615 isa<llvm::VectorType>(DstTy))
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000616 return Builder.CreateBitCast(Src, DstTy, "conv");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000617
Chris Lattner3707b252007-08-26 06:48:56 +0000618 // Finally, we have the arithmetic types: real int/float.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000619 Value *Res = NULL;
620 llvm::Type *ResTy = DstTy;
621
622 // Cast to half via float
623 if (DstType->isHalfType())
Chris Lattner8b418682012-02-07 00:39:47 +0000624 DstTy = CGF.FloatTy;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000625
626 if (isa<llvm::IntegerType>(SrcTy)) {
Douglas Gregor575a1c92011-05-20 16:38:50 +0000627 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000628 if (isa<llvm::IntegerType>(DstTy))
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000629 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000630 else if (InputSigned)
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000631 Res = Builder.CreateSIToFP(Src, DstTy, "conv");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000632 else
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000633 Res = Builder.CreateUIToFP(Src, DstTy, "conv");
634 } else if (isa<llvm::IntegerType>(DstTy)) {
635 assert(SrcTy->isFloatingPointTy() && "Unknown real conversion");
Douglas Gregor575a1c92011-05-20 16:38:50 +0000636 if (DstType->isSignedIntegerOrEnumerationType())
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000637 Res = Builder.CreateFPToSI(Src, DstTy, "conv");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000638 else
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000639 Res = Builder.CreateFPToUI(Src, DstTy, "conv");
640 } else {
641 assert(SrcTy->isFloatingPointTy() && DstTy->isFloatingPointTy() &&
642 "Unknown real conversion");
643 if (DstTy->getTypeID() < SrcTy->getTypeID())
644 Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
645 else
646 Res = Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000647 }
648
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000649 if (DstTy != ResTy) {
650 assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion");
651 Res = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16), Res);
652 }
653
654 return Res;
Chris Lattner3707b252007-08-26 06:48:56 +0000655}
656
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000657/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
658/// type to the specified destination type, where the destination type is an
659/// LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000660Value *ScalarExprEmitter::
661EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
662 QualType SrcTy, QualType DstTy) {
Chris Lattnered70f0a2007-08-26 16:52:28 +0000663 // Get the source element type.
John McCall183700f2009-09-21 23:43:11 +0000664 SrcTy = SrcTy->getAs<ComplexType>()->getElementType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000665
Chris Lattnered70f0a2007-08-26 16:52:28 +0000666 // Handle conversions to bool first, they are special: comparisons against 0.
667 if (DstTy->isBooleanType()) {
668 // Complex != 0 -> (Real != 0) | (Imag != 0)
669 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
670 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
671 return Builder.CreateOr(Src.first, Src.second, "tobool");
672 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000673
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000674 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
675 // the imaginary part of the complex value is discarded and the value of the
676 // real part is converted according to the conversion rules for the
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000677 // corresponding real type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000678 return EmitScalarConversion(Src.first, SrcTy, DstTy);
679}
680
Anders Carlssona40a9f32010-05-22 17:45:10 +0000681Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
John McCall0bab0cd2010-08-23 01:21:21 +0000682 if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>())
683 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
684
685 return llvm::Constant::getNullValue(ConvertType(Ty));
Anders Carlssona40a9f32010-05-22 17:45:10 +0000686}
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000687
Chris Lattner7f02f722007-08-24 05:35:26 +0000688//===----------------------------------------------------------------------===//
689// Visitor Methods
690//===----------------------------------------------------------------------===//
691
692Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbar488e9932008-08-16 00:56:44 +0000693 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner7f02f722007-08-24 05:35:26 +0000694 if (E->getType()->isVoidType())
695 return 0;
Owen Anderson03e20502009-07-30 23:11:26 +0000696 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Chris Lattner7f02f722007-08-24 05:35:26 +0000697}
698
Eli Friedmand38617c2008-05-14 19:38:39 +0000699Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000700 // Vector Mask Case
701 if (E->getNumSubExprs() == 2 ||
Rafael Espindola3f4cb122010-06-09 02:17:08 +0000702 (E->getNumSubExprs() == 3 && E->getExpr(2)->getType()->isVectorType())) {
Chris Lattner77b89b82010-06-27 07:15:29 +0000703 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
704 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
705 Value *Mask;
Nate Begeman37b6a572010-06-08 00:16:34 +0000706
Chris Lattner2acc6e32011-07-18 04:24:23 +0000707 llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
Nate Begeman37b6a572010-06-08 00:16:34 +0000708 unsigned LHSElts = LTy->getNumElements();
709
710 if (E->getNumSubExprs() == 3) {
711 Mask = CGF.EmitScalarExpr(E->getExpr(2));
712
713 // Shuffle LHS & RHS into one input vector.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000714 SmallVector<llvm::Constant*, 32> concat;
Nate Begeman37b6a572010-06-08 00:16:34 +0000715 for (unsigned i = 0; i != LHSElts; ++i) {
Chris Lattner48431f92011-04-19 22:55:03 +0000716 concat.push_back(Builder.getInt32(2*i));
717 concat.push_back(Builder.getInt32(2*i+1));
Nate Begeman37b6a572010-06-08 00:16:34 +0000718 }
719
Chris Lattnerfb018d12011-02-15 00:14:06 +0000720 Value* CV = llvm::ConstantVector::get(concat);
Nate Begeman37b6a572010-06-08 00:16:34 +0000721 LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat");
722 LHSElts *= 2;
723 } else {
724 Mask = RHS;
725 }
726
Chris Lattner2acc6e32011-07-18 04:24:23 +0000727 llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
Nate Begeman37b6a572010-06-08 00:16:34 +0000728 llvm::Constant* EltMask;
729
730 // Treat vec3 like vec4.
731 if ((LHSElts == 6) && (E->getNumSubExprs() == 3))
732 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
733 (1 << llvm::Log2_32(LHSElts+2))-1);
734 else if ((LHSElts == 3) && (E->getNumSubExprs() == 2))
735 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
736 (1 << llvm::Log2_32(LHSElts+1))-1);
737 else
738 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
739 (1 << llvm::Log2_32(LHSElts))-1);
740
741 // Mask off the high bits of each shuffle index.
Chris Lattner2ce88422012-01-25 05:34:41 +0000742 Value *MaskBits = llvm::ConstantVector::getSplat(MTy->getNumElements(),
743 EltMask);
Nate Begeman37b6a572010-06-08 00:16:34 +0000744 Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
745
746 // newv = undef
747 // mask = mask & maskbits
748 // for each elt
749 // n = extract mask i
750 // x = extract val n
751 // newv = insert newv, x, i
Chris Lattner2acc6e32011-07-18 04:24:23 +0000752 llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
Nate Begeman37b6a572010-06-08 00:16:34 +0000753 MTy->getNumElements());
754 Value* NewV = llvm::UndefValue::get(RTy);
755 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
Eli Friedman87b9c032012-04-05 21:48:40 +0000756 Value *IIndx = Builder.getInt32(i);
757 Value *Indx = Builder.CreateExtractElement(Mask, IIndx, "shuf_idx");
Chris Lattner77b89b82010-06-27 07:15:29 +0000758 Indx = Builder.CreateZExt(Indx, CGF.Int32Ty, "idx_zext");
Nate Begeman37b6a572010-06-08 00:16:34 +0000759
760 // Handle vec3 special since the index will be off by one for the RHS.
761 if ((LHSElts == 6) && (E->getNumSubExprs() == 3)) {
762 Value *cmpIndx, *newIndx;
Chris Lattner48431f92011-04-19 22:55:03 +0000763 cmpIndx = Builder.CreateICmpUGT(Indx, Builder.getInt32(3),
Nate Begeman37b6a572010-06-08 00:16:34 +0000764 "cmp_shuf_idx");
Chris Lattner48431f92011-04-19 22:55:03 +0000765 newIndx = Builder.CreateSub(Indx, Builder.getInt32(1), "shuf_idx_adj");
Nate Begeman37b6a572010-06-08 00:16:34 +0000766 Indx = Builder.CreateSelect(cmpIndx, newIndx, Indx, "sel_shuf_idx");
767 }
768 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
Eli Friedman87b9c032012-04-05 21:48:40 +0000769 NewV = Builder.CreateInsertElement(NewV, VExt, IIndx, "shuf_ins");
Nate Begeman37b6a572010-06-08 00:16:34 +0000770 }
771 return NewV;
Eli Friedmand38617c2008-05-14 19:38:39 +0000772 }
Nate Begeman37b6a572010-06-08 00:16:34 +0000773
Eli Friedmand38617c2008-05-14 19:38:39 +0000774 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
775 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
Nate Begeman37b6a572010-06-08 00:16:34 +0000776
777 // Handle vec3 special since the index will be off by one for the RHS.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000778 llvm::VectorType *VTy = cast<llvm::VectorType>(V1->getType());
Chris Lattner5f9e2722011-07-23 10:55:15 +0000779 SmallVector<llvm::Constant*, 32> indices;
Nate Begeman37b6a572010-06-08 00:16:34 +0000780 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
Eli Friedman0eb47fc2011-05-19 00:37:32 +0000781 unsigned Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2);
782 if (VTy->getNumElements() == 3 && Idx > 3)
783 Idx -= 1;
784 indices.push_back(Builder.getInt32(Idx));
Nate Begeman37b6a572010-06-08 00:16:34 +0000785 }
786
Chris Lattnerfb018d12011-02-15 00:14:06 +0000787 Value *SV = llvm::ConstantVector::get(indices);
Eli Friedmand38617c2008-05-14 19:38:39 +0000788 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
789}
Eli Friedman28665272009-11-26 03:22:21 +0000790Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
Richard Smith80d4b552011-12-28 19:48:30 +0000791 llvm::APSInt Value;
792 if (E->EvaluateAsInt(Value, CGF.getContext(), Expr::SE_AllowSideEffects)) {
Eli Friedman28665272009-11-26 03:22:21 +0000793 if (E->isArrow())
794 CGF.EmitScalarExpr(E->getBase());
795 else
796 EmitLValue(E->getBase());
Richard Smith80d4b552011-12-28 19:48:30 +0000797 return Builder.getInt(Value);
Eli Friedman28665272009-11-26 03:22:21 +0000798 }
Devang Patel78ba3d42010-10-04 21:46:04 +0000799
Alexey Samsonov3a70cd62012-04-27 07:24:20 +0000800 // Emit debug info for aggregate now, if it was delayed to reduce
Devang Patel78ba3d42010-10-04 21:46:04 +0000801 // debug info size.
802 CGDebugInfo *DI = CGF.getDebugInfo();
Alexey Samsonov3a70cd62012-04-27 07:24:20 +0000803 if (DI &&
804 CGF.CGM.getCodeGenOpts().DebugInfo == CodeGenOptions::LimitedDebugInfo) {
Devang Patel78ba3d42010-10-04 21:46:04 +0000805 QualType PQTy = E->getBase()->IgnoreParenImpCasts()->getType();
806 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy))
Devang Patel49c84652010-10-04 22:28:23 +0000807 if (FieldDecl *M = dyn_cast<FieldDecl>(E->getMemberDecl()))
Alexey Samsonov3a70cd62012-04-27 07:24:20 +0000808 DI->getOrCreateRecordType(PTy->getPointeeType(),
Devang Patel78ba3d42010-10-04 21:46:04 +0000809 M->getParent()->getLocation());
Devang Patel7fa8ab22010-10-04 22:13:18 +0000810 }
Eli Friedman28665272009-11-26 03:22:21 +0000811 return EmitLoadOfLValue(E);
812}
Eli Friedmand38617c2008-05-14 19:38:39 +0000813
Chris Lattner7f02f722007-08-24 05:35:26 +0000814Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000815 TestAndClearIgnoreResultAssign();
816
Chris Lattner7f02f722007-08-24 05:35:26 +0000817 // Emit subscript expressions in rvalue context's. For most cases, this just
818 // loads the lvalue formed by the subscript expr. However, we have to be
819 // careful, because the base of a vector subscript is occasionally an rvalue,
820 // so we can't get it as an lvalue.
821 if (!E->getBase()->getType()->isVectorType())
822 return EmitLoadOfLValue(E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000823
Chris Lattner7f02f722007-08-24 05:35:26 +0000824 // Handle the vector case. The base must be a vector, the index must be an
825 // integer value.
826 Value *Base = Visit(E->getBase());
827 Value *Idx = Visit(E->getIdx());
Douglas Gregor575a1c92011-05-20 16:38:50 +0000828 bool IdxSigned = E->getIdx()->getType()->isSignedIntegerOrEnumerationType();
Chris Lattner77b89b82010-06-27 07:15:29 +0000829 Idx = Builder.CreateIntCast(Idx, CGF.Int32Ty, IdxSigned, "vecidxcast");
Chris Lattner7f02f722007-08-24 05:35:26 +0000830 return Builder.CreateExtractElement(Base, Idx, "vecext");
831}
832
Nate Begeman0533b302009-10-18 20:10:40 +0000833static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
Chris Lattner2acc6e32011-07-18 04:24:23 +0000834 unsigned Off, llvm::Type *I32Ty) {
Nate Begeman0533b302009-10-18 20:10:40 +0000835 int MV = SVI->getMaskValue(Idx);
836 if (MV == -1)
837 return llvm::UndefValue::get(I32Ty);
838 return llvm::ConstantInt::get(I32Ty, Off+MV);
839}
840
841Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
842 bool Ignore = TestAndClearIgnoreResultAssign();
843 (void)Ignore;
844 assert (Ignore == false && "init list ignored");
845 unsigned NumInitElements = E->getNumInits();
846
847 if (E->hadArrayRangeDesignator())
848 CGF.ErrorUnsupported(E, "GNU array range designator extension");
849
Chris Lattner2acc6e32011-07-18 04:24:23 +0000850 llvm::VectorType *VType =
Nate Begeman0533b302009-10-18 20:10:40 +0000851 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
852
Sebastian Redlcea8d962011-09-24 17:48:14 +0000853 if (!VType) {
854 if (NumInitElements == 0) {
855 // C++11 value-initialization for the scalar.
856 return EmitNullValue(E->getType());
857 }
858 // We have a scalar in braces. Just use the first element.
Nate Begeman0533b302009-10-18 20:10:40 +0000859 return Visit(E->getInit(0));
Sebastian Redlcea8d962011-09-24 17:48:14 +0000860 }
Nate Begeman0533b302009-10-18 20:10:40 +0000861
862 unsigned ResElts = VType->getNumElements();
Nate Begeman0533b302009-10-18 20:10:40 +0000863
864 // Loop over initializers collecting the Value for each, and remembering
865 // whether the source was swizzle (ExtVectorElementExpr). This will allow
866 // us to fold the shuffle for the swizzle into the shuffle for the vector
867 // initializer, since LLVM optimizers generally do not want to touch
868 // shuffles.
869 unsigned CurIdx = 0;
870 bool VIsUndefShuffle = false;
871 llvm::Value *V = llvm::UndefValue::get(VType);
872 for (unsigned i = 0; i != NumInitElements; ++i) {
873 Expr *IE = E->getInit(i);
874 Value *Init = Visit(IE);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000875 SmallVector<llvm::Constant*, 16> Args;
Nate Begeman0533b302009-10-18 20:10:40 +0000876
Chris Lattner2acc6e32011-07-18 04:24:23 +0000877 llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
Nate Begeman0533b302009-10-18 20:10:40 +0000878
879 // Handle scalar elements. If the scalar initializer is actually one
880 // element of a different vector of the same width, use shuffle instead of
881 // extract+insert.
882 if (!VVT) {
883 if (isa<ExtVectorElementExpr>(IE)) {
884 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
885
886 if (EI->getVectorOperandType()->getNumElements() == ResElts) {
887 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
888 Value *LHS = 0, *RHS = 0;
889 if (CurIdx == 0) {
890 // insert into undef -> shuffle (src, undef)
891 Args.push_back(C);
Benjamin Kramer14c59822012-02-14 12:06:21 +0000892 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000893
894 LHS = EI->getVectorOperand();
895 RHS = V;
896 VIsUndefShuffle = true;
897 } else if (VIsUndefShuffle) {
898 // insert into undefshuffle && size match -> shuffle (v, src)
899 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
900 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000901 Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
Chris Lattner48431f92011-04-19 22:55:03 +0000902 Args.push_back(Builder.getInt32(ResElts + C->getZExtValue()));
Benjamin Kramer14c59822012-02-14 12:06:21 +0000903 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
904
Nate Begeman0533b302009-10-18 20:10:40 +0000905 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
906 RHS = EI->getVectorOperand();
907 VIsUndefShuffle = false;
908 }
909 if (!Args.empty()) {
Chris Lattnerfb018d12011-02-15 00:14:06 +0000910 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +0000911 V = Builder.CreateShuffleVector(LHS, RHS, Mask);
912 ++CurIdx;
913 continue;
914 }
915 }
916 }
Chris Lattner48431f92011-04-19 22:55:03 +0000917 V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx),
918 "vecinit");
Nate Begeman0533b302009-10-18 20:10:40 +0000919 VIsUndefShuffle = false;
920 ++CurIdx;
921 continue;
922 }
923
924 unsigned InitElts = VVT->getNumElements();
925
926 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
927 // input is the same width as the vector being constructed, generate an
928 // optimized shuffle of the swizzle input into the result.
Nate Begemana99f0832009-10-25 02:26:01 +0000929 unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
Nate Begeman0533b302009-10-18 20:10:40 +0000930 if (isa<ExtVectorElementExpr>(IE)) {
931 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
932 Value *SVOp = SVI->getOperand(0);
Chris Lattner2acc6e32011-07-18 04:24:23 +0000933 llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
Nate Begeman0533b302009-10-18 20:10:40 +0000934
935 if (OpTy->getNumElements() == ResElts) {
Nate Begeman0533b302009-10-18 20:10:40 +0000936 for (unsigned j = 0; j != CurIdx; ++j) {
937 // If the current vector initializer is a shuffle with undef, merge
938 // this shuffle directly into it.
939 if (VIsUndefShuffle) {
940 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
Chris Lattner77b89b82010-06-27 07:15:29 +0000941 CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000942 } else {
Chris Lattner48431f92011-04-19 22:55:03 +0000943 Args.push_back(Builder.getInt32(j));
Nate Begeman0533b302009-10-18 20:10:40 +0000944 }
945 }
946 for (unsigned j = 0, je = InitElts; j != je; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000947 Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
Benjamin Kramer14c59822012-02-14 12:06:21 +0000948 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000949
950 if (VIsUndefShuffle)
951 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
952
953 Init = SVOp;
954 }
955 }
956
957 // Extend init to result vector length, and then shuffle its contribution
958 // to the vector initializer into V.
959 if (Args.empty()) {
960 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner48431f92011-04-19 22:55:03 +0000961 Args.push_back(Builder.getInt32(j));
Benjamin Kramer14c59822012-02-14 12:06:21 +0000962 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Chris Lattnerfb018d12011-02-15 00:14:06 +0000963 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +0000964 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
Nate Begemana99f0832009-10-25 02:26:01 +0000965 Mask, "vext");
Nate Begeman0533b302009-10-18 20:10:40 +0000966
967 Args.clear();
968 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner48431f92011-04-19 22:55:03 +0000969 Args.push_back(Builder.getInt32(j));
Nate Begeman0533b302009-10-18 20:10:40 +0000970 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner48431f92011-04-19 22:55:03 +0000971 Args.push_back(Builder.getInt32(j+Offset));
Benjamin Kramer14c59822012-02-14 12:06:21 +0000972 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000973 }
974
975 // If V is undef, make sure it ends up on the RHS of the shuffle to aid
976 // merging subsequent shuffles into this one.
977 if (CurIdx == 0)
978 std::swap(V, Init);
Chris Lattnerfb018d12011-02-15 00:14:06 +0000979 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +0000980 V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
981 VIsUndefShuffle = isa<llvm::UndefValue>(Init);
982 CurIdx += InitElts;
983 }
984
985 // FIXME: evaluate codegen vs. shuffling against constant null vector.
986 // Emit remaining default initializers.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000987 llvm::Type *EltTy = VType->getElementType();
Nate Begeman0533b302009-10-18 20:10:40 +0000988
989 // Emit remaining default initializers
990 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
Chris Lattner48431f92011-04-19 22:55:03 +0000991 Value *Idx = Builder.getInt32(CurIdx);
Nate Begeman0533b302009-10-18 20:10:40 +0000992 llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
993 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
994 }
995 return V;
996}
997
Anders Carlssona3697c92009-11-23 17:57:54 +0000998static bool ShouldNullCheckClassCastValue(const CastExpr *CE) {
999 const Expr *E = CE->getSubExpr();
John McCall23cba802010-03-30 23:58:03 +00001000
John McCall2de56d12010-08-25 11:45:40 +00001001 if (CE->getCastKind() == CK_UncheckedDerivedToBase)
John McCall23cba802010-03-30 23:58:03 +00001002 return false;
Anders Carlssona3697c92009-11-23 17:57:54 +00001003
1004 if (isa<CXXThisExpr>(E)) {
1005 // We always assume that 'this' is never null.
1006 return false;
1007 }
1008
1009 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00001010 // And that glvalue casts are never null.
John McCall5baba9d2010-08-25 10:28:54 +00001011 if (ICE->getValueKind() != VK_RValue)
Anders Carlssona3697c92009-11-23 17:57:54 +00001012 return false;
1013 }
1014
1015 return true;
1016}
1017
Chris Lattner7f02f722007-08-24 05:35:26 +00001018// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
1019// have to handle a more broad range of conversions than explicit casts, as they
1020// handle things like function to ptr-to-function decay etc.
John McCallbc8d40d2011-06-24 21:55:10 +00001021Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
Eli Friedmand8889622009-11-27 04:41:50 +00001022 Expr *E = CE->getSubExpr();
Anders Carlsson592a2bb2009-09-22 22:00:46 +00001023 QualType DestTy = CE->getType();
John McCall2de56d12010-08-25 11:45:40 +00001024 CastKind Kind = CE->getCastKind();
Anders Carlsson592a2bb2009-09-22 22:00:46 +00001025
Mike Stump7f79f9b2009-05-29 15:46:01 +00001026 if (!DestTy->isVoidType())
1027 TestAndClearIgnoreResultAssign();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001028
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001029 // Since almost all cast kinds apply to scalars, this switch doesn't have
1030 // a default case, so the compiler will warn on a missing case. The cases
1031 // are in the same order as in the CastKind enum.
Anders Carlssone9776242009-08-24 18:26:39 +00001032 switch (Kind) {
John McCalldaa8e4e2010-11-15 09:13:47 +00001033 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001034 case CK_BuiltinFnToFnPtr:
1035 llvm_unreachable("builtin functions are handled elsewhere");
1036
John McCall2de56d12010-08-25 11:45:40 +00001037 case CK_LValueBitCast:
1038 case CK_ObjCObjectLValueCast: {
Douglas Gregore39a3892010-07-13 23:17:26 +00001039 Value *V = EmitLValue(E).getAddress();
1040 V = Builder.CreateBitCast(V,
1041 ConvertType(CGF.getContext().getPointerType(DestTy)));
Eli Friedmand71f4422011-12-19 23:03:09 +00001042 return EmitLoadOfLValue(CGF.MakeNaturalAlignAddrLValue(V, DestTy));
Douglas Gregore39a3892010-07-13 23:17:26 +00001043 }
John McCalldc05b112011-09-10 01:16:55 +00001044
John McCall1d9b3b22011-09-09 05:25:32 +00001045 case CK_CPointerToObjCPointerCast:
1046 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00001047 case CK_AnyPointerToBlockPointerCast:
1048 case CK_BitCast: {
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001049 Value *Src = Visit(const_cast<Expr*>(E));
1050 return Builder.CreateBitCast(Src, ConvertType(DestTy));
1051 }
David Chisnall7a7ee302012-01-16 17:27:18 +00001052 case CK_AtomicToNonAtomic:
1053 case CK_NonAtomicToAtomic:
John McCall2de56d12010-08-25 11:45:40 +00001054 case CK_NoOp:
1055 case CK_UserDefinedConversion:
Eli Friedmanad35a832009-11-16 21:33:53 +00001056 return Visit(const_cast<Expr*>(E));
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001057
John McCall2de56d12010-08-25 11:45:40 +00001058 case CK_BaseToDerived: {
Anders Carlssona3697c92009-11-23 17:57:54 +00001059 const CXXRecordDecl *DerivedClassDecl =
1060 DestTy->getCXXRecordDeclForPointerType();
1061
Anders Carlssona04efdf2010-04-24 21:23:59 +00001062 return CGF.GetAddressOfDerivedClass(Visit(E), DerivedClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +00001063 CE->path_begin(), CE->path_end(),
Anders Carlssona04efdf2010-04-24 21:23:59 +00001064 ShouldNullCheckClassCastValue(CE));
Anders Carlssona3697c92009-11-23 17:57:54 +00001065 }
John McCall2de56d12010-08-25 11:45:40 +00001066 case CK_UncheckedDerivedToBase:
1067 case CK_DerivedToBase: {
Anders Carlsson191dfe92009-09-12 04:57:16 +00001068 const RecordType *DerivedClassTy =
1069 E->getType()->getAs<PointerType>()->getPointeeType()->getAs<RecordType>();
1070 CXXRecordDecl *DerivedClassDecl =
1071 cast<CXXRecordDecl>(DerivedClassTy->getDecl());
1072
Anders Carlsson34a2d382010-04-24 21:06:20 +00001073 return CGF.GetAddressOfBaseClass(Visit(E), DerivedClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +00001074 CE->path_begin(), CE->path_end(),
Anders Carlsson34a2d382010-04-24 21:06:20 +00001075 ShouldNullCheckClassCastValue(CE));
Anders Carlsson191dfe92009-09-12 04:57:16 +00001076 }
Anders Carlsson575b3742011-04-11 02:03:26 +00001077 case CK_Dynamic: {
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001078 Value *V = Visit(const_cast<Expr*>(E));
1079 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
1080 return CGF.EmitDynamicCast(V, DCE);
1081 }
Eli Friedmand8889622009-11-27 04:41:50 +00001082
John McCall2de56d12010-08-25 11:45:40 +00001083 case CK_ArrayToPointerDecay: {
Eli Friedmanad35a832009-11-16 21:33:53 +00001084 assert(E->getType()->isArrayType() &&
1085 "Array to pointer decay must have array source type!");
1086
1087 Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
1088
1089 // Note that VLA pointers are always decayed, so we don't need to do
1090 // anything here.
1091 if (!E->getType()->isVariableArrayType()) {
1092 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
1093 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
1094 ->getElementType()) &&
1095 "Expected pointer to array");
1096 V = Builder.CreateStructGEP(V, 0, "arraydecay");
1097 }
1098
Chris Lattner410b12e2011-07-20 04:31:01 +00001099 // Make sure the array decay ends up being the right type. This matters if
1100 // the array type was of an incomplete type.
Chris Lattnercb8095f2011-07-20 04:59:57 +00001101 return CGF.Builder.CreateBitCast(V, ConvertType(CE->getType()));
Eli Friedmanad35a832009-11-16 21:33:53 +00001102 }
John McCall2de56d12010-08-25 11:45:40 +00001103 case CK_FunctionToPointerDecay:
Eli Friedmanad35a832009-11-16 21:33:53 +00001104 return EmitLValue(E).getAddress();
1105
John McCall404cd162010-11-13 01:35:44 +00001106 case CK_NullToPointer:
1107 if (MustVisitNullValue(E))
1108 (void) Visit(E);
1109
1110 return llvm::ConstantPointerNull::get(
1111 cast<llvm::PointerType>(ConvertType(DestTy)));
1112
John McCall2de56d12010-08-25 11:45:40 +00001113 case CK_NullToMemberPointer: {
John McCall404cd162010-11-13 01:35:44 +00001114 if (MustVisitNullValue(E))
John McCalld608cdb2010-08-22 10:59:02 +00001115 (void) Visit(E);
1116
John McCall0bab0cd2010-08-23 01:21:21 +00001117 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
1118 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
1119 }
Anders Carlsson191dfe92009-09-12 04:57:16 +00001120
John McCall4d4e5c12012-02-15 01:22:51 +00001121 case CK_ReinterpretMemberPointer:
John McCall2de56d12010-08-25 11:45:40 +00001122 case CK_BaseToDerivedMemberPointer:
1123 case CK_DerivedToBaseMemberPointer: {
Eli Friedmand8889622009-11-27 04:41:50 +00001124 Value *Src = Visit(E);
John McCalld608cdb2010-08-22 10:59:02 +00001125
1126 // Note that the AST doesn't distinguish between checked and
1127 // unchecked member pointer conversions, so we always have to
1128 // implement checked conversions here. This is inefficient when
1129 // actual control flow may be required in order to perform the
1130 // check, which it is for data member pointers (but not member
1131 // function pointers on Itanium and ARM).
John McCall0bab0cd2010-08-23 01:21:21 +00001132 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
Eli Friedmand8889622009-11-27 04:41:50 +00001133 }
John McCallf85e1932011-06-15 23:02:42 +00001134
John McCall33e56f32011-09-10 06:18:15 +00001135 case CK_ARCProduceObject:
John McCallf85e1932011-06-15 23:02:42 +00001136 return CGF.EmitARCRetainScalarExpr(E);
John McCall33e56f32011-09-10 06:18:15 +00001137 case CK_ARCConsumeObject:
John McCallf85e1932011-06-15 23:02:42 +00001138 return CGF.EmitObjCConsumeObject(E->getType(), Visit(E));
John McCall33e56f32011-09-10 06:18:15 +00001139 case CK_ARCReclaimReturnedObject: {
John McCall7e5e5f42011-07-07 06:58:02 +00001140 llvm::Value *value = Visit(E);
1141 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
1142 return CGF.EmitObjCConsumeObject(E->getType(), value);
1143 }
John McCall348f16f2011-10-04 06:23:45 +00001144 case CK_ARCExtendBlockObject:
1145 return CGF.EmitARCExtendBlockObject(E);
John McCallf85e1932011-06-15 23:02:42 +00001146
Douglas Gregorac1303e2012-02-22 05:02:47 +00001147 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedmancae40c42012-02-28 01:08:45 +00001148 return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType());
Douglas Gregorac1303e2012-02-22 05:02:47 +00001149
John McCall2bb5d002010-11-13 09:02:35 +00001150 case CK_FloatingRealToComplex:
1151 case CK_FloatingComplexCast:
1152 case CK_IntegralRealToComplex:
1153 case CK_IntegralComplexCast:
John McCallf3ea8cf2010-11-14 08:17:51 +00001154 case CK_IntegralComplexToFloatingComplex:
1155 case CK_FloatingComplexToIntegralComplex:
John McCall2de56d12010-08-25 11:45:40 +00001156 case CK_ConstructorConversion:
John McCall61ad0e62010-11-16 06:21:14 +00001157 case CK_ToUnion:
1158 llvm_unreachable("scalar cast to non-scalar value");
John McCallf6a16482010-12-04 03:47:34 +00001159
John McCall0ae287a2010-12-01 04:43:34 +00001160 case CK_LValueToRValue:
1161 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
John McCallf6a16482010-12-04 03:47:34 +00001162 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
John McCall0ae287a2010-12-01 04:43:34 +00001163 return Visit(const_cast<Expr*>(E));
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001164
John McCall2de56d12010-08-25 11:45:40 +00001165 case CK_IntegralToPointer: {
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001166 Value *Src = Visit(const_cast<Expr*>(E));
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001167
Anders Carlsson82debc72009-10-18 18:12:03 +00001168 // First, convert to the correct width so that we control the kind of
1169 // extension.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001170 llvm::Type *MiddleTy = CGF.IntPtrTy;
Douglas Gregor575a1c92011-05-20 16:38:50 +00001171 bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
Anders Carlsson82debc72009-10-18 18:12:03 +00001172 llvm::Value* IntResult =
1173 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001174
Anders Carlsson82debc72009-10-18 18:12:03 +00001175 return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy));
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001176 }
Eli Friedman65949422011-06-25 02:58:47 +00001177 case CK_PointerToIntegral:
1178 assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
1179 return Builder.CreatePtrToInt(Visit(E), ConvertType(DestTy));
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001180
John McCall2de56d12010-08-25 11:45:40 +00001181 case CK_ToVoid: {
John McCall2a416372010-12-05 02:00:02 +00001182 CGF.EmitIgnoredExpr(E);
Eli Friedmanad35a832009-11-16 21:33:53 +00001183 return 0;
1184 }
John McCall2de56d12010-08-25 11:45:40 +00001185 case CK_VectorSplat: {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001186 llvm::Type *DstTy = ConvertType(DestTy);
Eli Friedmanad35a832009-11-16 21:33:53 +00001187 Value *Elt = Visit(const_cast<Expr*>(E));
Craig Topper5fa56082012-02-06 05:05:50 +00001188 Elt = EmitScalarConversion(Elt, E->getType(),
1189 DestTy->getAs<VectorType>()->getElementType());
Eli Friedmanad35a832009-11-16 21:33:53 +00001190
1191 // Insert the element in element zero of an undef vector
1192 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
Chris Lattner48431f92011-04-19 22:55:03 +00001193 llvm::Value *Idx = Builder.getInt32(0);
Benjamin Kramer578faa82011-09-27 21:06:10 +00001194 UnV = Builder.CreateInsertElement(UnV, Elt, Idx);
Eli Friedmanad35a832009-11-16 21:33:53 +00001195
1196 // Splat the element across to all elements
Eli Friedmanad35a832009-11-16 21:33:53 +00001197 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
Chris Lattner48431f92011-04-19 22:55:03 +00001198 llvm::Constant *Zero = Builder.getInt32(0);
Chris Lattner2ce88422012-01-25 05:34:41 +00001199 llvm::Constant *Mask = llvm::ConstantVector::getSplat(NumElements, Zero);
Eli Friedmanad35a832009-11-16 21:33:53 +00001200 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
1201 return Yay;
1202 }
John McCalldaa8e4e2010-11-15 09:13:47 +00001203
John McCall2de56d12010-08-25 11:45:40 +00001204 case CK_IntegralCast:
1205 case CK_IntegralToFloating:
1206 case CK_FloatingToIntegral:
1207 case CK_FloatingCast:
Eli Friedmand8889622009-11-27 04:41:50 +00001208 return EmitScalarConversion(Visit(E), E->getType(), DestTy);
John McCalldaa8e4e2010-11-15 09:13:47 +00001209 case CK_IntegralToBoolean:
1210 return EmitIntToBoolConversion(Visit(E));
1211 case CK_PointerToBoolean:
1212 return EmitPointerToBoolConversion(Visit(E));
1213 case CK_FloatingToBoolean:
1214 return EmitFloatToBoolConversion(Visit(E));
John McCall2de56d12010-08-25 11:45:40 +00001215 case CK_MemberPointerToBoolean: {
John McCall0bab0cd2010-08-23 01:21:21 +00001216 llvm::Value *MemPtr = Visit(E);
1217 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
1218 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
Anders Carlssone9776242009-08-24 18:26:39 +00001219 }
John McCallf3ea8cf2010-11-14 08:17:51 +00001220
1221 case CK_FloatingComplexToReal:
1222 case CK_IntegralComplexToReal:
John McCallb418d742010-11-16 10:08:07 +00001223 return CGF.EmitComplexExpr(E, false, true).first;
John McCallf3ea8cf2010-11-14 08:17:51 +00001224
1225 case CK_FloatingComplexToBoolean:
1226 case CK_IntegralComplexToBoolean: {
John McCallb418d742010-11-16 10:08:07 +00001227 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
John McCallf3ea8cf2010-11-14 08:17:51 +00001228
1229 // TODO: kill this function off, inline appropriate case here
1230 return EmitComplexToScalarConversion(V, E->getType(), DestTy);
1231 }
1232
John McCall0bab0cd2010-08-23 01:21:21 +00001233 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001234
John McCall61ad0e62010-11-16 06:21:14 +00001235 llvm_unreachable("unknown scalar cast");
Chris Lattner7f02f722007-08-24 05:35:26 +00001236}
1237
Chris Lattner33793202007-08-31 22:09:40 +00001238Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
John McCall150b4622011-01-26 04:00:11 +00001239 CodeGenFunction::StmtExprEvaluation eval(CGF);
1240 return CGF.EmitCompoundStmt(*E->getSubStmt(), !E->getType()->isVoidType())
1241 .getScalarVal();
Chris Lattner33793202007-08-31 22:09:40 +00001242}
1243
Chris Lattner7f02f722007-08-24 05:35:26 +00001244//===----------------------------------------------------------------------===//
1245// Unary Operators
1246//===----------------------------------------------------------------------===//
1247
Chris Lattner8c11a652010-06-26 22:09:34 +00001248llvm::Value *ScalarExprEmitter::
Anton Yartsev683564a2011-02-07 02:17:30 +00001249EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
1250 llvm::Value *InVal,
1251 llvm::Value *NextVal, bool IsInc) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001252 switch (CGF.getContext().getLangOpts().getSignedOverflowBehavior()) {
Anton Yartsev683564a2011-02-07 02:17:30 +00001253 case LangOptions::SOB_Defined:
1254 return Builder.CreateAdd(InVal, NextVal, IsInc ? "inc" : "dec");
Richard Smith9d3e2262012-08-25 00:32:28 +00001255 case LangOptions::SOB_Undefined:
1256 if (!CGF.CatchUndefined)
1257 return Builder.CreateNSWAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1258 // Fall through.
Anton Yartsev683564a2011-02-07 02:17:30 +00001259 case LangOptions::SOB_Trapping:
1260 BinOpInfo BinOp;
1261 BinOp.LHS = InVal;
1262 BinOp.RHS = NextVal;
1263 BinOp.Ty = E->getType();
1264 BinOp.Opcode = BO_Add;
1265 BinOp.E = E;
1266 return EmitOverflowCheckedBinOp(BinOp);
Anton Yartsev683564a2011-02-07 02:17:30 +00001267 }
David Blaikieb219cfc2011-09-23 05:06:16 +00001268 llvm_unreachable("Unknown SignedOverflowBehaviorTy");
Anton Yartsev683564a2011-02-07 02:17:30 +00001269}
1270
John McCall5936e332011-02-15 09:22:45 +00001271llvm::Value *
1272ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1273 bool isInc, bool isPre) {
Chris Lattner8c11a652010-06-26 22:09:34 +00001274
John McCall5936e332011-02-15 09:22:45 +00001275 QualType type = E->getSubExpr()->getType();
John McCall545d9962011-06-25 02:11:03 +00001276 llvm::Value *value = EmitLoadOfLValue(LV);
John McCall5936e332011-02-15 09:22:45 +00001277 llvm::Value *input = value;
David Chisnall7a7ee302012-01-16 17:27:18 +00001278 llvm::PHINode *atomicPHI = 0;
Anton Yartsev683564a2011-02-07 02:17:30 +00001279
John McCall5936e332011-02-15 09:22:45 +00001280 int amount = (isInc ? 1 : -1);
1281
David Chisnall7a7ee302012-01-16 17:27:18 +00001282 if (const AtomicType *atomicTy = type->getAs<AtomicType>()) {
1283 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
1284 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
1285 Builder.CreateBr(opBB);
1286 Builder.SetInsertPoint(opBB);
1287 atomicPHI = Builder.CreatePHI(value->getType(), 2);
1288 atomicPHI->addIncoming(value, startBB);
1289 type = atomicTy->getValueType();
1290 value = atomicPHI;
1291 }
1292
John McCall5936e332011-02-15 09:22:45 +00001293 // Special case of integer increment that we have to check first: bool++.
1294 // Due to promotion rules, we get:
1295 // bool++ -> bool = bool + 1
1296 // -> bool = (int)bool + 1
1297 // -> bool = ((int)bool + 1 != 0)
1298 // An interesting aspect of this is that increment is always true.
1299 // Decrement does not have this property.
1300 if (isInc && type->isBooleanType()) {
1301 value = Builder.getTrue();
1302
1303 // Most common case by far: integer increment.
1304 } else if (type->isIntegerType()) {
1305
Michael Liao36d5cea2012-08-28 16:55:13 +00001306 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount, true);
John McCall5936e332011-02-15 09:22:45 +00001307
Eli Friedmanfa0b4092011-03-02 01:49:12 +00001308 // Note that signed integer inc/dec with width less than int can't
1309 // overflow because of promotion rules; we're just eliding a few steps here.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001310 if (type->isSignedIntegerOrEnumerationType() &&
Eli Friedmanfa0b4092011-03-02 01:49:12 +00001311 value->getType()->getPrimitiveSizeInBits() >=
John McCall913dab22011-06-25 01:32:37 +00001312 CGF.IntTy->getBitWidth())
John McCall5936e332011-02-15 09:22:45 +00001313 value = EmitAddConsiderOverflowBehavior(E, value, amt, isInc);
John McCall5936e332011-02-15 09:22:45 +00001314 else
1315 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1316
1317 // Next most common: pointer increment.
1318 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
1319 QualType type = ptr->getPointeeType();
1320
1321 // VLA types don't have constant size.
John McCall913dab22011-06-25 01:32:37 +00001322 if (const VariableArrayType *vla
1323 = CGF.getContext().getAsVariableArrayType(type)) {
1324 llvm::Value *numElts = CGF.getVLASize(vla).first;
John McCallbc8d40d2011-06-24 21:55:10 +00001325 if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize");
David Blaikie4e4d0842012-03-11 07:00:24 +00001326 if (CGF.getContext().getLangOpts().isSignedOverflowDefined())
John McCallbc8d40d2011-06-24 21:55:10 +00001327 value = Builder.CreateGEP(value, numElts, "vla.inc");
Chris Lattner2cb42222011-03-01 00:03:48 +00001328 else
John McCallbc8d40d2011-06-24 21:55:10 +00001329 value = Builder.CreateInBoundsGEP(value, numElts, "vla.inc");
John McCall5936e332011-02-15 09:22:45 +00001330
1331 // Arithmetic on function pointers (!) is just +-1.
1332 } else if (type->isFunctionType()) {
Chris Lattner48431f92011-04-19 22:55:03 +00001333 llvm::Value *amt = Builder.getInt32(amount);
John McCall5936e332011-02-15 09:22:45 +00001334
1335 value = CGF.EmitCastToVoidPtr(value);
David Blaikie4e4d0842012-03-11 07:00:24 +00001336 if (CGF.getContext().getLangOpts().isSignedOverflowDefined())
Chris Lattner2cb42222011-03-01 00:03:48 +00001337 value = Builder.CreateGEP(value, amt, "incdec.funcptr");
1338 else
1339 value = Builder.CreateInBoundsGEP(value, amt, "incdec.funcptr");
John McCall5936e332011-02-15 09:22:45 +00001340 value = Builder.CreateBitCast(value, input->getType());
1341
1342 // For everything else, we can just do a simple increment.
Anton Yartsev683564a2011-02-07 02:17:30 +00001343 } else {
Chris Lattner48431f92011-04-19 22:55:03 +00001344 llvm::Value *amt = Builder.getInt32(amount);
David Blaikie4e4d0842012-03-11 07:00:24 +00001345 if (CGF.getContext().getLangOpts().isSignedOverflowDefined())
Chris Lattner2cb42222011-03-01 00:03:48 +00001346 value = Builder.CreateGEP(value, amt, "incdec.ptr");
1347 else
1348 value = Builder.CreateInBoundsGEP(value, amt, "incdec.ptr");
John McCall5936e332011-02-15 09:22:45 +00001349 }
1350
1351 // Vector increment/decrement.
1352 } else if (type->isVectorType()) {
1353 if (type->hasIntegerRepresentation()) {
1354 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1355
Eli Friedmand4b9ee32011-05-06 18:04:18 +00001356 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
John McCall5936e332011-02-15 09:22:45 +00001357 } else {
1358 value = Builder.CreateFAdd(
1359 value,
1360 llvm::ConstantFP::get(value->getType(), amount),
Anton Yartsev683564a2011-02-07 02:17:30 +00001361 isInc ? "inc" : "dec");
1362 }
Anton Yartsev683564a2011-02-07 02:17:30 +00001363
John McCall5936e332011-02-15 09:22:45 +00001364 // Floating point.
1365 } else if (type->isRealFloatingType()) {
Chris Lattner8c11a652010-06-26 22:09:34 +00001366 // Add the inc/dec to the real part.
John McCall5936e332011-02-15 09:22:45 +00001367 llvm::Value *amt;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001368
1369 if (type->isHalfType()) {
1370 // Another special case: half FP increment should be done via float
1371 value =
1372 Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16),
1373 input);
1374 }
1375
John McCall5936e332011-02-15 09:22:45 +00001376 if (value->getType()->isFloatTy())
1377 amt = llvm::ConstantFP::get(VMContext,
1378 llvm::APFloat(static_cast<float>(amount)));
1379 else if (value->getType()->isDoubleTy())
1380 amt = llvm::ConstantFP::get(VMContext,
1381 llvm::APFloat(static_cast<double>(amount)));
Chris Lattner8c11a652010-06-26 22:09:34 +00001382 else {
John McCall5936e332011-02-15 09:22:45 +00001383 llvm::APFloat F(static_cast<float>(amount));
Chris Lattner8c11a652010-06-26 22:09:34 +00001384 bool ignored;
1385 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
1386 &ignored);
John McCall5936e332011-02-15 09:22:45 +00001387 amt = llvm::ConstantFP::get(VMContext, F);
Chris Lattner8c11a652010-06-26 22:09:34 +00001388 }
John McCall5936e332011-02-15 09:22:45 +00001389 value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
1390
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001391 if (type->isHalfType())
1392 value =
1393 Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16),
1394 value);
1395
John McCall5936e332011-02-15 09:22:45 +00001396 // Objective-C pointer types.
1397 } else {
1398 const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
1399 value = CGF.EmitCastToVoidPtr(value);
1400
1401 CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
1402 if (!isInc) size = -size;
1403 llvm::Value *sizeValue =
1404 llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
1405
David Blaikie4e4d0842012-03-11 07:00:24 +00001406 if (CGF.getContext().getLangOpts().isSignedOverflowDefined())
Chris Lattner2cb42222011-03-01 00:03:48 +00001407 value = Builder.CreateGEP(value, sizeValue, "incdec.objptr");
1408 else
1409 value = Builder.CreateInBoundsGEP(value, sizeValue, "incdec.objptr");
John McCall5936e332011-02-15 09:22:45 +00001410 value = Builder.CreateBitCast(value, input->getType());
Chris Lattner8c11a652010-06-26 22:09:34 +00001411 }
David Chisnall7a7ee302012-01-16 17:27:18 +00001412
1413 if (atomicPHI) {
1414 llvm::BasicBlock *opBB = Builder.GetInsertBlock();
1415 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
1416 llvm::Value *old = Builder.CreateAtomicCmpXchg(LV.getAddress(), atomicPHI,
1417 value, llvm::SequentiallyConsistent);
1418 atomicPHI->addIncoming(old, opBB);
1419 llvm::Value *success = Builder.CreateICmpEQ(old, atomicPHI);
1420 Builder.CreateCondBr(success, contBB, opBB);
1421 Builder.SetInsertPoint(contBB);
1422 return isPre ? value : input;
1423 }
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001424
Chris Lattner8c11a652010-06-26 22:09:34 +00001425 // Store the updated result through the lvalue.
1426 if (LV.isBitField())
John McCall545d9962011-06-25 02:11:03 +00001427 CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
Chris Lattner8c11a652010-06-26 22:09:34 +00001428 else
John McCall545d9962011-06-25 02:11:03 +00001429 CGF.EmitStoreThroughLValue(RValue::get(value), LV);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001430
Chris Lattner8c11a652010-06-26 22:09:34 +00001431 // If this is a postinc, return the value read from memory, otherwise use the
1432 // updated value.
John McCall5936e332011-02-15 09:22:45 +00001433 return isPre ? value : input;
Chris Lattner8c11a652010-06-26 22:09:34 +00001434}
1435
1436
1437
Chris Lattner7f02f722007-08-24 05:35:26 +00001438Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001439 TestAndClearIgnoreResultAssign();
Chris Lattner9a207232010-06-26 21:48:21 +00001440 // Emit unary minus with EmitSub so we handle overflow cases etc.
1441 BinOpInfo BinOp;
Chris Lattner4ac0d832010-06-28 17:12:37 +00001442 BinOp.RHS = Visit(E->getSubExpr());
1443
1444 if (BinOp.RHS->getType()->isFPOrFPVectorTy())
1445 BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
1446 else
1447 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
Chris Lattner9a207232010-06-26 21:48:21 +00001448 BinOp.Ty = E->getType();
John McCall2de56d12010-08-25 11:45:40 +00001449 BinOp.Opcode = BO_Sub;
Chris Lattner9a207232010-06-26 21:48:21 +00001450 BinOp.E = E;
1451 return EmitSub(BinOp);
Chris Lattner7f02f722007-08-24 05:35:26 +00001452}
1453
1454Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001455 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +00001456 Value *Op = Visit(E->getSubExpr());
1457 return Builder.CreateNot(Op, "neg");
1458}
1459
1460Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00001461
1462 // Perform vector logical not on comparison with zero vector.
1463 if (E->getType()->isExtVectorType()) {
1464 Value *Oper = Visit(E->getSubExpr());
1465 Value *Zero = llvm::Constant::getNullValue(Oper->getType());
1466 Value *Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp");
1467 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
1468 }
1469
Chris Lattner7f02f722007-08-24 05:35:26 +00001470 // Compare operand to zero.
1471 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001472
Chris Lattner7f02f722007-08-24 05:35:26 +00001473 // Invert value.
1474 // TODO: Could dynamically modify easy computations here. For example, if
1475 // the operand is an icmp ne, turn into icmp eq.
1476 BoolVal = Builder.CreateNot(BoolVal, "lnot");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001477
Anders Carlsson9f84d882009-05-19 18:44:53 +00001478 // ZExt result to the expr type.
1479 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00001480}
1481
Eli Friedman0027d2b2010-08-05 09:58:49 +00001482Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
1483 // Try folding the offsetof to a constant.
Richard Smith80d4b552011-12-28 19:48:30 +00001484 llvm::APSInt Value;
1485 if (E->EvaluateAsInt(Value, CGF.getContext()))
1486 return Builder.getInt(Value);
Eli Friedman0027d2b2010-08-05 09:58:49 +00001487
1488 // Loop over the components of the offsetof to compute the value.
1489 unsigned n = E->getNumComponents();
Chris Lattner2acc6e32011-07-18 04:24:23 +00001490 llvm::Type* ResultType = ConvertType(E->getType());
Eli Friedman0027d2b2010-08-05 09:58:49 +00001491 llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
1492 QualType CurrentType = E->getTypeSourceInfo()->getType();
1493 for (unsigned i = 0; i != n; ++i) {
1494 OffsetOfExpr::OffsetOfNode ON = E->getComponent(i);
Eli Friedman16fd39f2010-08-06 16:37:05 +00001495 llvm::Value *Offset = 0;
Eli Friedman0027d2b2010-08-05 09:58:49 +00001496 switch (ON.getKind()) {
1497 case OffsetOfExpr::OffsetOfNode::Array: {
1498 // Compute the index
1499 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
1500 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001501 bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
Eli Friedman0027d2b2010-08-05 09:58:49 +00001502 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
1503
1504 // Save the element type
1505 CurrentType =
1506 CGF.getContext().getAsArrayType(CurrentType)->getElementType();
1507
1508 // Compute the element size
1509 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
1510 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
1511
1512 // Multiply out to compute the result
1513 Offset = Builder.CreateMul(Idx, ElemSize);
1514 break;
1515 }
1516
1517 case OffsetOfExpr::OffsetOfNode::Field: {
1518 FieldDecl *MemberDecl = ON.getField();
1519 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1520 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1521
1522 // Compute the index of the field in its parent.
1523 unsigned i = 0;
1524 // FIXME: It would be nice if we didn't have to loop here!
1525 for (RecordDecl::field_iterator Field = RD->field_begin(),
1526 FieldEnd = RD->field_end();
David Blaikie262bc182012-04-30 02:36:29 +00001527 Field != FieldEnd; ++Field, ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00001528 if (*Field == MemberDecl)
Eli Friedman0027d2b2010-08-05 09:58:49 +00001529 break;
1530 }
1531 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1532
1533 // Compute the offset to the field
1534 int64_t OffsetInt = RL.getFieldOffset(i) /
1535 CGF.getContext().getCharWidth();
1536 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1537
1538 // Save the element type.
1539 CurrentType = MemberDecl->getType();
1540 break;
1541 }
Eli Friedman16fd39f2010-08-06 16:37:05 +00001542
Eli Friedman0027d2b2010-08-05 09:58:49 +00001543 case OffsetOfExpr::OffsetOfNode::Identifier:
Eli Friedman6d4e44b2010-08-06 01:17:25 +00001544 llvm_unreachable("dependent __builtin_offsetof");
Eli Friedman16fd39f2010-08-06 16:37:05 +00001545
Eli Friedman0027d2b2010-08-05 09:58:49 +00001546 case OffsetOfExpr::OffsetOfNode::Base: {
1547 if (ON.getBase()->isVirtual()) {
1548 CGF.ErrorUnsupported(E, "virtual base in offsetof");
1549 continue;
1550 }
1551
1552 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1553 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1554
1555 // Save the element type.
1556 CurrentType = ON.getBase()->getType();
1557
1558 // Compute the offset to the base.
1559 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1560 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
Benjamin Kramerd4f51982012-07-04 18:45:14 +00001561 CharUnits OffsetInt = RL.getBaseClassOffset(BaseRD);
1562 Offset = llvm::ConstantInt::get(ResultType, OffsetInt.getQuantity());
Eli Friedman0027d2b2010-08-05 09:58:49 +00001563 break;
1564 }
1565 }
1566 Result = Builder.CreateAdd(Result, Offset);
1567 }
1568 return Result;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001569}
1570
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001571/// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
Sebastian Redl05189992008-11-11 17:56:53 +00001572/// argument of the sizeof expression as an integer.
1573Value *
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001574ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
1575 const UnaryExprOrTypeTraitExpr *E) {
Sebastian Redl05189992008-11-11 17:56:53 +00001576 QualType TypeToSize = E->getTypeOfArgument();
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001577 if (E->getKind() == UETT_SizeOf) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001578 if (const VariableArrayType *VAT =
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001579 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
1580 if (E->isArgumentType()) {
1581 // sizeof(type) - make sure to emit the VLA size.
John McCallbc8d40d2011-06-24 21:55:10 +00001582 CGF.EmitVariablyModifiedType(TypeToSize);
Eli Friedman8f426fa2009-04-20 03:21:44 +00001583 } else {
1584 // C99 6.5.3.4p2: If the argument is an expression of type
1585 // VLA, it is evaluated.
John McCall2a416372010-12-05 02:00:02 +00001586 CGF.EmitIgnoredExpr(E->getArgumentExpr());
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001587 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001588
John McCallbc8d40d2011-06-24 21:55:10 +00001589 QualType eltType;
1590 llvm::Value *numElts;
1591 llvm::tie(numElts, eltType) = CGF.getVLASize(VAT);
1592
1593 llvm::Value *size = numElts;
1594
1595 // Scale the number of non-VLA elements by the non-VLA element size.
1596 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
1597 if (!eltSize.isOne())
1598 size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), numElts);
1599
1600 return size;
Anders Carlssonb50525b2008-12-21 03:33:21 +00001601 }
Anders Carlsson5d463152008-12-12 07:38:43 +00001602 }
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001603
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001604 // If this isn't sizeof(vla), the result must be constant; use the constant
1605 // folding logic so we don't have to duplicate it here.
Richard Smith80d4b552011-12-28 19:48:30 +00001606 return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext()));
Chris Lattner7f02f722007-08-24 05:35:26 +00001607}
1608
Chris Lattner46f93d02007-08-24 21:20:17 +00001609Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
1610 Expr *Op = E->getSubExpr();
John McCallb418d742010-11-16 10:08:07 +00001611 if (Op->getType()->isAnyComplexType()) {
1612 // If it's an l-value, load through the appropriate subobject l-value.
1613 // Note that we have to ask E because Op might be an l-value that
1614 // this won't work for, e.g. an Obj-C property.
John McCall7eb0a9e2010-11-24 05:12:34 +00001615 if (E->isGLValue())
John McCall545d9962011-06-25 02:11:03 +00001616 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal();
John McCallb418d742010-11-16 10:08:07 +00001617
1618 // Otherwise, calculate and project.
1619 return CGF.EmitComplexExpr(Op, false, true).first;
1620 }
1621
Chris Lattner46f93d02007-08-24 21:20:17 +00001622 return Visit(Op);
1623}
John McCallb418d742010-11-16 10:08:07 +00001624
Chris Lattner46f93d02007-08-24 21:20:17 +00001625Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
1626 Expr *Op = E->getSubExpr();
John McCallb418d742010-11-16 10:08:07 +00001627 if (Op->getType()->isAnyComplexType()) {
1628 // If it's an l-value, load through the appropriate subobject l-value.
1629 // Note that we have to ask E because Op might be an l-value that
1630 // this won't work for, e.g. an Obj-C property.
John McCall7eb0a9e2010-11-24 05:12:34 +00001631 if (Op->isGLValue())
John McCall545d9962011-06-25 02:11:03 +00001632 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal();
John McCallb418d742010-11-16 10:08:07 +00001633
1634 // Otherwise, calculate and project.
1635 return CGF.EmitComplexExpr(Op, true, false).second;
1636 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001637
Mike Stump7f79f9b2009-05-29 15:46:01 +00001638 // __imag on a scalar returns zero. Emit the subexpr to ensure side
1639 // effects are evaluated, but not the actual value.
Richard Smithdfb80de2012-02-18 20:53:32 +00001640 if (Op->isGLValue())
1641 CGF.EmitLValue(Op);
1642 else
1643 CGF.EmitScalarExpr(Op, true);
Owen Andersonc9c88b42009-07-31 20:28:54 +00001644 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner46f93d02007-08-24 21:20:17 +00001645}
1646
Chris Lattner7f02f722007-08-24 05:35:26 +00001647//===----------------------------------------------------------------------===//
1648// Binary Operators
1649//===----------------------------------------------------------------------===//
1650
1651BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001652 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +00001653 BinOpInfo Result;
1654 Result.LHS = Visit(E->getLHS());
1655 Result.RHS = Visit(E->getRHS());
Chris Lattner1f1ded92007-08-24 21:00:35 +00001656 Result.Ty = E->getType();
Chris Lattner9a207232010-06-26 21:48:21 +00001657 Result.Opcode = E->getOpcode();
Lang Hamesbe9af122012-10-02 04:45:10 +00001658 Result.FPContractable = E->isFPContractable();
Chris Lattner7f02f722007-08-24 05:35:26 +00001659 Result.E = E;
1660 return Result;
1661}
1662
Douglas Gregor6a03e342010-04-23 04:16:32 +00001663LValue ScalarExprEmitter::EmitCompoundAssignLValue(
1664 const CompoundAssignOperator *E,
1665 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001666 Value *&Result) {
Benjamin Kramer54d76db2009-12-25 15:43:36 +00001667 QualType LHSTy = E->getLHS()->getType();
Chris Lattner1f1ded92007-08-24 21:00:35 +00001668 BinOpInfo OpInfo;
Douglas Gregor6a03e342010-04-23 04:16:32 +00001669
Eli Friedmanab3a8522009-03-28 01:22:36 +00001670 if (E->getComputationResultType()->isAnyComplexType()) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001671 // This needs to go through the complex expression emitter, but it's a tad
1672 // complicated to do that... I'm leaving it out for now. (Note that we do
1673 // actually need the imaginary part of the RHS for multiplication and
1674 // division.)
Eli Friedmanab3a8522009-03-28 01:22:36 +00001675 CGF.ErrorUnsupported(E, "complex compound assignment");
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001676 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Douglas Gregor6a03e342010-04-23 04:16:32 +00001677 return LValue();
Eli Friedmanab3a8522009-03-28 01:22:36 +00001678 }
Douglas Gregor6a03e342010-04-23 04:16:32 +00001679
Mike Stumpcc0442f2009-05-22 19:07:20 +00001680 // Emit the RHS first. __block variables need to have the rhs evaluated
1681 // first, plus this should improve codegen a little.
1682 OpInfo.RHS = Visit(E->getRHS());
1683 OpInfo.Ty = E->getComputationResultType();
Chris Lattner9a207232010-06-26 21:48:21 +00001684 OpInfo.Opcode = E->getOpcode();
Mike Stumpcc0442f2009-05-22 19:07:20 +00001685 OpInfo.E = E;
Eli Friedmanab3a8522009-03-28 01:22:36 +00001686 // Load/convert the LHS.
Richard Smith7ac9ef12012-09-08 02:08:36 +00001687 LValue LHSLV = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
John McCall545d9962011-06-25 02:11:03 +00001688 OpInfo.LHS = EmitLoadOfLValue(LHSLV);
David Chisnall7a7ee302012-01-16 17:27:18 +00001689
1690 llvm::PHINode *atomicPHI = 0;
Eli Friedman860a3192012-06-16 02:19:17 +00001691 if (LHSTy->isAtomicType()) {
David Chisnall7a7ee302012-01-16 17:27:18 +00001692 // FIXME: For floating point types, we should be saving and restoring the
1693 // floating point environment in the loop.
1694 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
1695 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
1696 Builder.CreateBr(opBB);
1697 Builder.SetInsertPoint(opBB);
1698 atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2);
1699 atomicPHI->addIncoming(OpInfo.LHS, startBB);
David Chisnall7a7ee302012-01-16 17:27:18 +00001700 OpInfo.LHS = atomicPHI;
1701 }
Eli Friedman860a3192012-06-16 02:19:17 +00001702
1703 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
1704 E->getComputationLHSType());
1705
Chris Lattner1f1ded92007-08-24 21:00:35 +00001706 // Expand the binary operator.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001707 Result = (this->*Func)(OpInfo);
Douglas Gregor6a03e342010-04-23 04:16:32 +00001708
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001709 // Convert the result back to the LHS type.
Eli Friedmanab3a8522009-03-28 01:22:36 +00001710 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
David Chisnall7a7ee302012-01-16 17:27:18 +00001711
1712 if (atomicPHI) {
1713 llvm::BasicBlock *opBB = Builder.GetInsertBlock();
1714 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
1715 llvm::Value *old = Builder.CreateAtomicCmpXchg(LHSLV.getAddress(), atomicPHI,
1716 Result, llvm::SequentiallyConsistent);
1717 atomicPHI->addIncoming(old, opBB);
1718 llvm::Value *success = Builder.CreateICmpEQ(old, atomicPHI);
1719 Builder.CreateCondBr(success, contBB, opBB);
1720 Builder.SetInsertPoint(contBB);
1721 return LHSLV;
1722 }
Douglas Gregor6a03e342010-04-23 04:16:32 +00001723
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001724 // Store the result value into the LHS lvalue. Bit-fields are handled
1725 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
1726 // 'An assignment expression has the value of the left operand after the
1727 // assignment...'.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001728 if (LHSLV.isBitField())
John McCall545d9962011-06-25 02:11:03 +00001729 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001730 else
John McCall545d9962011-06-25 02:11:03 +00001731 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001732
Douglas Gregor6a03e342010-04-23 04:16:32 +00001733 return LHSLV;
1734}
1735
1736Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
1737 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
1738 bool Ignore = TestAndClearIgnoreResultAssign();
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001739 Value *RHS;
1740 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
1741
1742 // If the result is clearly ignored, return now.
Mike Stump7f79f9b2009-05-29 15:46:01 +00001743 if (Ignore)
1744 return 0;
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001745
John McCallb418d742010-11-16 10:08:07 +00001746 // The result of an assignment in C is the assigned r-value.
David Blaikie4e4d0842012-03-11 07:00:24 +00001747 if (!CGF.getContext().getLangOpts().CPlusPlus)
John McCallb418d742010-11-16 10:08:07 +00001748 return RHS;
1749
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001750 // If the lvalue is non-volatile, return the computed value of the assignment.
1751 if (!LHS.isVolatileQualified())
1752 return RHS;
1753
1754 // Otherwise, reload the value.
John McCall545d9962011-06-25 02:11:03 +00001755 return EmitLoadOfLValue(LHS);
Chris Lattner1f1ded92007-08-24 21:00:35 +00001756}
1757
Chris Lattner80230302010-09-11 21:47:09 +00001758void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
Richard Smith7ac9ef12012-09-08 02:08:36 +00001759 const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001760 llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
Chris Lattner80230302010-09-11 21:47:09 +00001761
1762 if (Ops.Ty->hasSignedIntegerRepresentation()) {
1763 llvm::Value *IntMin =
Chris Lattner48431f92011-04-19 22:55:03 +00001764 Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
Chris Lattner80230302010-09-11 21:47:09 +00001765 llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
1766
Richard Smith7ac9ef12012-09-08 02:08:36 +00001767 llvm::Value *Cond1 = Builder.CreateICmpNE(Ops.RHS, Zero);
1768 llvm::Value *LHSCmp = Builder.CreateICmpNE(Ops.LHS, IntMin);
1769 llvm::Value *RHSCmp = Builder.CreateICmpNE(Ops.RHS, NegOne);
1770 llvm::Value *Cond2 = Builder.CreateOr(LHSCmp, RHSCmp, "or");
1771 CGF.EmitCheck(Builder.CreateAnd(Cond1, Cond2, "and"));
Chris Lattner80230302010-09-11 21:47:09 +00001772 } else {
Richard Smith7ac9ef12012-09-08 02:08:36 +00001773 CGF.EmitCheck(Builder.CreateICmpNE(Ops.RHS, Zero));
Chris Lattner80230302010-09-11 21:47:09 +00001774 }
Chris Lattner80230302010-09-11 21:47:09 +00001775}
Chris Lattner1f1ded92007-08-24 21:00:35 +00001776
Chris Lattner7f02f722007-08-24 05:35:26 +00001777Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Richard Smith7ac9ef12012-09-08 02:08:36 +00001778 if (isTrapvOverflowBehavior()) {
Chris Lattner80230302010-09-11 21:47:09 +00001779 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1780
1781 if (Ops.Ty->isIntegerType())
1782 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
Richard Smith7ac9ef12012-09-08 02:08:36 +00001783 else if (Ops.Ty->isRealFloatingType())
1784 CGF.EmitCheck(Builder.CreateFCmpUNE(Ops.RHS, Zero));
Chris Lattner80230302010-09-11 21:47:09 +00001785 }
Peter Collingbournec5096cb2011-10-27 19:19:51 +00001786 if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
1787 llvm::Value *Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
David Blaikie4e4d0842012-03-11 07:00:24 +00001788 if (CGF.getContext().getLangOpts().OpenCL) {
Peter Collingbournec5096cb2011-10-27 19:19:51 +00001789 // OpenCL 1.1 7.4: minimum accuracy of single precision / is 2.5ulp
1790 llvm::Type *ValTy = Val->getType();
1791 if (ValTy->isFloatTy() ||
1792 (isa<llvm::VectorType>(ValTy) &&
1793 cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy()))
Duncan Sands82500162012-04-10 08:23:07 +00001794 CGF.SetFPAccuracy(Val, 2.5);
Peter Collingbournec5096cb2011-10-27 19:19:51 +00001795 }
1796 return Val;
1797 }
Douglas Gregorf6094622010-07-23 15:58:24 +00001798 else if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00001799 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
1800 else
1801 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
1802}
1803
1804Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
1805 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner80230302010-09-11 21:47:09 +00001806 if (isTrapvOverflowBehavior()) {
1807 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1808
1809 if (Ops.Ty->isIntegerType())
1810 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
1811 }
1812
Eli Friedman52d68742011-04-10 04:44:11 +00001813 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00001814 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
1815 else
1816 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
1817}
1818
Mike Stump2add4732009-04-01 20:28:16 +00001819Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
1820 unsigned IID;
1821 unsigned OpID = 0;
Mike Stump5d8b2cf2009-04-02 01:03:55 +00001822
Chris Lattner9a207232010-06-26 21:48:21 +00001823 switch (Ops.Opcode) {
John McCall2de56d12010-08-25 11:45:40 +00001824 case BO_Add:
1825 case BO_AddAssign:
Mike Stump035cf892009-04-02 18:15:54 +00001826 OpID = 1;
1827 IID = llvm::Intrinsic::sadd_with_overflow;
1828 break;
John McCall2de56d12010-08-25 11:45:40 +00001829 case BO_Sub:
1830 case BO_SubAssign:
Mike Stump035cf892009-04-02 18:15:54 +00001831 OpID = 2;
1832 IID = llvm::Intrinsic::ssub_with_overflow;
1833 break;
John McCall2de56d12010-08-25 11:45:40 +00001834 case BO_Mul:
1835 case BO_MulAssign:
Mike Stump035cf892009-04-02 18:15:54 +00001836 OpID = 3;
1837 IID = llvm::Intrinsic::smul_with_overflow;
1838 break;
1839 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00001840 llvm_unreachable("Unsupported operation for overflow detection");
Mike Stump2add4732009-04-01 20:28:16 +00001841 }
Mike Stump035cf892009-04-02 18:15:54 +00001842 OpID <<= 1;
1843 OpID |= 1;
1844
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001845 llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
Mike Stump2add4732009-04-01 20:28:16 +00001846
Benjamin Kramer8dd55a32011-07-14 17:45:50 +00001847 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
Mike Stump2add4732009-04-01 20:28:16 +00001848
1849 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
1850 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
1851 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
1852
Richard Smith7ac9ef12012-09-08 02:08:36 +00001853 // Handle overflow with llvm.trap if no custom handler has been specified.
1854 const std::string *handlerName =
1855 &CGF.getContext().getLangOpts().OverflowHandler;
1856 if (handlerName->empty()) {
1857 CGF.EmitCheck(Builder.CreateNot(overflow));
1858 return result;
1859 }
1860
Mike Stump2add4732009-04-01 20:28:16 +00001861 // Branch in case of overflow.
David Chisnall7f18e672010-09-17 18:29:54 +00001862 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
Bill Wendling14ef3192011-07-07 21:13:10 +00001863 llvm::Function::iterator insertPt = initialBB;
1864 llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn,
1865 llvm::next(insertPt));
Chris Lattner93a00352010-08-07 00:20:46 +00001866 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
Mike Stump2add4732009-04-01 20:28:16 +00001867
1868 Builder.CreateCondBr(overflow, overflowBB, continueBB);
1869
David Chisnall7f18e672010-09-17 18:29:54 +00001870 // If an overflow handler is set, then we want to call it and then use its
1871 // result, if it returns.
1872 Builder.SetInsertPoint(overflowBB);
1873
1874 // Get the overflow handler.
Chris Lattner8b418682012-02-07 00:39:47 +00001875 llvm::Type *Int8Ty = CGF.Int8Ty;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001876 llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
David Chisnall7f18e672010-09-17 18:29:54 +00001877 llvm::FunctionType *handlerTy =
1878 llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
1879 llvm::Value *handler = CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
1880
1881 // Sign extend the args to 64-bit, so that we can use the same handler for
1882 // all types of overflow.
1883 llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
1884 llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
1885
1886 // Call the handler with the two arguments, the operation, and the size of
1887 // the result.
1888 llvm::Value *handlerResult = Builder.CreateCall4(handler, lhs, rhs,
1889 Builder.getInt8(OpID),
1890 Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth()));
1891
1892 // Truncate the result back to the desired size.
1893 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
1894 Builder.CreateBr(continueBB);
1895
Mike Stump2add4732009-04-01 20:28:16 +00001896 Builder.SetInsertPoint(continueBB);
Jay Foadbbf3bac2011-03-30 11:28:58 +00001897 llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
David Chisnall7f18e672010-09-17 18:29:54 +00001898 phi->addIncoming(result, initialBB);
1899 phi->addIncoming(handlerResult, overflowBB);
1900
1901 return phi;
Mike Stump2add4732009-04-01 20:28:16 +00001902}
Chris Lattner7f02f722007-08-24 05:35:26 +00001903
John McCall913dab22011-06-25 01:32:37 +00001904/// Emit pointer + index arithmetic.
1905static Value *emitPointerArithmetic(CodeGenFunction &CGF,
1906 const BinOpInfo &op,
1907 bool isSubtraction) {
1908 // Must have binary (not unary) expr here. Unary pointer
1909 // increment/decrement doesn't use this path.
1910 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
1911
1912 Value *pointer = op.LHS;
1913 Expr *pointerOperand = expr->getLHS();
1914 Value *index = op.RHS;
1915 Expr *indexOperand = expr->getRHS();
1916
1917 // In a subtraction, the LHS is always the pointer.
1918 if (!isSubtraction && !pointer->getType()->isPointerTy()) {
1919 std::swap(pointer, index);
1920 std::swap(pointerOperand, indexOperand);
1921 }
1922
1923 unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
1924 if (width != CGF.PointerWidthInBits) {
1925 // Zero-extend or sign-extend the pointer value according to
1926 // whether the index is signed or not.
1927 bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
1928 index = CGF.Builder.CreateIntCast(index, CGF.PtrDiffTy, isSigned,
1929 "idx.ext");
1930 }
1931
1932 // If this is subtraction, negate the index.
1933 if (isSubtraction)
1934 index = CGF.Builder.CreateNeg(index, "idx.neg");
1935
1936 const PointerType *pointerType
1937 = pointerOperand->getType()->getAs<PointerType>();
1938 if (!pointerType) {
1939 QualType objectType = pointerOperand->getType()
1940 ->castAs<ObjCObjectPointerType>()
1941 ->getPointeeType();
1942 llvm::Value *objectSize
1943 = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
1944
1945 index = CGF.Builder.CreateMul(index, objectSize);
1946
1947 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
1948 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
1949 return CGF.Builder.CreateBitCast(result, pointer->getType());
1950 }
1951
1952 QualType elementType = pointerType->getPointeeType();
1953 if (const VariableArrayType *vla
1954 = CGF.getContext().getAsVariableArrayType(elementType)) {
1955 // The element count here is the total number of non-VLA elements.
1956 llvm::Value *numElements = CGF.getVLASize(vla).first;
1957
1958 // Effectively, the multiply by the VLA size is part of the GEP.
1959 // GEP indexes are signed, and scaling an index isn't permitted to
1960 // signed-overflow, so we use the same semantics for our explicit
1961 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikie4e4d0842012-03-11 07:00:24 +00001962 if (CGF.getLangOpts().isSignedOverflowDefined()) {
John McCall913dab22011-06-25 01:32:37 +00001963 index = CGF.Builder.CreateMul(index, numElements, "vla.index");
1964 pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr");
1965 } else {
1966 index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
1967 pointer = CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
Chris Lattnera4d71452010-06-26 21:25:03 +00001968 }
John McCall913dab22011-06-25 01:32:37 +00001969 return pointer;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001970 }
Daniel Dunbar2a866252009-04-25 05:08:32 +00001971
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001972 // Explicitly handle GNU void* and function pointer arithmetic extensions. The
1973 // GNU void* casts amount to no-ops since our void* type is i8*, but this is
1974 // future proof.
John McCall913dab22011-06-25 01:32:37 +00001975 if (elementType->isVoidType() || elementType->isFunctionType()) {
1976 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
1977 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
1978 return CGF.Builder.CreateBitCast(result, pointer->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001979 }
1980
David Blaikie4e4d0842012-03-11 07:00:24 +00001981 if (CGF.getLangOpts().isSignedOverflowDefined())
John McCall913dab22011-06-25 01:32:37 +00001982 return CGF.Builder.CreateGEP(pointer, index, "add.ptr");
1983
1984 return CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
Chris Lattner7f02f722007-08-24 05:35:26 +00001985}
1986
Lang Hamesbe9af122012-10-02 04:45:10 +00001987// Construct an fmuladd intrinsic to represent a fused mul-add of MulOp and
1988// Addend. Use negMul and negAdd to negate the first operand of the Mul or
1989// the add operand respectively. This allows fmuladd to represent a*b-c, or
1990// c-a*b. Patterns in LLVM should catch the negated forms and translate them to
1991// efficient operations.
1992static Value* buildFMulAdd(llvm::BinaryOperator *MulOp, Value *Addend,
1993 const CodeGenFunction &CGF, CGBuilderTy &Builder,
1994 bool negMul, bool negAdd) {
1995 assert(!(negMul && negAdd) && "Only one of negMul and negAdd should be set.");
1996
1997 Value *MulOp0 = MulOp->getOperand(0);
1998 Value *MulOp1 = MulOp->getOperand(1);
1999 if (negMul) {
2000 MulOp0 =
2001 Builder.CreateFSub(
2002 llvm::ConstantFP::getZeroValueForNegation(MulOp0->getType()), MulOp0,
2003 "neg");
2004 } else if (negAdd) {
2005 Addend =
2006 Builder.CreateFSub(
2007 llvm::ConstantFP::getZeroValueForNegation(Addend->getType()), Addend,
2008 "neg");
2009 }
2010
2011 Value *FMulAdd =
2012 Builder.CreateCall3(
2013 CGF.CGM.getIntrinsic(llvm::Intrinsic::fmuladd, Addend->getType()),
2014 MulOp0, MulOp1, Addend);
2015 MulOp->eraseFromParent();
2016
2017 return FMulAdd;
2018}
2019
2020// Check whether it would be legal to emit an fmuladd intrinsic call to
2021// represent op and if so, build the fmuladd.
2022//
2023// Checks that (a) the operation is fusable, and (b) -ffp-contract=on.
2024// Does NOT check the type of the operation - it's assumed that this function
2025// will be called from contexts where it's known that the type is contractable.
2026static Value* tryEmitFMulAdd(const BinOpInfo &op,
2027 const CodeGenFunction &CGF, CGBuilderTy &Builder,
2028 bool isSub=false) {
2029
2030 assert((op.Opcode == BO_Add || op.Opcode == BO_AddAssign ||
2031 op.Opcode == BO_Sub || op.Opcode == BO_SubAssign) &&
2032 "Only fadd/fsub can be the root of an fmuladd.");
2033
2034 // Check whether this op is marked as fusable.
2035 if (!op.FPContractable)
2036 return 0;
2037
2038 // Check whether -ffp-contract=on. (If -ffp-contract=off/fast, fusing is
2039 // either disabled, or handled entirely by the LLVM backend).
2040 if (CGF.getContext().getLangOpts().getFPContractMode() != LangOptions::FPC_On)
2041 return 0;
2042
2043 // We have a potentially fusable op. Look for a mul on one of the operands.
2044 if (llvm::BinaryOperator* LHSBinOp = dyn_cast<llvm::BinaryOperator>(op.LHS)) {
2045 if (LHSBinOp->getOpcode() == llvm::Instruction::FMul) {
2046 return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub);
2047 }
2048 } else if (llvm::BinaryOperator* RHSBinOp =
2049 dyn_cast<llvm::BinaryOperator>(op.RHS)) {
2050 if (RHSBinOp->getOpcode() == llvm::Instruction::FMul) {
2051 return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false);
2052 }
2053 }
2054
2055 return 0;
2056}
2057
John McCall913dab22011-06-25 01:32:37 +00002058Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
2059 if (op.LHS->getType()->isPointerTy() ||
2060 op.RHS->getType()->isPointerTy())
2061 return emitPointerArithmetic(CGF, op, /*subtraction*/ false);
2062
2063 if (op.Ty->isSignedIntegerOrEnumerationType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002064 switch (CGF.getContext().getLangOpts().getSignedOverflowBehavior()) {
John McCall913dab22011-06-25 01:32:37 +00002065 case LangOptions::SOB_Defined:
2066 return Builder.CreateAdd(op.LHS, op.RHS, "add");
Richard Smith9d3e2262012-08-25 00:32:28 +00002067 case LangOptions::SOB_Undefined:
2068 if (!CGF.CatchUndefined)
2069 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
2070 // Fall through.
John McCall913dab22011-06-25 01:32:37 +00002071 case LangOptions::SOB_Trapping:
2072 return EmitOverflowCheckedBinOp(op);
2073 }
2074 }
2075
Lang Hamesbe9af122012-10-02 04:45:10 +00002076 if (op.LHS->getType()->isFPOrFPVectorTy()) {
2077 // Try to form an fmuladd.
2078 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder))
2079 return FMulAdd;
2080
John McCall913dab22011-06-25 01:32:37 +00002081 return Builder.CreateFAdd(op.LHS, op.RHS, "add");
Lang Hamesbe9af122012-10-02 04:45:10 +00002082 }
John McCall913dab22011-06-25 01:32:37 +00002083
2084 return Builder.CreateAdd(op.LHS, op.RHS, "add");
2085}
2086
2087Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
2088 // The LHS is always a pointer if either side is.
2089 if (!op.LHS->getType()->isPointerTy()) {
2090 if (op.Ty->isSignedIntegerOrEnumerationType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002091 switch (CGF.getContext().getLangOpts().getSignedOverflowBehavior()) {
Chris Lattnera4d71452010-06-26 21:25:03 +00002092 case LangOptions::SOB_Defined:
John McCall913dab22011-06-25 01:32:37 +00002093 return Builder.CreateSub(op.LHS, op.RHS, "sub");
Richard Smith9d3e2262012-08-25 00:32:28 +00002094 case LangOptions::SOB_Undefined:
2095 if (!CGF.CatchUndefined)
2096 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
2097 // Fall through.
Chris Lattnera4d71452010-06-26 21:25:03 +00002098 case LangOptions::SOB_Trapping:
John McCall913dab22011-06-25 01:32:37 +00002099 return EmitOverflowCheckedBinOp(op);
Chris Lattnera4d71452010-06-26 21:25:03 +00002100 }
2101 }
2102
Lang Hamesbe9af122012-10-02 04:45:10 +00002103 if (op.LHS->getType()->isFPOrFPVectorTy()) {
2104 // Try to form an fmuladd.
2105 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder, true))
2106 return FMulAdd;
John McCall913dab22011-06-25 01:32:37 +00002107 return Builder.CreateFSub(op.LHS, op.RHS, "sub");
Lang Hamesbe9af122012-10-02 04:45:10 +00002108 }
Chris Lattner2eb91e42010-03-29 17:28:16 +00002109
John McCall913dab22011-06-25 01:32:37 +00002110 return Builder.CreateSub(op.LHS, op.RHS, "sub");
Mike Stump2add4732009-04-01 20:28:16 +00002111 }
Chris Lattner1f1ded92007-08-24 21:00:35 +00002112
John McCall913dab22011-06-25 01:32:37 +00002113 // If the RHS is not a pointer, then we have normal pointer
2114 // arithmetic.
2115 if (!op.RHS->getType()->isPointerTy())
2116 return emitPointerArithmetic(CGF, op, /*subtraction*/ true);
Eli Friedmandaa24a22009-03-28 02:45:41 +00002117
John McCall913dab22011-06-25 01:32:37 +00002118 // Otherwise, this is a pointer subtraction.
Daniel Dunbarb09fae72009-01-23 18:51:09 +00002119
John McCall913dab22011-06-25 01:32:37 +00002120 // Do the raw subtraction part.
2121 llvm::Value *LHS
2122 = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
2123 llvm::Value *RHS
2124 = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
2125 Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Daniel Dunbar2a866252009-04-25 05:08:32 +00002126
John McCall913dab22011-06-25 01:32:37 +00002127 // Okay, figure out the element size.
2128 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
2129 QualType elementType = expr->getLHS()->getType()->getPointeeType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002130
John McCall913dab22011-06-25 01:32:37 +00002131 llvm::Value *divisor = 0;
2132
2133 // For a variable-length array, this is going to be non-constant.
2134 if (const VariableArrayType *vla
2135 = CGF.getContext().getAsVariableArrayType(elementType)) {
2136 llvm::Value *numElements;
2137 llvm::tie(numElements, elementType) = CGF.getVLASize(vla);
2138
2139 divisor = numElements;
2140
2141 // Scale the number of non-VLA elements by the non-VLA element size.
2142 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
2143 if (!eltSize.isOne())
2144 divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
2145
2146 // For everything elese, we can just compute it, safe in the
2147 // assumption that Sema won't let anything through that we can't
2148 // safely compute the size of.
2149 } else {
2150 CharUnits elementSize;
2151 // Handle GCC extension for pointer arithmetic on void* and
2152 // function pointer types.
2153 if (elementType->isVoidType() || elementType->isFunctionType())
2154 elementSize = CharUnits::One();
2155 else
2156 elementSize = CGF.getContext().getTypeSizeInChars(elementType);
2157
2158 // Don't even emit the divide for element size of 1.
2159 if (elementSize.isOne())
2160 return diffInChars;
2161
2162 divisor = CGF.CGM.getSize(elementSize);
Chris Lattner7f02f722007-08-24 05:35:26 +00002163 }
Chris Lattner2cb42222011-03-01 00:03:48 +00002164
Chris Lattner2cb42222011-03-01 00:03:48 +00002165 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
2166 // pointer difference in C is only defined in the case where both operands
2167 // are pointing to elements of an array.
John McCall913dab22011-06-25 01:32:37 +00002168 return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
Chris Lattner7f02f722007-08-24 05:35:26 +00002169}
2170
2171Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
2172 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2173 // RHS to the same size as the LHS.
2174 Value *RHS = Ops.RHS;
2175 if (Ops.LHS->getType() != RHS->getType())
2176 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002177
Richard Smith9d3e2262012-08-25 00:32:28 +00002178 if (CGF.CatchUndefined && isa<llvm::IntegerType>(Ops.LHS->getType())) {
Mike Stumpbe07f602009-12-14 21:58:14 +00002179 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
Richard Smith9d3e2262012-08-25 00:32:28 +00002180 llvm::Value *WidthMinusOne =
Richard Smith5b092ef2012-08-25 05:43:00 +00002181 llvm::ConstantInt::get(RHS->getType(), Width - 1);
Richard Smith7ac9ef12012-09-08 02:08:36 +00002182 CGF.EmitCheck(Builder.CreateICmpULE(RHS, WidthMinusOne));
Richard Smith9d3e2262012-08-25 00:32:28 +00002183
2184 if (Ops.Ty->hasSignedIntegerRepresentation()) {
2185 // Check whether we are shifting any non-zero bits off the top of the
2186 // integer.
Richard Smith9d3e2262012-08-25 00:32:28 +00002187 llvm::Value *BitsShiftedOff =
2188 Builder.CreateLShr(Ops.LHS,
2189 Builder.CreateSub(WidthMinusOne, RHS, "shl.zeros",
2190 /*NUW*/true, /*NSW*/true),
2191 "shl.check");
2192 if (CGF.getLangOpts().CPlusPlus) {
2193 // In C99, we are not permitted to shift a 1 bit into the sign bit.
2194 // Under C++11's rules, shifting a 1 bit into the sign bit is
2195 // OK, but shifting a 1 bit out of it is not. (C89 and C++03 don't
2196 // define signed left shifts, so we use the C99 and C++11 rules there).
2197 llvm::Value *One = llvm::ConstantInt::get(BitsShiftedOff->getType(), 1);
2198 BitsShiftedOff = Builder.CreateLShr(BitsShiftedOff, One);
2199 }
2200 llvm::Value *Zero = llvm::ConstantInt::get(BitsShiftedOff->getType(), 0);
Richard Smith7ac9ef12012-09-08 02:08:36 +00002201 CGF.EmitCheck(Builder.CreateICmpEQ(BitsShiftedOff, Zero));
Richard Smith9d3e2262012-08-25 00:32:28 +00002202 }
Mike Stumpbe07f602009-12-14 21:58:14 +00002203 }
2204
Chris Lattner7f02f722007-08-24 05:35:26 +00002205 return Builder.CreateShl(Ops.LHS, RHS, "shl");
2206}
2207
2208Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
2209 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2210 // RHS to the same size as the LHS.
2211 Value *RHS = Ops.RHS;
2212 if (Ops.LHS->getType() != RHS->getType())
2213 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002214
Richard Smith9d3e2262012-08-25 00:32:28 +00002215 if (CGF.CatchUndefined && isa<llvm::IntegerType>(Ops.LHS->getType())) {
Mike Stumpbe07f602009-12-14 21:58:14 +00002216 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
Richard Smith7ac9ef12012-09-08 02:08:36 +00002217 llvm::Value *WidthVal = llvm::ConstantInt::get(RHS->getType(), Width);
2218 CGF.EmitCheck(Builder.CreateICmpULT(RHS, WidthVal));
Mike Stumpbe07f602009-12-14 21:58:14 +00002219 }
2220
Douglas Gregorf6094622010-07-23 15:58:24 +00002221 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00002222 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
2223 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
2224}
2225
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002226enum IntrinsicType { VCMPEQ, VCMPGT };
2227// return corresponding comparison intrinsic for given vector type
2228static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
2229 BuiltinType::Kind ElemKind) {
2230 switch (ElemKind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002231 default: llvm_unreachable("unexpected element type");
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002232 case BuiltinType::Char_U:
2233 case BuiltinType::UChar:
2234 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2235 llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002236 case BuiltinType::Char_S:
2237 case BuiltinType::SChar:
2238 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2239 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002240 case BuiltinType::UShort:
2241 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2242 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002243 case BuiltinType::Short:
2244 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2245 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002246 case BuiltinType::UInt:
2247 case BuiltinType::ULong:
2248 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2249 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002250 case BuiltinType::Int:
2251 case BuiltinType::Long:
2252 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2253 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002254 case BuiltinType::Float:
2255 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
2256 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002257 }
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002258}
2259
Chris Lattner7f02f722007-08-24 05:35:26 +00002260Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
2261 unsigned SICmpOpc, unsigned FCmpOpc) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002262 TestAndClearIgnoreResultAssign();
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002263 Value *Result;
Chris Lattner7f02f722007-08-24 05:35:26 +00002264 QualType LHSTy = E->getLHS()->getType();
John McCall0bab0cd2010-08-23 01:21:21 +00002265 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
John McCall2de56d12010-08-25 11:45:40 +00002266 assert(E->getOpcode() == BO_EQ ||
2267 E->getOpcode() == BO_NE);
John McCalld608cdb2010-08-22 10:59:02 +00002268 Value *LHS = CGF.EmitScalarExpr(E->getLHS());
2269 Value *RHS = CGF.EmitScalarExpr(E->getRHS());
John McCall0bab0cd2010-08-23 01:21:21 +00002270 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
John McCall2de56d12010-08-25 11:45:40 +00002271 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
Eli Friedmanb81c7862009-12-11 07:36:43 +00002272 } else if (!LHSTy->isAnyComplexType()) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002273 Value *LHS = Visit(E->getLHS());
2274 Value *RHS = Visit(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002275
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002276 // If AltiVec, the comparison results in a numeric type, so we use
2277 // intrinsics comparing vectors and giving 0 or 1 as a result
Anton Yartsev6305f722011-03-28 21:00:05 +00002278 if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002279 // constants for mapping CR6 register bits to predicate result
2280 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
2281
2282 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
2283
2284 // in several cases vector arguments order will be reversed
2285 Value *FirstVecArg = LHS,
2286 *SecondVecArg = RHS;
2287
2288 QualType ElTy = LHSTy->getAs<VectorType>()->getElementType();
John McCallf4c73712011-01-19 06:33:43 +00002289 const BuiltinType *BTy = ElTy->getAs<BuiltinType>();
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002290 BuiltinType::Kind ElementKind = BTy->getKind();
2291
2292 switch(E->getOpcode()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002293 default: llvm_unreachable("is not a comparison operation");
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002294 case BO_EQ:
2295 CR6 = CR6_LT;
2296 ID = GetIntrinsic(VCMPEQ, ElementKind);
2297 break;
2298 case BO_NE:
2299 CR6 = CR6_EQ;
2300 ID = GetIntrinsic(VCMPEQ, ElementKind);
2301 break;
2302 case BO_LT:
2303 CR6 = CR6_LT;
2304 ID = GetIntrinsic(VCMPGT, ElementKind);
2305 std::swap(FirstVecArg, SecondVecArg);
2306 break;
2307 case BO_GT:
2308 CR6 = CR6_LT;
2309 ID = GetIntrinsic(VCMPGT, ElementKind);
2310 break;
2311 case BO_LE:
2312 if (ElementKind == BuiltinType::Float) {
2313 CR6 = CR6_LT;
2314 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2315 std::swap(FirstVecArg, SecondVecArg);
2316 }
2317 else {
2318 CR6 = CR6_EQ;
2319 ID = GetIntrinsic(VCMPGT, ElementKind);
2320 }
2321 break;
2322 case BO_GE:
2323 if (ElementKind == BuiltinType::Float) {
2324 CR6 = CR6_LT;
2325 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2326 }
2327 else {
2328 CR6 = CR6_EQ;
2329 ID = GetIntrinsic(VCMPGT, ElementKind);
2330 std::swap(FirstVecArg, SecondVecArg);
2331 }
2332 break;
2333 }
2334
Chris Lattner48431f92011-04-19 22:55:03 +00002335 Value *CR6Param = Builder.getInt32(CR6);
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002336 llvm::Function *F = CGF.CGM.getIntrinsic(ID);
2337 Result = Builder.CreateCall3(F, CR6Param, FirstVecArg, SecondVecArg, "");
2338 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
2339 }
2340
Duncan Sandsf177d9d2010-02-15 16:14:01 +00002341 if (LHS->getType()->isFPOrFPVectorTy()) {
Nate Begeman7a66d7b2008-07-25 20:16:05 +00002342 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002343 LHS, RHS, "cmp");
Douglas Gregorf6094622010-07-23 15:58:24 +00002344 } else if (LHSTy->hasSignedIntegerRepresentation()) {
Eli Friedmanec2c1262008-05-29 15:09:15 +00002345 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002346 LHS, RHS, "cmp");
2347 } else {
Eli Friedmanec2c1262008-05-29 15:09:15 +00002348 // Unsigned integers and pointers.
2349 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002350 LHS, RHS, "cmp");
2351 }
Chris Lattner9c10fcf2009-07-08 01:08:03 +00002352
2353 // If this is a vector comparison, sign extend the result to the appropriate
2354 // vector integer type and return it (don't convert to bool).
2355 if (LHSTy->isVectorType())
2356 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002357
Chris Lattner7f02f722007-08-24 05:35:26 +00002358 } else {
2359 // Complex Comparison: can only be an equality comparison.
2360 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
2361 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002362
John McCall183700f2009-09-21 23:43:11 +00002363 QualType CETy = LHSTy->getAs<ComplexType>()->getElementType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002364
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002365 Value *ResultR, *ResultI;
Chris Lattner7f02f722007-08-24 05:35:26 +00002366 if (CETy->isRealFloatingType()) {
2367 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2368 LHS.first, RHS.first, "cmp.r");
2369 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2370 LHS.second, RHS.second, "cmp.i");
2371 } else {
2372 // Complex comparisons can only be equality comparisons. As such, signed
2373 // and unsigned opcodes are the same.
2374 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2375 LHS.first, RHS.first, "cmp.r");
2376 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2377 LHS.second, RHS.second, "cmp.i");
2378 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002379
John McCall2de56d12010-08-25 11:45:40 +00002380 if (E->getOpcode() == BO_EQ) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002381 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
2382 } else {
John McCall2de56d12010-08-25 11:45:40 +00002383 assert(E->getOpcode() == BO_NE &&
Chris Lattner7f02f722007-08-24 05:35:26 +00002384 "Complex comparison other than == or != ?");
2385 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
2386 }
2387 }
Nuno Lopes32f62092009-01-11 23:22:37 +00002388
2389 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
Chris Lattner7f02f722007-08-24 05:35:26 +00002390}
2391
2392Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002393 bool Ignore = TestAndClearIgnoreResultAssign();
2394
John McCallf85e1932011-06-15 23:02:42 +00002395 Value *RHS;
2396 LValue LHS;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002397
John McCallf85e1932011-06-15 23:02:42 +00002398 switch (E->getLHS()->getType().getObjCLifetime()) {
2399 case Qualifiers::OCL_Strong:
2400 llvm::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
2401 break;
2402
2403 case Qualifiers::OCL_Autoreleasing:
2404 llvm::tie(LHS,RHS) = CGF.EmitARCStoreAutoreleasing(E);
2405 break;
2406
2407 case Qualifiers::OCL_Weak:
2408 RHS = Visit(E->getRHS());
Richard Smith7ac9ef12012-09-08 02:08:36 +00002409 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
John McCallf85e1932011-06-15 23:02:42 +00002410 RHS = CGF.EmitARCStoreWeak(LHS.getAddress(), RHS, Ignore);
2411 break;
2412
2413 // No reason to do any of these differently.
2414 case Qualifiers::OCL_None:
2415 case Qualifiers::OCL_ExplicitNone:
2416 // __block variables need to have the rhs evaluated first, plus
2417 // this should improve codegen just a little.
2418 RHS = Visit(E->getRHS());
Richard Smith7ac9ef12012-09-08 02:08:36 +00002419 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
John McCallf85e1932011-06-15 23:02:42 +00002420
2421 // Store the value into the LHS. Bit-fields are handled specially
2422 // because the result is altered by the store, i.e., [C99 6.5.16p1]
2423 // 'An assignment expression has the value of the left operand after
2424 // the assignment...'.
2425 if (LHS.isBitField())
John McCall545d9962011-06-25 02:11:03 +00002426 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
John McCallf85e1932011-06-15 23:02:42 +00002427 else
John McCall545d9962011-06-25 02:11:03 +00002428 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
John McCallf85e1932011-06-15 23:02:42 +00002429 }
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002430
2431 // If the result is clearly ignored, return now.
Mike Stump7f79f9b2009-05-29 15:46:01 +00002432 if (Ignore)
2433 return 0;
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002434
John McCallb418d742010-11-16 10:08:07 +00002435 // The result of an assignment in C is the assigned r-value.
David Blaikie4e4d0842012-03-11 07:00:24 +00002436 if (!CGF.getContext().getLangOpts().CPlusPlus)
John McCallb418d742010-11-16 10:08:07 +00002437 return RHS;
2438
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002439 // If the lvalue is non-volatile, return the computed value of the assignment.
2440 if (!LHS.isVolatileQualified())
2441 return RHS;
2442
2443 // Otherwise, reload the value.
John McCall545d9962011-06-25 02:11:03 +00002444 return EmitLoadOfLValue(LHS);
Chris Lattner7f02f722007-08-24 05:35:26 +00002445}
2446
2447Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00002448
2449 // Perform vector logical and on comparisons with zero vectors.
2450 if (E->getType()->isVectorType()) {
2451 Value *LHS = Visit(E->getLHS());
2452 Value *RHS = Visit(E->getRHS());
2453 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
2454 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
2455 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
2456 Value *And = Builder.CreateAnd(LHS, RHS);
2457 return Builder.CreateSExt(And, Zero->getType(), "sext");
2458 }
2459
Chris Lattner2acc6e32011-07-18 04:24:23 +00002460 llvm::Type *ResTy = ConvertType(E->getType());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002461
Chris Lattner20eb09d2008-11-12 08:26:50 +00002462 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
2463 // If we have 1 && X, just emit X without inserting the control flow.
Chris Lattnerc2c90012011-02-27 23:02:32 +00002464 bool LHSCondVal;
2465 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
2466 if (LHSCondVal) { // If we have 1 && X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00002467 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002468 // ZExt result to int or bool.
2469 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
Chris Lattner0946ccd2008-11-11 07:41:27 +00002470 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002471
Chris Lattner7804bcb2009-10-17 04:24:20 +00002472 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
Chris Lattner20eb09d2008-11-12 08:26:50 +00002473 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner7804bcb2009-10-17 04:24:20 +00002474 return llvm::Constant::getNullValue(ResTy);
Chris Lattner0946ccd2008-11-11 07:41:27 +00002475 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002476
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002477 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
2478 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
Chris Lattner20eb09d2008-11-12 08:26:50 +00002479
John McCall150b4622011-01-26 04:00:11 +00002480 CodeGenFunction::ConditionalEvaluation eval(CGF);
2481
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002482 // Branch on the LHS first. If it is false, go to the failure (cont) block.
2483 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
2484
2485 // Any edges into the ContBlock are now from an (indeterminate number of)
2486 // edges from this first condition. All of these values will be false. Start
2487 // setting up the PHI node in the Cont Block for this.
Jay Foadbbf3bac2011-03-30 11:28:58 +00002488 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
Owen Anderson0032b272009-08-13 21:57:51 +00002489 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002490 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2491 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00002492 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002493
John McCall150b4622011-01-26 04:00:11 +00002494 eval.begin(CGF);
Chris Lattner7f02f722007-08-24 05:35:26 +00002495 CGF.EmitBlock(RHSBlock);
2496 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
John McCall150b4622011-01-26 04:00:11 +00002497 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002498
Chris Lattner7f02f722007-08-24 05:35:26 +00002499 // Reaquire the RHS block, as there may be subblocks inserted.
2500 RHSBlock = Builder.GetInsertBlock();
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002501
2502 // Emit an unconditional branch from this block to ContBlock. Insert an entry
2503 // into the phi node for the edge with the value of RHSCond.
Devang Patelacd72362011-03-30 00:08:31 +00002504 if (CGF.getDebugInfo())
2505 // There is no need to emit line number for unconditional branch.
2506 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
Chris Lattner7f02f722007-08-24 05:35:26 +00002507 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00002508 PN->addIncoming(RHSCond, RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002509
Chris Lattner7f02f722007-08-24 05:35:26 +00002510 // ZExt result to int.
Chris Lattner7804bcb2009-10-17 04:24:20 +00002511 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00002512}
2513
2514Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00002515
2516 // Perform vector logical or on comparisons with zero vectors.
2517 if (E->getType()->isVectorType()) {
2518 Value *LHS = Visit(E->getLHS());
2519 Value *RHS = Visit(E->getRHS());
2520 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
2521 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
2522 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
2523 Value *Or = Builder.CreateOr(LHS, RHS);
2524 return Builder.CreateSExt(Or, Zero->getType(), "sext");
2525 }
2526
Chris Lattner2acc6e32011-07-18 04:24:23 +00002527 llvm::Type *ResTy = ConvertType(E->getType());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002528
Chris Lattner20eb09d2008-11-12 08:26:50 +00002529 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
2530 // If we have 0 || X, just emit X without inserting the control flow.
Chris Lattnerc2c90012011-02-27 23:02:32 +00002531 bool LHSCondVal;
2532 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
2533 if (!LHSCondVal) { // If we have 0 || X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00002534 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002535 // ZExt result to int or bool.
2536 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
Chris Lattner0946ccd2008-11-11 07:41:27 +00002537 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002538
Chris Lattner7804bcb2009-10-17 04:24:20 +00002539 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
Chris Lattner20eb09d2008-11-12 08:26:50 +00002540 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner7804bcb2009-10-17 04:24:20 +00002541 return llvm::ConstantInt::get(ResTy, 1);
Chris Lattner0946ccd2008-11-11 07:41:27 +00002542 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002543
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002544 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
2545 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002546
John McCall150b4622011-01-26 04:00:11 +00002547 CodeGenFunction::ConditionalEvaluation eval(CGF);
2548
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002549 // Branch on the LHS first. If it is true, go to the success (cont) block.
2550 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
2551
2552 // Any edges into the ContBlock are now from an (indeterminate number of)
2553 // edges from this first condition. All of these values will be true. Start
2554 // setting up the PHI node in the Cont Block for this.
Jay Foadbbf3bac2011-03-30 11:28:58 +00002555 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
Owen Anderson0032b272009-08-13 21:57:51 +00002556 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002557 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2558 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00002559 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002560
John McCall150b4622011-01-26 04:00:11 +00002561 eval.begin(CGF);
Anders Carlsson33da07d2009-06-04 02:53:13 +00002562
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002563 // Emit the RHS condition as a bool value.
Chris Lattner7f02f722007-08-24 05:35:26 +00002564 CGF.EmitBlock(RHSBlock);
2565 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002566
John McCall150b4622011-01-26 04:00:11 +00002567 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002568
Chris Lattner7f02f722007-08-24 05:35:26 +00002569 // Reaquire the RHS block, as there may be subblocks inserted.
2570 RHSBlock = Builder.GetInsertBlock();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002571
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002572 // Emit an unconditional branch from this block to ContBlock. Insert an entry
2573 // into the phi node for the edge with the value of RHSCond.
2574 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00002575 PN->addIncoming(RHSCond, RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002576
Chris Lattner7f02f722007-08-24 05:35:26 +00002577 // ZExt result to int.
Chris Lattner7804bcb2009-10-17 04:24:20 +00002578 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00002579}
2580
2581Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
John McCall2a416372010-12-05 02:00:02 +00002582 CGF.EmitIgnoredExpr(E->getLHS());
Daniel Dunbara448fb22008-11-11 23:11:34 +00002583 CGF.EnsureInsertPoint();
Chris Lattner7f02f722007-08-24 05:35:26 +00002584 return Visit(E->getRHS());
2585}
2586
2587//===----------------------------------------------------------------------===//
2588// Other Operators
2589//===----------------------------------------------------------------------===//
2590
Chris Lattner9802a512008-11-12 08:55:54 +00002591/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
2592/// expression is cheap enough and side-effect-free enough to evaluate
2593/// unconditionally instead of conditionally. This is used to convert control
2594/// flow into selects in some cases.
Mike Stumpdf317bf2009-11-03 23:25:48 +00002595static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
2596 CodeGenFunction &CGF) {
Peter Collingbournef111d932011-04-15 00:35:48 +00002597 E = E->IgnoreParens();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002598
Chris Lattnerc6bea672011-04-16 23:15:35 +00002599 // Anything that is an integer or floating point constant is fine.
2600 if (E->isConstantInitializer(CGF.getContext(), false))
Chris Lattner9802a512008-11-12 08:55:54 +00002601 return true;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002602
Chris Lattner9802a512008-11-12 08:55:54 +00002603 // Non-volatile automatic variables too, to get "cond ? X : Y" where
2604 // X and Y are local variables.
2605 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2606 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Mike Stumpdf317bf2009-11-03 23:25:48 +00002607 if (VD->hasLocalStorage() && !(CGF.getContext()
2608 .getCanonicalType(VD->getType())
2609 .isVolatileQualified()))
Chris Lattner9802a512008-11-12 08:55:54 +00002610 return true;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002611
Chris Lattner9802a512008-11-12 08:55:54 +00002612 return false;
2613}
2614
2615
Chris Lattner7f02f722007-08-24 05:35:26 +00002616Value *ScalarExprEmitter::
John McCall56ca35d2011-02-17 10:25:35 +00002617VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002618 TestAndClearIgnoreResultAssign();
John McCall56ca35d2011-02-17 10:25:35 +00002619
2620 // Bind the common expression if necessary.
Eli Friedmand97927d2012-01-06 20:42:20 +00002621 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
John McCall56ca35d2011-02-17 10:25:35 +00002622
2623 Expr *condExpr = E->getCond();
2624 Expr *lhsExpr = E->getTrueExpr();
2625 Expr *rhsExpr = E->getFalseExpr();
2626
Chris Lattner31a09842008-11-12 08:04:58 +00002627 // If the condition constant folds and can be elided, try to avoid emitting
2628 // the condition and the dead arm.
Chris Lattnerc2c90012011-02-27 23:02:32 +00002629 bool CondExprBool;
2630 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCall56ca35d2011-02-17 10:25:35 +00002631 Expr *live = lhsExpr, *dead = rhsExpr;
Chris Lattnerc2c90012011-02-27 23:02:32 +00002632 if (!CondExprBool) std::swap(live, dead);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002633
Eli Friedmanc8645e32011-10-15 02:10:40 +00002634 // If the dead side doesn't have labels we need, just emit the Live part.
2635 if (!CGF.ContainsLabel(dead)) {
2636 Value *Result = Visit(live);
2637
2638 // If the live part is a throw expression, it acts like it has a void
2639 // type, so evaluating it returns a null Value*. However, a conditional
2640 // with non-void type must return a non-null Value*.
2641 if (!Result && !E->getType()->isVoidType())
2642 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
2643
2644 return Result;
2645 }
Chris Lattnerc657e922008-11-11 18:56:45 +00002646 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002647
Nate Begeman6155d732010-09-20 22:41:17 +00002648 // OpenCL: If the condition is a vector, we can treat this condition like
2649 // the select function.
David Blaikie4e4d0842012-03-11 07:00:24 +00002650 if (CGF.getContext().getLangOpts().OpenCL
John McCall56ca35d2011-02-17 10:25:35 +00002651 && condExpr->getType()->isVectorType()) {
2652 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
2653 llvm::Value *LHS = Visit(lhsExpr);
2654 llvm::Value *RHS = Visit(rhsExpr);
Nate Begeman6155d732010-09-20 22:41:17 +00002655
Chris Lattner2acc6e32011-07-18 04:24:23 +00002656 llvm::Type *condType = ConvertType(condExpr->getType());
2657 llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
Nate Begeman6155d732010-09-20 22:41:17 +00002658
2659 unsigned numElem = vecTy->getNumElements();
Chris Lattner2acc6e32011-07-18 04:24:23 +00002660 llvm::Type *elemType = vecTy->getElementType();
Nate Begeman6155d732010-09-20 22:41:17 +00002661
Chris Lattner2ce88422012-01-25 05:34:41 +00002662 llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy);
Nate Begeman6155d732010-09-20 22:41:17 +00002663 llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
2664 llvm::Value *tmp = Builder.CreateSExt(TestMSB,
2665 llvm::VectorType::get(elemType,
2666 numElem),
2667 "sext");
2668 llvm::Value *tmp2 = Builder.CreateNot(tmp);
2669
2670 // Cast float to int to perform ANDs if necessary.
2671 llvm::Value *RHSTmp = RHS;
2672 llvm::Value *LHSTmp = LHS;
2673 bool wasCast = false;
Chris Lattner2acc6e32011-07-18 04:24:23 +00002674 llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
Peter Collingbourne565204d2012-05-29 00:35:18 +00002675 if (rhsVTy->getElementType()->isFloatingPointTy()) {
Nate Begeman6155d732010-09-20 22:41:17 +00002676 RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
2677 LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
2678 wasCast = true;
2679 }
2680
2681 llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
2682 llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
2683 llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
2684 if (wasCast)
2685 tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
2686
2687 return tmp5;
2688 }
2689
Chris Lattner9802a512008-11-12 08:55:54 +00002690 // If this is a really simple expression (like x ? 4 : 5), emit this as a
2691 // select instead of as control flow. We can only do this if it is cheap and
Chris Lattner531a5502008-11-16 06:16:27 +00002692 // safe to evaluate the LHS and RHS unconditionally.
John McCall56ca35d2011-02-17 10:25:35 +00002693 if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
2694 isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
2695 llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
2696 llvm::Value *LHS = Visit(lhsExpr);
2697 llvm::Value *RHS = Visit(rhsExpr);
Eli Friedman1e4f68c2011-12-08 22:01:56 +00002698 if (!LHS) {
2699 // If the conditional has void type, make sure we return a null Value*.
2700 assert(!RHS && "LHS and RHS types must match");
2701 return 0;
2702 }
Chris Lattner9802a512008-11-12 08:55:54 +00002703 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
2704 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002705
Daniel Dunbarbe65abc2008-11-12 10:13:37 +00002706 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
2707 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002708 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
John McCall150b4622011-01-26 04:00:11 +00002709
2710 CodeGenFunction::ConditionalEvaluation eval(CGF);
John McCall56ca35d2011-02-17 10:25:35 +00002711 CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock);
Anders Carlssonfb6fa302009-06-04 03:00:32 +00002712
Chris Lattner7f02f722007-08-24 05:35:26 +00002713 CGF.EmitBlock(LHSBlock);
John McCall150b4622011-01-26 04:00:11 +00002714 eval.begin(CGF);
John McCall56ca35d2011-02-17 10:25:35 +00002715 Value *LHS = Visit(lhsExpr);
John McCall150b4622011-01-26 04:00:11 +00002716 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002717
Chris Lattner7f02f722007-08-24 05:35:26 +00002718 LHSBlock = Builder.GetInsertBlock();
John McCall150b4622011-01-26 04:00:11 +00002719 Builder.CreateBr(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002720
Chris Lattner7f02f722007-08-24 05:35:26 +00002721 CGF.EmitBlock(RHSBlock);
John McCall150b4622011-01-26 04:00:11 +00002722 eval.begin(CGF);
John McCall56ca35d2011-02-17 10:25:35 +00002723 Value *RHS = Visit(rhsExpr);
John McCall150b4622011-01-26 04:00:11 +00002724 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002725
John McCall150b4622011-01-26 04:00:11 +00002726 RHSBlock = Builder.GetInsertBlock();
Chris Lattner7f02f722007-08-24 05:35:26 +00002727 CGF.EmitBlock(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002728
Eli Friedman48daf592009-12-07 20:25:53 +00002729 // If the LHS or RHS is a throw expression, it will be legitimately null.
2730 if (!LHS)
2731 return RHS;
2732 if (!RHS)
2733 return LHS;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002734
Chris Lattner7f02f722007-08-24 05:35:26 +00002735 // Create a PHI node for the real part.
Jay Foadbbf3bac2011-03-30 11:28:58 +00002736 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
Chris Lattner7f02f722007-08-24 05:35:26 +00002737 PN->addIncoming(LHS, LHSBlock);
2738 PN->addIncoming(RHS, RHSBlock);
2739 return PN;
2740}
2741
2742Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Eli Friedman79769322009-03-04 05:52:32 +00002743 return Visit(E->getChosenSubExpr(CGF.getContext()));
Chris Lattner7f02f722007-08-24 05:35:26 +00002744}
2745
Chris Lattner2202bce2007-11-30 17:56:23 +00002746Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Eli Friedman4fd0aa52009-01-20 17:46:04 +00002747 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002748 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
2749
2750 // If EmitVAArg fails, we fall back to the LLVM instruction.
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002751 if (!ArgPtr)
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002752 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
2753
Mike Stump7f79f9b2009-05-29 15:46:01 +00002754 // FIXME Volatility.
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002755 return Builder.CreateLoad(ArgPtr);
Anders Carlsson7c50aca2007-10-15 20:28:48 +00002756}
2757
John McCall6b5a61b2011-02-07 10:33:21 +00002758Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
2759 return CGF.EmitBlockLiteral(block);
Mike Stumpdf6b68c2009-02-12 18:29:15 +00002760}
2761
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002762Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
2763 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
Chris Lattner2acc6e32011-07-18 04:24:23 +00002764 llvm::Type *DstTy = ConvertType(E->getType());
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002765
2766 // Going from vec4->vec3 or vec3->vec4 is a special case and requires
2767 // a shuffle vector instead of a bitcast.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002768 llvm::Type *SrcTy = Src->getType();
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002769 if (isa<llvm::VectorType>(DstTy) && isa<llvm::VectorType>(SrcTy)) {
2770 unsigned numElementsDst = cast<llvm::VectorType>(DstTy)->getNumElements();
2771 unsigned numElementsSrc = cast<llvm::VectorType>(SrcTy)->getNumElements();
2772 if ((numElementsDst == 3 && numElementsSrc == 4)
2773 || (numElementsDst == 4 && numElementsSrc == 3)) {
2774
2775
2776 // In the case of going from int4->float3, a bitcast is needed before
2777 // doing a shuffle.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002778 llvm::Type *srcElemTy =
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002779 cast<llvm::VectorType>(SrcTy)->getElementType();
Chris Lattner2acc6e32011-07-18 04:24:23 +00002780 llvm::Type *dstElemTy =
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002781 cast<llvm::VectorType>(DstTy)->getElementType();
2782
2783 if ((srcElemTy->isIntegerTy() && dstElemTy->isFloatTy())
2784 || (srcElemTy->isFloatTy() && dstElemTy->isIntegerTy())) {
2785 // Create a float type of the same size as the source or destination.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002786 llvm::VectorType *newSrcTy = llvm::VectorType::get(dstElemTy,
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002787 numElementsSrc);
2788
2789 Src = Builder.CreateBitCast(Src, newSrcTy, "astypeCast");
2790 }
2791
2792 llvm::Value *UnV = llvm::UndefValue::get(Src->getType());
2793
Chris Lattner5f9e2722011-07-23 10:55:15 +00002794 SmallVector<llvm::Constant*, 3> Args;
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002795 Args.push_back(Builder.getInt32(0));
2796 Args.push_back(Builder.getInt32(1));
2797 Args.push_back(Builder.getInt32(2));
2798
2799 if (numElementsDst == 4)
Chris Lattner8b418682012-02-07 00:39:47 +00002800 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002801
2802 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
2803
2804 return Builder.CreateShuffleVector(Src, UnV, Mask, "astype");
2805 }
2806 }
2807
2808 return Builder.CreateBitCast(Src, DstTy, "astype");
2809}
2810
Eli Friedman276b0612011-10-11 02:20:01 +00002811Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
2812 return CGF.EmitAtomicExpr(E).getScalarVal();
2813}
2814
Chris Lattner7f02f722007-08-24 05:35:26 +00002815//===----------------------------------------------------------------------===//
2816// Entry Point into this File
2817//===----------------------------------------------------------------------===//
2818
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002819/// EmitScalarExpr - Emit the computation of the specified expression of scalar
2820/// type, ignoring the result.
Mike Stump7f79f9b2009-05-29 15:46:01 +00002821Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002822 assert(E && !hasAggregateLLVMType(E->getType()) &&
2823 "Invalid scalar expression to emit");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002824
Devang Patel5de7a0e2011-03-07 18:29:53 +00002825 if (isa<CXXDefaultArgExpr>(E))
Devang Patelaa112892011-03-07 18:45:56 +00002826 disableDebugInfo();
Devang Patel5de7a0e2011-03-07 18:29:53 +00002827 Value *V = ScalarExprEmitter(*this, IgnoreResultAssign)
Mike Stump7f79f9b2009-05-29 15:46:01 +00002828 .Visit(const_cast<Expr*>(E));
Devang Patel5de7a0e2011-03-07 18:29:53 +00002829 if (isa<CXXDefaultArgExpr>(E))
Devang Patelaa112892011-03-07 18:45:56 +00002830 enableDebugInfo();
Devang Patel5de7a0e2011-03-07 18:29:53 +00002831 return V;
Chris Lattner7f02f722007-08-24 05:35:26 +00002832}
Chris Lattner3707b252007-08-26 06:48:56 +00002833
2834/// EmitScalarConversion - Emit a conversion from the specified type to the
2835/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002836Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
2837 QualType DstTy) {
Chris Lattner3707b252007-08-26 06:48:56 +00002838 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
2839 "Invalid scalar expression to emit");
2840 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
2841}
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002842
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002843/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
2844/// type to the specified destination type, where the destination type is an
2845/// LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002846Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
2847 QualType SrcTy,
2848 QualType DstTy) {
Chris Lattner9b2dc282008-04-04 16:54:41 +00002849 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002850 "Invalid complex -> scalar conversion");
2851 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
2852 DstTy);
2853}
Anders Carlssoncc23aca2007-12-10 19:35:18 +00002854
Chris Lattner8c11a652010-06-26 22:09:34 +00002855
2856llvm::Value *CodeGenFunction::
2857EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2858 bool isInc, bool isPre) {
2859 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
2860}
2861
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002862LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
2863 llvm::Value *V;
2864 // object->isa or (*object).isa
2865 // Generate code as for: *(Class*)object
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002866 // build Class* type
Chris Lattner2acc6e32011-07-18 04:24:23 +00002867 llvm::Type *ClassPtrTy = ConvertType(E->getType());
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00002868
2869 Expr *BaseExpr = E->getBase();
John McCall7eb0a9e2010-11-24 05:12:34 +00002870 if (BaseExpr->isRValue()) {
Eli Friedmand71f4422011-12-19 23:03:09 +00002871 V = CreateMemTemp(E->getType(), "resval");
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00002872 llvm::Value *Src = EmitScalarExpr(BaseExpr);
2873 Builder.CreateStore(Src, V);
Daniel Dunbar9f553f52010-08-21 03:08:16 +00002874 V = ScalarExprEmitter(*this).EmitLoadOfLValue(
Eli Friedmand71f4422011-12-19 23:03:09 +00002875 MakeNaturalAlignAddrLValue(V, E->getType()));
Daniel Dunbar9f553f52010-08-21 03:08:16 +00002876 } else {
2877 if (E->isArrow())
2878 V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr);
2879 else
2880 V = EmitLValue(BaseExpr).getAddress();
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00002881 }
2882
2883 // build Class* type
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002884 ClassPtrTy = ClassPtrTy->getPointerTo();
2885 V = Builder.CreateBitCast(V, ClassPtrTy);
Eli Friedmand71f4422011-12-19 23:03:09 +00002886 return MakeNaturalAlignAddrLValue(V, E->getType());
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002887}
2888
Douglas Gregor6a03e342010-04-23 04:16:32 +00002889
John McCall2a416372010-12-05 02:00:02 +00002890LValue CodeGenFunction::EmitCompoundAssignmentLValue(
Douglas Gregor6a03e342010-04-23 04:16:32 +00002891 const CompoundAssignOperator *E) {
2892 ScalarExprEmitter Scalar(*this);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002893 Value *Result = 0;
Douglas Gregor6a03e342010-04-23 04:16:32 +00002894 switch (E->getOpcode()) {
2895#define COMPOUND_OP(Op) \
John McCall2de56d12010-08-25 11:45:40 +00002896 case BO_##Op##Assign: \
Douglas Gregor6a03e342010-04-23 04:16:32 +00002897 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002898 Result)
Douglas Gregor6a03e342010-04-23 04:16:32 +00002899 COMPOUND_OP(Mul);
2900 COMPOUND_OP(Div);
2901 COMPOUND_OP(Rem);
2902 COMPOUND_OP(Add);
2903 COMPOUND_OP(Sub);
2904 COMPOUND_OP(Shl);
2905 COMPOUND_OP(Shr);
2906 COMPOUND_OP(And);
2907 COMPOUND_OP(Xor);
2908 COMPOUND_OP(Or);
2909#undef COMPOUND_OP
2910
John McCall2de56d12010-08-25 11:45:40 +00002911 case BO_PtrMemD:
2912 case BO_PtrMemI:
2913 case BO_Mul:
2914 case BO_Div:
2915 case BO_Rem:
2916 case BO_Add:
2917 case BO_Sub:
2918 case BO_Shl:
2919 case BO_Shr:
2920 case BO_LT:
2921 case BO_GT:
2922 case BO_LE:
2923 case BO_GE:
2924 case BO_EQ:
2925 case BO_NE:
2926 case BO_And:
2927 case BO_Xor:
2928 case BO_Or:
2929 case BO_LAnd:
2930 case BO_LOr:
2931 case BO_Assign:
2932 case BO_Comma:
David Blaikieb219cfc2011-09-23 05:06:16 +00002933 llvm_unreachable("Not valid compound assignment operators");
Douglas Gregor6a03e342010-04-23 04:16:32 +00002934 }
2935
2936 llvm_unreachable("Unhandled compound assignment operator");
2937}