blob: 6f65638236583c01e511b7a761f03a6ec2692abc [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
14#include "CodeGenFunction.h"
Fariborz Jahanianf7bcc7e2009-10-10 20:07:56 +000015#include "CGObjCRuntime.h"
Chris Lattner7f02f722007-08-24 05:35:26 +000016#include "CodeGenModule.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbar98c5ead2008-08-12 05:08:18 +000018#include "clang/AST/DeclObjC.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000019#include "clang/AST/RecordLayout.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000020#include "clang/AST/StmtVisitor.h"
Chris Lattner25ddea72008-04-20 00:50:39 +000021#include "clang/Basic/TargetInfo.h"
Chris Lattner7f02f722007-08-24 05:35:26 +000022#include "llvm/Constants.h"
23#include "llvm/Function.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000024#include "llvm/GlobalVariable.h"
Anders Carlsson7c50aca2007-10-15 20:28:48 +000025#include "llvm/Intrinsics.h"
Mike Stump2add4732009-04-01 20:28:16 +000026#include "llvm/Module.h"
Chris Lattnerf7b5ea92008-11-12 08:38:24 +000027#include "llvm/Support/CFG.h"
Mike Stump4e7a1f72009-02-21 20:00:35 +000028#include "llvm/Target/TargetData.h"
Chris Lattnerc89bf692008-01-03 07:05:49 +000029#include <cstdarg>
Ted Kremenek6aad91a2007-12-10 23:44:32 +000030
Chris Lattner7f02f722007-08-24 05:35:26 +000031using namespace clang;
32using namespace CodeGen;
33using llvm::Value;
34
35//===----------------------------------------------------------------------===//
36// Scalar Expression Emitter
37//===----------------------------------------------------------------------===//
38
39struct BinOpInfo {
40 Value *LHS;
41 Value *RHS;
Chris Lattner1f1ded92007-08-24 21:00:35 +000042 QualType Ty; // Computation Type.
Chris Lattner7f02f722007-08-24 05:35:26 +000043 const BinaryOperator *E;
44};
45
46namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +000047class ScalarExprEmitter
Chris Lattner7f02f722007-08-24 05:35:26 +000048 : public StmtVisitor<ScalarExprEmitter, Value*> {
49 CodeGenFunction &CGF;
Daniel Dunbar45d196b2008-11-01 01:53:16 +000050 CGBuilderTy &Builder;
Mike Stump7f79f9b2009-05-29 15:46:01 +000051 bool IgnoreResultAssign;
Owen Andersona1cf15f2009-07-14 23:10:40 +000052 llvm::LLVMContext &VMContext;
Chris Lattner7f02f722007-08-24 05:35:26 +000053public:
54
Mike Stump7f79f9b2009-05-29 15:46:01 +000055 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
Mike Stumpdb52dcd2009-09-09 13:00:44 +000056 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
Owen Andersona1cf15f2009-07-14 23:10:40 +000057 VMContext(cgf.getLLVMContext()) {
Chris Lattner7f02f722007-08-24 05:35:26 +000058 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +000059
Chris Lattner7f02f722007-08-24 05:35:26 +000060 //===--------------------------------------------------------------------===//
61 // Utilities
62 //===--------------------------------------------------------------------===//
63
Mike Stump7f79f9b2009-05-29 15:46:01 +000064 bool TestAndClearIgnoreResultAssign() {
Chris Lattner9c10fcf2009-07-08 01:08:03 +000065 bool I = IgnoreResultAssign;
66 IgnoreResultAssign = false;
67 return I;
68 }
Mike Stump7f79f9b2009-05-29 15:46:01 +000069
Chris Lattner7f02f722007-08-24 05:35:26 +000070 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
71 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
72
73 Value *EmitLoadOfLValue(LValue LV, QualType T) {
Chris Lattner9b655512007-08-31 22:49:20 +000074 return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +000075 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +000076
Chris Lattner7f02f722007-08-24 05:35:26 +000077 /// EmitLoadOfLValue - Given an expression with complex type that represents a
78 /// value l-value, this method emits the address of the l-value, then loads
79 /// and returns the result.
80 Value *EmitLoadOfLValue(const Expr *E) {
Chris Lattner7f02f722007-08-24 05:35:26 +000081 return EmitLoadOfLValue(EmitLValue(E), E->getType());
82 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +000083
Chris Lattner9abc84e2007-08-26 16:42:57 +000084 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +000085 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +000086 Value *EmitConversionToBool(Value *Src, QualType DstTy);
Mike Stumpdb52dcd2009-09-09 13:00:44 +000087
Chris Lattner3707b252007-08-26 06:48:56 +000088 /// EmitScalarConversion - Emit a conversion from the specified type to the
89 /// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +000090 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
91
92 /// EmitComplexToScalarConversion - Emit a conversion from the specified
Mike Stumpdb52dcd2009-09-09 13:00:44 +000093 /// complex type to the specified destination type, where the destination type
94 /// is an LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +000095 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
96 QualType SrcTy, QualType DstTy);
Mike Stumpdf6b68c2009-02-12 18:29:15 +000097
Chris Lattner7f02f722007-08-24 05:35:26 +000098 //===--------------------------------------------------------------------===//
99 // Visitor Methods
100 //===--------------------------------------------------------------------===//
101
102 Value *VisitStmt(Stmt *S) {
Ted Kremenek7a9d49f2007-12-11 21:27:55 +0000103 S->dump(CGF.getContext().getSourceManager());
Chris Lattner7f02f722007-08-24 05:35:26 +0000104 assert(0 && "Stmt can't have complex result type!");
105 return 0;
106 }
107 Value *VisitExpr(Expr *S);
Fariborz Jahanianf51dc642009-10-21 23:45:42 +0000108
Chris Lattner7f02f722007-08-24 05:35:26 +0000109 Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
110
111 // Leaves.
112 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000113 return llvm::ConstantInt::get(VMContext, E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000114 }
115 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Owen Andersonbc0a2222009-07-27 21:00:51 +0000116 return llvm::ConstantFP::get(VMContext, E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000117 }
118 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000119 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000120 }
Nate Begemane7579b52007-11-15 05:40:03 +0000121 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000122 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Nate Begemane7579b52007-11-15 05:40:03 +0000123 }
Argyrios Kyrtzidis7267f782008-08-23 19:35:47 +0000124 Value *VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
Owen Andersonc9c88b42009-07-31 20:28:54 +0000125 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Argyrios Kyrtzidis7267f782008-08-23 19:35:47 +0000126 }
Anders Carlsson3f704562008-12-21 22:39:40 +0000127 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
Owen Andersonc9c88b42009-07-31 20:28:54 +0000128 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Anders Carlsson3f704562008-12-21 22:39:40 +0000129 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000130 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000131 return llvm::ConstantInt::get(ConvertType(E->getType()),
Steve Naroffec0550f2007-10-15 20:41:53 +0000132 CGF.getContext().typesAreCompatible(
133 E->getArgType1(), E->getArgType2()));
Chris Lattner7f02f722007-08-24 05:35:26 +0000134 }
Sebastian Redl05189992008-11-11 17:56:53 +0000135 Value *VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000136 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
Chris Lattnerd9becd12009-10-28 23:59:40 +0000137 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
138 return Builder.CreateBitCast(V, ConvertType(E->getType()));
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000139 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000140
Chris Lattner7f02f722007-08-24 05:35:26 +0000141 // l-values.
142 Value *VisitDeclRefExpr(DeclRefExpr *E) {
Eli Friedman28665272009-11-26 03:22:21 +0000143 Expr::EvalResult Result;
144 if (E->Evaluate(Result, CGF.getContext()) && Result.Val.isInt()) {
145 assert(!Result.HasSideEffects && "Constant declref with side-effect?!");
146 return llvm::ConstantInt::get(VMContext, Result.Val.getInt());
147 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000148 return EmitLoadOfLValue(E);
149 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000150 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
151 return CGF.EmitObjCSelectorExpr(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000152 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000153 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
154 return CGF.EmitObjCProtocolExpr(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000155 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000156 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000157 return EmitLoadOfLValue(E);
158 }
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000159 Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
Daniel Dunbar85c59ed2008-08-29 08:11:39 +0000160 return EmitLoadOfLValue(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000161 }
Fariborz Jahanian09105f52009-08-20 17:02:02 +0000162 Value *VisitObjCImplicitSetterGetterRefExpr(
163 ObjCImplicitSetterGetterRefExpr *E) {
Fariborz Jahanian43f44702008-11-22 22:30:21 +0000164 return EmitLoadOfLValue(E);
165 }
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000166 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
167 return CGF.EmitObjCMessageExpr(E).getScalarVal();
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000168 }
169
Fariborz Jahanian83dc3252009-12-09 19:05:56 +0000170 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
Fariborz Jahanian820bca42009-12-09 23:35:29 +0000171 LValue LV = CGF.EmitObjCIsaExpr(E);
172 Value *V = CGF.EmitLoadOfLValue(LV, E->getType()).getScalarVal();
Fariborz Jahanian83dc3252009-12-09 19:05:56 +0000173 return V;
174 }
175
Chris Lattner7f02f722007-08-24 05:35:26 +0000176 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmand38617c2008-05-14 19:38:39 +0000177 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Eli Friedman28665272009-11-26 03:22:21 +0000178 Value *VisitMemberExpr(MemberExpr *E);
Nate Begeman213541a2008-04-18 23:10:10 +0000179 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Chris Lattnerbe20bb52008-10-26 23:53:12 +0000180 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
181 return EmitLoadOfLValue(E);
182 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000183 Value *VisitStringLiteral(Expr *E) { return EmitLValue(E).getAddress(); }
Chris Lattnereaf2bb82009-02-24 22:18:39 +0000184 Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
185 return EmitLValue(E).getAddress();
186 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000187
Chris Lattnerd9f69102008-08-10 01:53:14 +0000188 Value *VisitPredefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); }
Devang Patel35634f52007-10-24 17:18:43 +0000189
Nate Begeman0533b302009-10-18 20:10:40 +0000190 Value *VisitInitListExpr(InitListExpr *E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000191
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000192 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Owen Andersonc9c88b42009-07-31 20:28:54 +0000193 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000194 }
Eli Friedmand8889622009-11-27 04:41:50 +0000195 Value *VisitCastExpr(CastExpr *E) {
Eli Friedmanc62aad82009-04-20 03:54:15 +0000196 // Make sure to evaluate VLA bounds now so that we have them for later.
197 if (E->getType()->isVariablyModifiedType())
198 CGF.EmitVLASize(E->getType());
199
Anders Carlsson592a2bb2009-09-22 22:00:46 +0000200 return EmitCastExpr(E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000201 }
Eli Friedmand8889622009-11-27 04:41:50 +0000202 Value *EmitCastExpr(CastExpr *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000203
204 Value *VisitCallExpr(const CallExpr *E) {
Anders Carlssone9f2f452009-05-27 03:37:57 +0000205 if (E->getCallReturnType()->isReferenceType())
206 return EmitLoadOfLValue(E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000207
Chris Lattner9b655512007-08-31 22:49:20 +0000208 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +0000209 }
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000210
Chris Lattner33793202007-08-31 22:09:40 +0000211 Value *VisitStmtExpr(const StmtExpr *E);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000212
Mike Stumpa99038c2009-02-28 09:07:16 +0000213 Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000214
Chris Lattner7f02f722007-08-24 05:35:26 +0000215 // Unary Operators.
216 Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre);
217 Value *VisitUnaryPostDec(const UnaryOperator *E) {
218 return VisitPrePostIncDec(E, false, false);
219 }
220 Value *VisitUnaryPostInc(const UnaryOperator *E) {
221 return VisitPrePostIncDec(E, true, false);
222 }
223 Value *VisitUnaryPreDec(const UnaryOperator *E) {
224 return VisitPrePostIncDec(E, false, true);
225 }
226 Value *VisitUnaryPreInc(const UnaryOperator *E) {
227 return VisitPrePostIncDec(E, true, true);
228 }
229 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
230 return EmitLValue(E->getSubExpr()).getAddress();
231 }
232 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
233 Value *VisitUnaryPlus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000234 // This differs from gcc, though, most likely due to a bug in gcc.
235 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +0000236 return Visit(E->getSubExpr());
237 }
238 Value *VisitUnaryMinus (const UnaryOperator *E);
239 Value *VisitUnaryNot (const UnaryOperator *E);
240 Value *VisitUnaryLNot (const UnaryOperator *E);
Chris Lattner46f93d02007-08-24 21:20:17 +0000241 Value *VisitUnaryReal (const UnaryOperator *E);
242 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000243 Value *VisitUnaryExtension(const UnaryOperator *E) {
244 return Visit(E->getSubExpr());
245 }
Anders Carlsson5a1deb82008-01-29 15:56:48 +0000246 Value *VisitUnaryOffsetOf(const UnaryOperator *E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000247
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000248 // C++
Chris Lattner04421082008-04-08 04:40:51 +0000249 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
250 return Visit(DAE->getExpr());
251 }
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000252 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
253 return CGF.LoadCXXThis();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000254 }
255
Anders Carlsson7f6ad152009-05-19 04:48:36 +0000256 Value *VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) {
Anders Carlsson30824632009-05-31 00:09:15 +0000257 return CGF.EmitCXXExprWithTemporaries(E).getScalarVal();
Anders Carlsson7f6ad152009-05-19 04:48:36 +0000258 }
Anders Carlssona00703d2009-05-31 01:40:14 +0000259 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
260 return CGF.EmitCXXNewExpr(E);
261 }
Anders Carlsson60e282c2009-08-16 21:13:42 +0000262 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
263 CGF.EmitCXXDeleteExpr(E);
264 return 0;
265 }
Eli Friedman9dfebdc2009-12-10 22:40:32 +0000266 Value *VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
267 return llvm::ConstantInt::get(Builder.getInt1Ty(),
268 E->EvaluateTrait(CGF.getContext()));
269 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000270
Douglas Gregora71d8192009-09-04 17:36:40 +0000271 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
272 // C++ [expr.pseudo]p1:
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000273 // The result shall only be used as the operand for the function call
Douglas Gregora71d8192009-09-04 17:36:40 +0000274 // operator (), and the result of such a call has type void. The only
275 // effect is the evaluation of the postfix-expression before the dot or
276 // arrow.
277 CGF.EmitScalarExpr(E->getBase());
278 return 0;
279 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000280
Anders Carlssonc1eb14a2009-09-15 04:39:46 +0000281 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
282 return llvm::Constant::getNullValue(ConvertType(E->getType()));
283 }
Anders Carlsson756b5c42009-10-30 01:42:31 +0000284
285 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
286 CGF.EmitCXXThrowExpr(E);
287 return 0;
288 }
289
Chris Lattner7f02f722007-08-24 05:35:26 +0000290 // Binary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000291 Value *EmitMul(const BinOpInfo &Ops) {
Mike Stump035cf892009-04-02 18:15:54 +0000292 if (CGF.getContext().getLangOptions().OverflowChecking
293 && Ops.Ty->isSignedIntegerType())
Mike Stump2add4732009-04-01 20:28:16 +0000294 return EmitOverflowCheckedBinOp(Ops);
Chris Lattner87415d22009-06-17 06:36:24 +0000295 if (Ops.LHS->getType()->isFPOrFPVector())
296 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
Chris Lattner7f02f722007-08-24 05:35:26 +0000297 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
298 }
Mike Stump2add4732009-04-01 20:28:16 +0000299 /// Create a binary op that checks for overflow.
300 /// Currently only supports +, - and *.
301 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
Chris Lattner7f02f722007-08-24 05:35:26 +0000302 Value *EmitDiv(const BinOpInfo &Ops);
303 Value *EmitRem(const BinOpInfo &Ops);
304 Value *EmitAdd(const BinOpInfo &Ops);
305 Value *EmitSub(const BinOpInfo &Ops);
306 Value *EmitShl(const BinOpInfo &Ops);
307 Value *EmitShr(const BinOpInfo &Ops);
308 Value *EmitAnd(const BinOpInfo &Ops) {
309 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
310 }
311 Value *EmitXor(const BinOpInfo &Ops) {
312 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
313 }
314 Value *EmitOr (const BinOpInfo &Ops) {
315 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
316 }
317
Chris Lattner1f1ded92007-08-24 21:00:35 +0000318 BinOpInfo EmitBinOps(const BinaryOperator *E);
Chris Lattner3ccf7742007-08-26 21:41:21 +0000319 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner1f1ded92007-08-24 21:00:35 +0000320 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
321
322 // Binary operators and binary compound assignment operators.
323#define HANDLEBINOP(OP) \
Chris Lattner3ccf7742007-08-26 21:41:21 +0000324 Value *VisitBin ## OP(const BinaryOperator *E) { \
325 return Emit ## OP(EmitBinOps(E)); \
326 } \
327 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
328 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner1f1ded92007-08-24 21:00:35 +0000329 }
330 HANDLEBINOP(Mul);
331 HANDLEBINOP(Div);
332 HANDLEBINOP(Rem);
333 HANDLEBINOP(Add);
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000334 HANDLEBINOP(Sub);
Chris Lattner1f1ded92007-08-24 21:00:35 +0000335 HANDLEBINOP(Shl);
336 HANDLEBINOP(Shr);
337 HANDLEBINOP(And);
338 HANDLEBINOP(Xor);
339 HANDLEBINOP(Or);
340#undef HANDLEBINOP
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000341
Chris Lattner7f02f722007-08-24 05:35:26 +0000342 // Comparisons.
343 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
344 unsigned SICmpOpc, unsigned FCmpOpc);
345#define VISITCOMP(CODE, UI, SI, FP) \
346 Value *VisitBin##CODE(const BinaryOperator *E) { \
347 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
348 llvm::FCmpInst::FP); }
349 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
350 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
351 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
352 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
353 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
354 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
355#undef VISITCOMP
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000356
Chris Lattner7f02f722007-08-24 05:35:26 +0000357 Value *VisitBinAssign (const BinaryOperator *E);
358
359 Value *VisitBinLAnd (const BinaryOperator *E);
360 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000361 Value *VisitBinComma (const BinaryOperator *E);
362
Eli Friedman25b825d2009-11-18 09:41:26 +0000363 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
364 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
365
Chris Lattner7f02f722007-08-24 05:35:26 +0000366 // Other Operators.
Mike Stumpdf6b68c2009-02-12 18:29:15 +0000367 Value *VisitBlockExpr(const BlockExpr *BE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000368 Value *VisitConditionalOperator(const ConditionalOperator *CO);
369 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000370 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000371 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
372 return CGF.EmitObjCStringLiteral(E);
373 }
374};
375} // end anonymous namespace.
376
377//===----------------------------------------------------------------------===//
378// Utilities
379//===----------------------------------------------------------------------===//
380
Chris Lattner9abc84e2007-08-26 16:42:57 +0000381/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +0000382/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +0000383Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
John McCall467b27b2009-10-22 20:10:53 +0000384 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000385
Chris Lattner9abc84e2007-08-26 16:42:57 +0000386 if (SrcType->isRealFloatingType()) {
387 // Compare against 0.0 for fp scalars.
Owen Andersonc9c88b42009-07-31 20:28:54 +0000388 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattner9abc84e2007-08-26 16:42:57 +0000389 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
390 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000391
Anders Carlsson237957c2009-08-09 18:26:27 +0000392 if (SrcType->isMemberPointerType()) {
393 // FIXME: This is ABI specific.
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000394
Anders Carlsson237957c2009-08-09 18:26:27 +0000395 // Compare against -1.
396 llvm::Value *NegativeOne = llvm::Constant::getAllOnesValue(Src->getType());
397 return Builder.CreateICmpNE(Src, NegativeOne, "tobool");
398 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000399
Daniel Dunbard1d66bc2008-08-25 10:38:11 +0000400 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
Chris Lattner9abc84e2007-08-26 16:42:57 +0000401 "Unknown scalar type to convert");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000402
Chris Lattner9abc84e2007-08-26 16:42:57 +0000403 // Because of the type rules of C, we often end up computing a logical value,
404 // then zero extending it to int, then wanting it as a logical value again.
405 // Optimize this common case.
406 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
Owen Anderson0032b272009-08-13 21:57:51 +0000407 if (ZI->getOperand(0)->getType() ==
408 llvm::Type::getInt1Ty(CGF.getLLVMContext())) {
Chris Lattner9abc84e2007-08-26 16:42:57 +0000409 Value *Result = ZI->getOperand(0);
Eli Friedman356916e2008-01-29 18:13:51 +0000410 // If there aren't any more uses, zap the instruction to save space.
411 // Note that there can be more uses, for example if this
412 // is the result of an assignment.
413 if (ZI->use_empty())
414 ZI->eraseFromParent();
Chris Lattner9abc84e2007-08-26 16:42:57 +0000415 return Result;
416 }
417 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000418
Chris Lattner9abc84e2007-08-26 16:42:57 +0000419 // Compare against an integer or pointer null.
Owen Andersonc9c88b42009-07-31 20:28:54 +0000420 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattner9abc84e2007-08-26 16:42:57 +0000421 return Builder.CreateICmpNE(Src, Zero, "tobool");
422}
423
Chris Lattner3707b252007-08-26 06:48:56 +0000424/// EmitScalarConversion - Emit a conversion from the specified type to the
425/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000426Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
427 QualType DstType) {
Chris Lattner96196622008-07-26 22:37:01 +0000428 SrcType = CGF.getContext().getCanonicalType(SrcType);
429 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner3707b252007-08-26 06:48:56 +0000430 if (SrcType == DstType) return Src;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000431
Chris Lattnercf289082007-08-26 07:21:11 +0000432 if (DstType->isVoidType()) return 0;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000433
Owen Anderson0032b272009-08-13 21:57:51 +0000434 llvm::LLVMContext &VMContext = CGF.getLLVMContext();
Chris Lattner3707b252007-08-26 06:48:56 +0000435
436 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnered70f0a2007-08-26 16:52:28 +0000437 if (DstType->isBooleanType())
438 return EmitConversionToBool(Src, SrcType);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000439
Chris Lattner3707b252007-08-26 06:48:56 +0000440 const llvm::Type *DstTy = ConvertType(DstType);
441
442 // Ignore conversions like int -> uint.
443 if (Src->getType() == DstTy)
444 return Src;
445
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000446 // Handle pointer conversions next: pointers can only be converted to/from
447 // other pointers and integers. Check for pointer types in terms of LLVM, as
448 // some native types (like Obj-C id) may map to a pointer type.
Daniel Dunbar270cc662008-08-25 09:51:32 +0000449 if (isa<llvm::PointerType>(DstTy)) {
Chris Lattner3707b252007-08-26 06:48:56 +0000450 // The source value may be an integer, or a pointer.
Anders Carlsson191dfe92009-09-12 04:57:16 +0000451 if (isa<llvm::PointerType>(Src->getType()))
Chris Lattner3707b252007-08-26 06:48:56 +0000452 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson191dfe92009-09-12 04:57:16 +0000453
Chris Lattner3707b252007-08-26 06:48:56 +0000454 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Eli Friedman25615422009-03-04 04:02:35 +0000455 // First, convert to the correct width so that we control the kind of
456 // extension.
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000457 const llvm::Type *MiddleTy =
Owen Anderson0032b272009-08-13 21:57:51 +0000458 llvm::IntegerType::get(VMContext, CGF.LLVMPointerWidth);
Eli Friedman25615422009-03-04 04:02:35 +0000459 bool InputSigned = SrcType->isSignedIntegerType();
460 llvm::Value* IntResult =
461 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
462 // Then, cast to pointer.
463 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000464 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000465
Daniel Dunbar270cc662008-08-25 09:51:32 +0000466 if (isa<llvm::PointerType>(Src->getType())) {
Chris Lattner3707b252007-08-26 06:48:56 +0000467 // Must be an ptr to int cast.
468 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson50b5a302007-10-31 23:18:02 +0000469 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000470 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000471
Nate Begeman213541a2008-04-18 23:10:10 +0000472 // A scalar can be splatted to an extended vector of the same element type
Nate Begeman2ef13e52009-08-10 23:49:36 +0000473 if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000474 // Cast the scalar to element type
John McCall183700f2009-09-21 23:43:11 +0000475 QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType();
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000476 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
477
478 // Insert the element in element zero of an undef vector
Owen Anderson03e20502009-07-30 23:11:26 +0000479 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
Owen Anderson0032b272009-08-13 21:57:51 +0000480 llvm::Value *Idx =
481 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0);
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000482 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
483
484 // Splat the element across to all elements
485 llvm::SmallVector<llvm::Constant*, 16> Args;
486 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
487 for (unsigned i = 0; i < NumElements; i++)
Owen Anderson0032b272009-08-13 21:57:51 +0000488 Args.push_back(llvm::ConstantInt::get(
489 llvm::Type::getInt32Ty(VMContext), 0));
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000490
Owen Anderson4a289322009-07-28 21:22:35 +0000491 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000492 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
493 return Yay;
494 }
Nate Begeman4119d1a2007-12-30 02:59:45 +0000495
Chris Lattner3b1ae002008-02-02 04:51:41 +0000496 // Allow bitcast from vector to integer/fp of the same size.
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000497 if (isa<llvm::VectorType>(Src->getType()) ||
Chris Lattner3b1ae002008-02-02 04:51:41 +0000498 isa<llvm::VectorType>(DstTy))
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000499 return Builder.CreateBitCast(Src, DstTy, "conv");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000500
Chris Lattner3707b252007-08-26 06:48:56 +0000501 // Finally, we have the arithmetic types: real int/float.
502 if (isa<llvm::IntegerType>(Src->getType())) {
503 bool InputSigned = SrcType->isSignedIntegerType();
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000504 if (isa<llvm::IntegerType>(DstTy))
505 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
506 else if (InputSigned)
507 return Builder.CreateSIToFP(Src, DstTy, "conv");
508 else
509 return Builder.CreateUIToFP(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000510 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000511
Chris Lattner3707b252007-08-26 06:48:56 +0000512 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
513 if (isa<llvm::IntegerType>(DstTy)) {
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000514 if (DstType->isSignedIntegerType())
515 return Builder.CreateFPToSI(Src, DstTy, "conv");
516 else
517 return Builder.CreateFPToUI(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000518 }
519
520 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000521 if (DstTy->getTypeID() < Src->getType()->getTypeID())
522 return Builder.CreateFPTrunc(Src, DstTy, "conv");
523 else
524 return Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000525}
526
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000527/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
528/// type to the specified destination type, where the destination type is an
529/// LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000530Value *ScalarExprEmitter::
531EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
532 QualType SrcTy, QualType DstTy) {
Chris Lattnered70f0a2007-08-26 16:52:28 +0000533 // Get the source element type.
John McCall183700f2009-09-21 23:43:11 +0000534 SrcTy = SrcTy->getAs<ComplexType>()->getElementType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000535
Chris Lattnered70f0a2007-08-26 16:52:28 +0000536 // Handle conversions to bool first, they are special: comparisons against 0.
537 if (DstTy->isBooleanType()) {
538 // Complex != 0 -> (Real != 0) | (Imag != 0)
539 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
540 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
541 return Builder.CreateOr(Src.first, Src.second, "tobool");
542 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000543
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000544 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
545 // the imaginary part of the complex value is discarded and the value of the
546 // real part is converted according to the conversion rules for the
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000547 // corresponding real type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000548 return EmitScalarConversion(Src.first, SrcTy, DstTy);
549}
550
551
Chris Lattner7f02f722007-08-24 05:35:26 +0000552//===----------------------------------------------------------------------===//
553// Visitor Methods
554//===----------------------------------------------------------------------===//
555
556Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbar488e9932008-08-16 00:56:44 +0000557 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner7f02f722007-08-24 05:35:26 +0000558 if (E->getType()->isVoidType())
559 return 0;
Owen Anderson03e20502009-07-30 23:11:26 +0000560 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Chris Lattner7f02f722007-08-24 05:35:26 +0000561}
562
Eli Friedmand38617c2008-05-14 19:38:39 +0000563Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
564 llvm::SmallVector<llvm::Constant*, 32> indices;
565 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
566 indices.push_back(cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i))));
567 }
568 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
569 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
Owen Anderson4a289322009-07-28 21:22:35 +0000570 Value* SV = llvm::ConstantVector::get(indices.begin(), indices.size());
Eli Friedmand38617c2008-05-14 19:38:39 +0000571 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
572}
Eli Friedman28665272009-11-26 03:22:21 +0000573Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
574 Expr::EvalResult Result;
575 if (E->Evaluate(Result, CGF.getContext()) && Result.Val.isInt()) {
576 if (E->isArrow())
577 CGF.EmitScalarExpr(E->getBase());
578 else
579 EmitLValue(E->getBase());
580 return llvm::ConstantInt::get(VMContext, Result.Val.getInt());
581 }
582 return EmitLoadOfLValue(E);
583}
Eli Friedmand38617c2008-05-14 19:38:39 +0000584
Chris Lattner7f02f722007-08-24 05:35:26 +0000585Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000586 TestAndClearIgnoreResultAssign();
587
Chris Lattner7f02f722007-08-24 05:35:26 +0000588 // Emit subscript expressions in rvalue context's. For most cases, this just
589 // loads the lvalue formed by the subscript expr. However, we have to be
590 // careful, because the base of a vector subscript is occasionally an rvalue,
591 // so we can't get it as an lvalue.
592 if (!E->getBase()->getType()->isVectorType())
593 return EmitLoadOfLValue(E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000594
Chris Lattner7f02f722007-08-24 05:35:26 +0000595 // Handle the vector case. The base must be a vector, the index must be an
596 // integer value.
597 Value *Base = Visit(E->getBase());
598 Value *Idx = Visit(E->getIdx());
Eli Friedmandaa24a22009-03-28 02:45:41 +0000599 bool IdxSigned = E->getIdx()->getType()->isSignedIntegerType();
Owen Anderson0032b272009-08-13 21:57:51 +0000600 Idx = Builder.CreateIntCast(Idx,
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000601 llvm::Type::getInt32Ty(CGF.getLLVMContext()),
Owen Anderson0032b272009-08-13 21:57:51 +0000602 IdxSigned,
Eli Friedman515ff5a2009-03-28 03:27:06 +0000603 "vecidxcast");
Chris Lattner7f02f722007-08-24 05:35:26 +0000604 return Builder.CreateExtractElement(Base, Idx, "vecext");
605}
606
Nate Begeman0533b302009-10-18 20:10:40 +0000607static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
608 unsigned Off, const llvm::Type *I32Ty) {
609 int MV = SVI->getMaskValue(Idx);
610 if (MV == -1)
611 return llvm::UndefValue::get(I32Ty);
612 return llvm::ConstantInt::get(I32Ty, Off+MV);
613}
614
615Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
616 bool Ignore = TestAndClearIgnoreResultAssign();
617 (void)Ignore;
618 assert (Ignore == false && "init list ignored");
619 unsigned NumInitElements = E->getNumInits();
620
621 if (E->hadArrayRangeDesignator())
622 CGF.ErrorUnsupported(E, "GNU array range designator extension");
623
624 const llvm::VectorType *VType =
625 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
626
627 // We have a scalar in braces. Just use the first element.
628 if (!VType)
629 return Visit(E->getInit(0));
630
631 unsigned ResElts = VType->getNumElements();
632 const llvm::Type *I32Ty = llvm::Type::getInt32Ty(CGF.getLLVMContext());
633
634 // Loop over initializers collecting the Value for each, and remembering
635 // whether the source was swizzle (ExtVectorElementExpr). This will allow
636 // us to fold the shuffle for the swizzle into the shuffle for the vector
637 // initializer, since LLVM optimizers generally do not want to touch
638 // shuffles.
639 unsigned CurIdx = 0;
640 bool VIsUndefShuffle = false;
641 llvm::Value *V = llvm::UndefValue::get(VType);
642 for (unsigned i = 0; i != NumInitElements; ++i) {
643 Expr *IE = E->getInit(i);
644 Value *Init = Visit(IE);
645 llvm::SmallVector<llvm::Constant*, 16> Args;
646
647 const llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
648
649 // Handle scalar elements. If the scalar initializer is actually one
650 // element of a different vector of the same width, use shuffle instead of
651 // extract+insert.
652 if (!VVT) {
653 if (isa<ExtVectorElementExpr>(IE)) {
654 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
655
656 if (EI->getVectorOperandType()->getNumElements() == ResElts) {
657 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
658 Value *LHS = 0, *RHS = 0;
659 if (CurIdx == 0) {
660 // insert into undef -> shuffle (src, undef)
661 Args.push_back(C);
662 for (unsigned j = 1; j != ResElts; ++j)
663 Args.push_back(llvm::UndefValue::get(I32Ty));
664
665 LHS = EI->getVectorOperand();
666 RHS = V;
667 VIsUndefShuffle = true;
668 } else if (VIsUndefShuffle) {
669 // insert into undefshuffle && size match -> shuffle (v, src)
670 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
671 for (unsigned j = 0; j != CurIdx; ++j)
672 Args.push_back(getMaskElt(SVV, j, 0, I32Ty));
673 Args.push_back(llvm::ConstantInt::get(I32Ty,
674 ResElts + C->getZExtValue()));
675 for (unsigned j = CurIdx + 1; j != ResElts; ++j)
676 Args.push_back(llvm::UndefValue::get(I32Ty));
677
678 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
679 RHS = EI->getVectorOperand();
680 VIsUndefShuffle = false;
681 }
682 if (!Args.empty()) {
683 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], ResElts);
684 V = Builder.CreateShuffleVector(LHS, RHS, Mask);
685 ++CurIdx;
686 continue;
687 }
688 }
689 }
690 Value *Idx = llvm::ConstantInt::get(I32Ty, CurIdx);
691 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
692 VIsUndefShuffle = false;
693 ++CurIdx;
694 continue;
695 }
696
697 unsigned InitElts = VVT->getNumElements();
698
699 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
700 // input is the same width as the vector being constructed, generate an
701 // optimized shuffle of the swizzle input into the result.
Nate Begemana99f0832009-10-25 02:26:01 +0000702 unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
Nate Begeman0533b302009-10-18 20:10:40 +0000703 if (isa<ExtVectorElementExpr>(IE)) {
704 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
705 Value *SVOp = SVI->getOperand(0);
706 const llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
707
708 if (OpTy->getNumElements() == ResElts) {
Nate Begeman0533b302009-10-18 20:10:40 +0000709 for (unsigned j = 0; j != CurIdx; ++j) {
710 // If the current vector initializer is a shuffle with undef, merge
711 // this shuffle directly into it.
712 if (VIsUndefShuffle) {
713 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
714 I32Ty));
715 } else {
716 Args.push_back(llvm::ConstantInt::get(I32Ty, j));
717 }
718 }
719 for (unsigned j = 0, je = InitElts; j != je; ++j)
720 Args.push_back(getMaskElt(SVI, j, Offset, I32Ty));
721 for (unsigned j = CurIdx + InitElts; j != ResElts; ++j)
722 Args.push_back(llvm::UndefValue::get(I32Ty));
723
724 if (VIsUndefShuffle)
725 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
726
727 Init = SVOp;
728 }
729 }
730
731 // Extend init to result vector length, and then shuffle its contribution
732 // to the vector initializer into V.
733 if (Args.empty()) {
734 for (unsigned j = 0; j != InitElts; ++j)
735 Args.push_back(llvm::ConstantInt::get(I32Ty, j));
736 for (unsigned j = InitElts; j != ResElts; ++j)
737 Args.push_back(llvm::UndefValue::get(I32Ty));
738 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], ResElts);
739 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
Nate Begemana99f0832009-10-25 02:26:01 +0000740 Mask, "vext");
Nate Begeman0533b302009-10-18 20:10:40 +0000741
742 Args.clear();
743 for (unsigned j = 0; j != CurIdx; ++j)
744 Args.push_back(llvm::ConstantInt::get(I32Ty, j));
745 for (unsigned j = 0; j != InitElts; ++j)
Nate Begemana99f0832009-10-25 02:26:01 +0000746 Args.push_back(llvm::ConstantInt::get(I32Ty, j+Offset));
Nate Begeman0533b302009-10-18 20:10:40 +0000747 for (unsigned j = CurIdx + InitElts; j != ResElts; ++j)
748 Args.push_back(llvm::UndefValue::get(I32Ty));
749 }
750
751 // If V is undef, make sure it ends up on the RHS of the shuffle to aid
752 // merging subsequent shuffles into this one.
753 if (CurIdx == 0)
754 std::swap(V, Init);
755 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], ResElts);
756 V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
757 VIsUndefShuffle = isa<llvm::UndefValue>(Init);
758 CurIdx += InitElts;
759 }
760
761 // FIXME: evaluate codegen vs. shuffling against constant null vector.
762 // Emit remaining default initializers.
763 const llvm::Type *EltTy = VType->getElementType();
764
765 // Emit remaining default initializers
766 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
767 Value *Idx = llvm::ConstantInt::get(I32Ty, CurIdx);
768 llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
769 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
770 }
771 return V;
772}
773
Anders Carlssona3697c92009-11-23 17:57:54 +0000774static bool ShouldNullCheckClassCastValue(const CastExpr *CE) {
775 const Expr *E = CE->getSubExpr();
776
777 if (isa<CXXThisExpr>(E)) {
778 // We always assume that 'this' is never null.
779 return false;
780 }
781
782 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
783 // And that lvalue casts are never null.
784 if (ICE->isLvalueCast())
785 return false;
786 }
787
788 return true;
789}
790
Chris Lattner7f02f722007-08-24 05:35:26 +0000791// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
792// have to handle a more broad range of conversions than explicit casts, as they
793// handle things like function to ptr-to-function decay etc.
Eli Friedmand8889622009-11-27 04:41:50 +0000794Value *ScalarExprEmitter::EmitCastExpr(CastExpr *CE) {
795 Expr *E = CE->getSubExpr();
Anders Carlsson592a2bb2009-09-22 22:00:46 +0000796 QualType DestTy = CE->getType();
797 CastExpr::CastKind Kind = CE->getCastKind();
798
Mike Stump7f79f9b2009-05-29 15:46:01 +0000799 if (!DestTy->isVoidType())
800 TestAndClearIgnoreResultAssign();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000801
Eli Friedman8c3e7e72009-11-27 02:07:44 +0000802 // Since almost all cast kinds apply to scalars, this switch doesn't have
803 // a default case, so the compiler will warn on a missing case. The cases
804 // are in the same order as in the CastKind enum.
Anders Carlssone9776242009-08-24 18:26:39 +0000805 switch (Kind) {
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000806 case CastExpr::CK_Unknown:
Eli Friedmand8889622009-11-27 04:41:50 +0000807 // FIXME: All casts should have a known kind!
Eli Friedmanad35a832009-11-16 21:33:53 +0000808 //assert(0 && "Unknown cast kind!");
Anders Carlssone9776242009-08-24 18:26:39 +0000809 break;
Eli Friedmanad35a832009-11-16 21:33:53 +0000810
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +0000811 case CastExpr::CK_AnyPointerToObjCPointerCast:
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000812 case CastExpr::CK_BitCast: {
813 Value *Src = Visit(const_cast<Expr*>(E));
814 return Builder.CreateBitCast(Src, ConvertType(DestTy));
815 }
Eli Friedmanad35a832009-11-16 21:33:53 +0000816 case CastExpr::CK_NoOp:
817 return Visit(const_cast<Expr*>(E));
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000818
Anders Carlssona3697c92009-11-23 17:57:54 +0000819 case CastExpr::CK_BaseToDerived: {
820 const CXXRecordDecl *BaseClassDecl =
821 E->getType()->getCXXRecordDeclForPointerType();
822 const CXXRecordDecl *DerivedClassDecl =
823 DestTy->getCXXRecordDeclForPointerType();
824
825 Value *Src = Visit(const_cast<Expr*>(E));
826
827 bool NullCheckValue = ShouldNullCheckClassCastValue(CE);
828 return CGF.GetAddressOfDerivedClass(Src, BaseClassDecl, DerivedClassDecl,
829 NullCheckValue);
830 }
Anders Carlsson191dfe92009-09-12 04:57:16 +0000831 case CastExpr::CK_DerivedToBase: {
832 const RecordType *DerivedClassTy =
833 E->getType()->getAs<PointerType>()->getPointeeType()->getAs<RecordType>();
834 CXXRecordDecl *DerivedClassDecl =
835 cast<CXXRecordDecl>(DerivedClassTy->getDecl());
836
837 const RecordType *BaseClassTy =
838 DestTy->getAs<PointerType>()->getPointeeType()->getAs<RecordType>();
839 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseClassTy->getDecl());
840
841 Value *Src = Visit(const_cast<Expr*>(E));
Anders Carlsson32baf622009-09-12 06:04:24 +0000842
Anders Carlssona3697c92009-11-23 17:57:54 +0000843 bool NullCheckValue = ShouldNullCheckClassCastValue(CE);
844 return CGF.GetAddressOfBaseClass(Src, DerivedClassDecl, BaseClassDecl,
845 NullCheckValue);
Anders Carlsson191dfe92009-09-12 04:57:16 +0000846 }
Eli Friedman8c3e7e72009-11-27 02:07:44 +0000847 case CastExpr::CK_Dynamic: {
848 Value *V = Visit(const_cast<Expr*>(E));
849 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
850 return CGF.EmitDynamicCast(V, DCE);
851 }
Eli Friedmand8889622009-11-27 04:41:50 +0000852 case CastExpr::CK_ToUnion:
Eli Friedmanad35a832009-11-16 21:33:53 +0000853 assert(0 && "Should be unreachable!");
854 break;
Eli Friedmand8889622009-11-27 04:41:50 +0000855
Eli Friedmanad35a832009-11-16 21:33:53 +0000856 case CastExpr::CK_ArrayToPointerDecay: {
857 assert(E->getType()->isArrayType() &&
858 "Array to pointer decay must have array source type!");
859
860 Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
861
862 // Note that VLA pointers are always decayed, so we don't need to do
863 // anything here.
864 if (!E->getType()->isVariableArrayType()) {
865 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
866 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
867 ->getElementType()) &&
868 "Expected pointer to array");
869 V = Builder.CreateStructGEP(V, 0, "arraydecay");
870 }
871
872 return V;
873 }
874 case CastExpr::CK_FunctionToPointerDecay:
875 return EmitLValue(E).getAddress();
876
877 case CastExpr::CK_NullToMemberPointer:
878 return CGF.CGM.EmitNullConstant(DestTy);
Anders Carlsson191dfe92009-09-12 04:57:16 +0000879
Eli Friedman8c3e7e72009-11-27 02:07:44 +0000880 case CastExpr::CK_BaseToDerivedMemberPointer:
Eli Friedmand8889622009-11-27 04:41:50 +0000881 case CastExpr::CK_DerivedToBaseMemberPointer: {
882 Value *Src = Visit(E);
883
884 // See if we need to adjust the pointer.
885 const CXXRecordDecl *BaseDecl =
886 cast<CXXRecordDecl>(E->getType()->getAs<MemberPointerType>()->
887 getClass()->getAs<RecordType>()->getDecl());
888 const CXXRecordDecl *DerivedDecl =
889 cast<CXXRecordDecl>(CE->getType()->getAs<MemberPointerType>()->
890 getClass()->getAs<RecordType>()->getDecl());
891 if (CE->getCastKind() == CastExpr::CK_DerivedToBaseMemberPointer)
892 std::swap(DerivedDecl, BaseDecl);
893
894 llvm::Constant *Adj = CGF.CGM.GetCXXBaseClassOffset(DerivedDecl, BaseDecl);
895 if (Adj) {
896 if (CE->getCastKind() == CastExpr::CK_DerivedToBaseMemberPointer)
897 Src = Builder.CreateSub(Src, Adj, "adj");
898 else
899 Src = Builder.CreateAdd(Src, Adj, "adj");
900 }
901 return Src;
902 }
903
Eli Friedman8c3e7e72009-11-27 02:07:44 +0000904 case CastExpr::CK_UserDefinedConversion:
905 case CastExpr::CK_ConstructorConversion:
Eli Friedmand8889622009-11-27 04:41:50 +0000906 assert(0 && "Should be unreachable!");
Eli Friedman8c3e7e72009-11-27 02:07:44 +0000907 break;
908
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000909 case CastExpr::CK_IntegralToPointer: {
910 Value *Src = Visit(const_cast<Expr*>(E));
Anders Carlsson82debc72009-10-18 18:12:03 +0000911
912 // First, convert to the correct width so that we control the kind of
913 // extension.
914 const llvm::Type *MiddleTy =
915 llvm::IntegerType::get(VMContext, CGF.LLVMPointerWidth);
916 bool InputSigned = E->getType()->isSignedIntegerType();
917 llvm::Value* IntResult =
918 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
919
920 return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy));
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000921 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000922 case CastExpr::CK_PointerToIntegral: {
923 Value *Src = Visit(const_cast<Expr*>(E));
924 return Builder.CreatePtrToInt(Src, ConvertType(DestTy));
925 }
Eli Friedmanad35a832009-11-16 21:33:53 +0000926 case CastExpr::CK_ToVoid: {
927 CGF.EmitAnyExpr(E, 0, false, true);
928 return 0;
929 }
Eli Friedmanad35a832009-11-16 21:33:53 +0000930 case CastExpr::CK_VectorSplat: {
931 const llvm::Type *DstTy = ConvertType(DestTy);
932 Value *Elt = Visit(const_cast<Expr*>(E));
933
934 // Insert the element in element zero of an undef vector
935 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
936 llvm::Value *Idx =
937 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0);
938 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
939
940 // Splat the element across to all elements
941 llvm::SmallVector<llvm::Constant*, 16> Args;
942 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
943 for (unsigned i = 0; i < NumElements; i++)
944 Args.push_back(llvm::ConstantInt::get(
945 llvm::Type::getInt32Ty(VMContext), 0));
946
947 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
948 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
949 return Yay;
950 }
Eli Friedman8c3e7e72009-11-27 02:07:44 +0000951 case CastExpr::CK_IntegralCast:
952 case CastExpr::CK_IntegralToFloating:
953 case CastExpr::CK_FloatingToIntegral:
954 case CastExpr::CK_FloatingCast:
Eli Friedmand8889622009-11-27 04:41:50 +0000955 return EmitScalarConversion(Visit(E), E->getType(), DestTy);
Eli Friedmanad35a832009-11-16 21:33:53 +0000956
Eli Friedman3a173702009-12-11 09:26:29 +0000957 case CastExpr::CK_MemberPointerToBoolean:
958 return CGF.EvaluateExprAsBool(E);
Anders Carlssone9776242009-08-24 18:26:39 +0000959 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000960
Chris Lattner58a2e942007-08-26 07:26:12 +0000961 // Handle cases where the source is an non-complex type.
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000962
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000963 if (!CGF.hasAggregateLLVMType(E->getType())) {
Chris Lattner3707b252007-08-26 06:48:56 +0000964 Value *Src = Visit(const_cast<Expr*>(E));
965
Chris Lattner3707b252007-08-26 06:48:56 +0000966 // Use EmitScalarConversion to perform the conversion.
967 return EmitScalarConversion(Src, E->getType(), DestTy);
968 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000969
Chris Lattner9b2dc282008-04-04 16:54:41 +0000970 if (E->getType()->isAnyComplexType()) {
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000971 // Handle cases where the source is a complex type.
Mike Stump7f79f9b2009-05-29 15:46:01 +0000972 bool IgnoreImag = true;
973 bool IgnoreImagAssign = true;
974 bool IgnoreReal = IgnoreResultAssign;
975 bool IgnoreRealAssign = IgnoreResultAssign;
976 if (DestTy->isBooleanType())
977 IgnoreImagAssign = IgnoreImag = false;
978 else if (DestTy->isVoidType()) {
979 IgnoreReal = IgnoreImag = false;
980 IgnoreRealAssign = IgnoreImagAssign = true;
981 }
982 CodeGenFunction::ComplexPairTy V
983 = CGF.EmitComplexExpr(E, IgnoreReal, IgnoreImag, IgnoreRealAssign,
984 IgnoreImagAssign);
985 return EmitComplexToScalarConversion(V, E->getType(), DestTy);
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000986 }
Chris Lattner10b00cf2007-08-26 07:16:41 +0000987
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000988 // Okay, this is a cast from an aggregate. It must be a cast to void. Just
989 // evaluate the result and return.
Mike Stump7f79f9b2009-05-29 15:46:01 +0000990 CGF.EmitAggExpr(E, 0, false, true);
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000991 return 0;
Chris Lattner7f02f722007-08-24 05:35:26 +0000992}
993
Chris Lattner33793202007-08-31 22:09:40 +0000994Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
Chris Lattner91d723d2008-07-26 20:23:23 +0000995 return CGF.EmitCompoundStmt(*E->getSubStmt(),
996 !E->getType()->isVoidType()).getScalarVal();
Chris Lattner33793202007-08-31 22:09:40 +0000997}
998
Mike Stumpa99038c2009-02-28 09:07:16 +0000999Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
Fariborz Jahanianf7bcc7e2009-10-10 20:07:56 +00001000 llvm::Value *V = CGF.GetAddrOfBlockDecl(E);
1001 if (E->getType().isObjCGCWeak())
1002 return CGF.CGM.getObjCRuntime().EmitObjCWeakRead(CGF, V);
Daniel Dunbar2da84ff2009-11-29 21:23:36 +00001003 return Builder.CreateLoad(V, "tmp");
Mike Stump4e7a1f72009-02-21 20:00:35 +00001004}
Chris Lattner33793202007-08-31 22:09:40 +00001005
Chris Lattner7f02f722007-08-24 05:35:26 +00001006//===----------------------------------------------------------------------===//
1007// Unary Operators
1008//===----------------------------------------------------------------------===//
1009
1010Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattnerdfce2a52007-08-24 16:24:49 +00001011 bool isInc, bool isPre) {
Chris Lattner7f02f722007-08-24 05:35:26 +00001012 LValue LV = EmitLValue(E->getSubExpr());
Eli Friedmanf52bbeb2009-03-23 03:00:06 +00001013 QualType ValTy = E->getSubExpr()->getType();
1014 Value *InVal = CGF.EmitLoadOfLValue(LV, ValTy).getScalarVal();
Owen Anderson0032b272009-08-13 21:57:51 +00001015
1016 llvm::LLVMContext &VMContext = CGF.getLLVMContext();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001017
Chris Lattner7f02f722007-08-24 05:35:26 +00001018 int AmountVal = isInc ? 1 : -1;
Eli Friedmandaa24a22009-03-28 02:45:41 +00001019
1020 if (ValTy->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001021 ValTy->getAs<PointerType>()->isVariableArrayType()) {
Eli Friedmandaa24a22009-03-28 02:45:41 +00001022 // The amount of the addition/subtraction needs to account for the VLA size
1023 CGF.ErrorUnsupported(E, "VLA pointer inc/dec");
1024 }
1025
Chris Lattner7f02f722007-08-24 05:35:26 +00001026 Value *NextVal;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001027 if (const llvm::PointerType *PT =
Chris Lattner8cc9d082009-03-18 04:25:13 +00001028 dyn_cast<llvm::PointerType>(InVal->getType())) {
Owen Andersona1cf15f2009-07-14 23:10:40 +00001029 llvm::Constant *Inc =
Owen Anderson0032b272009-08-13 21:57:51 +00001030 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), AmountVal);
Chris Lattner8cc9d082009-03-18 04:25:13 +00001031 if (!isa<llvm::FunctionType>(PT->getElementType())) {
Fariborz Jahanian62a11a72009-07-16 22:04:59 +00001032 QualType PTEE = ValTy->getPointeeType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001033 if (const ObjCInterfaceType *OIT =
Fariborz Jahanian62a11a72009-07-16 22:04:59 +00001034 dyn_cast<ObjCInterfaceType>(PTEE)) {
1035 // Handle interface types, which are not represented with a concrete type.
1036 int size = CGF.getContext().getTypeSize(OIT) / 8;
1037 if (!isInc)
1038 size = -size;
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001039 Inc = llvm::ConstantInt::get(Inc->getType(), size);
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00001040 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
Fariborz Jahanian62a11a72009-07-16 22:04:59 +00001041 InVal = Builder.CreateBitCast(InVal, i8Ty);
1042 NextVal = Builder.CreateGEP(InVal, Inc, "add.ptr");
1043 llvm::Value *lhs = LV.getAddress();
Owen Anderson96e0fc72009-07-29 22:16:19 +00001044 lhs = Builder.CreateBitCast(lhs, llvm::PointerType::getUnqual(i8Ty));
John McCall0953e762009-09-24 19:53:00 +00001045 LV = LValue::MakeAddr(lhs, CGF.MakeQualifiers(ValTy));
Mike Stumpb3589f42009-07-30 22:28:39 +00001046 } else
Dan Gohman664f8932009-08-12 00:33:55 +00001047 NextVal = Builder.CreateInBoundsGEP(InVal, Inc, "ptrincdec");
Chris Lattner8cc9d082009-03-18 04:25:13 +00001048 } else {
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00001049 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
Chris Lattner8cc9d082009-03-18 04:25:13 +00001050 NextVal = Builder.CreateBitCast(InVal, i8Ty, "tmp");
1051 NextVal = Builder.CreateGEP(NextVal, Inc, "ptrincdec");
1052 NextVal = Builder.CreateBitCast(NextVal, InVal->getType());
1053 }
Owen Anderson0032b272009-08-13 21:57:51 +00001054 } else if (InVal->getType() == llvm::Type::getInt1Ty(VMContext) && isInc) {
Chris Lattnerdb3bd4b2009-02-11 07:40:06 +00001055 // Bool++ is an interesting case, due to promotion rules, we get:
1056 // Bool++ -> Bool = Bool+1 -> Bool = (int)Bool+1 ->
1057 // Bool = ((int)Bool+1) != 0
1058 // An interesting aspect of this is that increment is always true.
1059 // Decrement does not have this property.
Owen Anderson3b144ba2009-07-31 17:39:36 +00001060 NextVal = llvm::ConstantInt::getTrue(VMContext);
Chris Lattner87415d22009-06-17 06:36:24 +00001061 } else if (isa<llvm::IntegerType>(InVal->getType())) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001062 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
Dan Gohmanbf933a02009-08-12 01:16:29 +00001063
1064 // Signed integer overflow is undefined behavior.
1065 if (ValTy->isSignedIntegerType())
1066 NextVal = Builder.CreateNSWAdd(InVal, NextVal, isInc ? "inc" : "dec");
1067 else
1068 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
Chris Lattnere936cc82007-08-26 05:10:16 +00001069 } else {
1070 // Add the inc/dec to the real part.
Benjamin Kramerffbb15e2009-10-05 13:47:21 +00001071 if (InVal->getType()->isFloatTy())
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001072 NextVal =
1073 llvm::ConstantFP::get(VMContext,
Owen Andersonbc0a2222009-07-27 21:00:51 +00001074 llvm::APFloat(static_cast<float>(AmountVal)));
Benjamin Kramerffbb15e2009-10-05 13:47:21 +00001075 else if (InVal->getType()->isDoubleTy())
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001076 NextVal =
Owen Andersonbc0a2222009-07-27 21:00:51 +00001077 llvm::ConstantFP::get(VMContext,
1078 llvm::APFloat(static_cast<double>(AmountVal)));
Chris Lattner25ddea72008-04-20 00:50:39 +00001079 else {
1080 llvm::APFloat F(static_cast<float>(AmountVal));
Dale Johannesenee5a7002008-10-09 23:02:32 +00001081 bool ignored;
1082 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
1083 &ignored);
Owen Andersonbc0a2222009-07-27 21:00:51 +00001084 NextVal = llvm::ConstantFP::get(VMContext, F);
Chris Lattnerca2617c2007-09-13 06:19:18 +00001085 }
Chris Lattner87415d22009-06-17 06:36:24 +00001086 NextVal = Builder.CreateFAdd(InVal, NextVal, isInc ? "inc" : "dec");
Chris Lattnere936cc82007-08-26 05:10:16 +00001087 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001088
Chris Lattner7f02f722007-08-24 05:35:26 +00001089 // Store the updated result through the lvalue.
Eli Friedmanf52bbeb2009-03-23 03:00:06 +00001090 if (LV.isBitfield())
1091 CGF.EmitStoreThroughBitfieldLValue(RValue::get(NextVal), LV, ValTy,
1092 &NextVal);
1093 else
1094 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV, ValTy);
Chris Lattner7f02f722007-08-24 05:35:26 +00001095
1096 // If this is a postinc, return the value read from memory, otherwise use the
1097 // updated value.
1098 return isPre ? NextVal : InVal;
1099}
1100
1101
1102Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001103 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +00001104 Value *Op = Visit(E->getSubExpr());
Chris Lattner87415d22009-06-17 06:36:24 +00001105 if (Op->getType()->isFPOrFPVector())
1106 return Builder.CreateFNeg(Op, "neg");
Chris Lattner7f02f722007-08-24 05:35:26 +00001107 return Builder.CreateNeg(Op, "neg");
1108}
1109
1110Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001111 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +00001112 Value *Op = Visit(E->getSubExpr());
1113 return Builder.CreateNot(Op, "neg");
1114}
1115
1116Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
1117 // Compare operand to zero.
1118 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001119
Chris Lattner7f02f722007-08-24 05:35:26 +00001120 // Invert value.
1121 // TODO: Could dynamically modify easy computations here. For example, if
1122 // the operand is an icmp ne, turn into icmp eq.
1123 BoolVal = Builder.CreateNot(BoolVal, "lnot");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001124
Anders Carlsson9f84d882009-05-19 18:44:53 +00001125 // ZExt result to the expr type.
1126 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00001127}
1128
Sebastian Redl05189992008-11-11 17:56:53 +00001129/// VisitSizeOfAlignOfExpr - Return the size or alignment of the type of
1130/// argument of the sizeof expression as an integer.
1131Value *
1132ScalarExprEmitter::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
Sebastian Redl05189992008-11-11 17:56:53 +00001133 QualType TypeToSize = E->getTypeOfArgument();
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001134 if (E->isSizeOf()) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001135 if (const VariableArrayType *VAT =
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001136 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
1137 if (E->isArgumentType()) {
1138 // sizeof(type) - make sure to emit the VLA size.
1139 CGF.EmitVLASize(TypeToSize);
Eli Friedman8f426fa2009-04-20 03:21:44 +00001140 } else {
1141 // C99 6.5.3.4p2: If the argument is an expression of type
1142 // VLA, it is evaluated.
1143 CGF.EmitAnyExpr(E->getArgumentExpr());
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001144 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001145
Anders Carlsson96f21472009-02-05 19:43:10 +00001146 return CGF.GetVLASize(VAT);
Anders Carlssonb50525b2008-12-21 03:33:21 +00001147 }
Anders Carlsson5d463152008-12-12 07:38:43 +00001148 }
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001149
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001150 // If this isn't sizeof(vla), the result must be constant; use the constant
1151 // folding logic so we don't have to duplicate it here.
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001152 Expr::EvalResult Result;
1153 E->Evaluate(Result, CGF.getContext());
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001154 return llvm::ConstantInt::get(VMContext, Result.Val.getInt());
Chris Lattner7f02f722007-08-24 05:35:26 +00001155}
1156
Chris Lattner46f93d02007-08-24 21:20:17 +00001157Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
1158 Expr *Op = E->getSubExpr();
Chris Lattner9b2dc282008-04-04 16:54:41 +00001159 if (Op->getType()->isAnyComplexType())
Mike Stump7f79f9b2009-05-29 15:46:01 +00001160 return CGF.EmitComplexExpr(Op, false, true, false, true).first;
Chris Lattner46f93d02007-08-24 21:20:17 +00001161 return Visit(Op);
1162}
1163Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
1164 Expr *Op = E->getSubExpr();
Chris Lattner9b2dc282008-04-04 16:54:41 +00001165 if (Op->getType()->isAnyComplexType())
Mike Stump7f79f9b2009-05-29 15:46:01 +00001166 return CGF.EmitComplexExpr(Op, true, false, true, false).second;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001167
Mike Stump7f79f9b2009-05-29 15:46:01 +00001168 // __imag on a scalar returns zero. Emit the subexpr to ensure side
1169 // effects are evaluated, but not the actual value.
1170 if (E->isLvalue(CGF.getContext()) == Expr::LV_Valid)
1171 CGF.EmitLValue(Op);
1172 else
1173 CGF.EmitScalarExpr(Op, true);
Owen Andersonc9c88b42009-07-31 20:28:54 +00001174 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner46f93d02007-08-24 21:20:17 +00001175}
1176
Mike Stump1eb44332009-09-09 15:08:12 +00001177Value *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E) {
Eli Friedman35183ac2009-02-27 06:44:11 +00001178 Value* ResultAsPtr = EmitLValue(E->getSubExpr()).getAddress();
Eli Friedman769e4112009-01-24 22:38:55 +00001179 const llvm::Type* ResultType = ConvertType(E->getType());
Eli Friedman35183ac2009-02-27 06:44:11 +00001180 return Builder.CreatePtrToInt(ResultAsPtr, ResultType, "offsetof");
Anders Carlsson5a1deb82008-01-29 15:56:48 +00001181}
Chris Lattner46f93d02007-08-24 21:20:17 +00001182
Chris Lattner7f02f722007-08-24 05:35:26 +00001183//===----------------------------------------------------------------------===//
1184// Binary Operators
1185//===----------------------------------------------------------------------===//
1186
1187BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001188 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +00001189 BinOpInfo Result;
1190 Result.LHS = Visit(E->getLHS());
1191 Result.RHS = Visit(E->getRHS());
Chris Lattner1f1ded92007-08-24 21:00:35 +00001192 Result.Ty = E->getType();
Chris Lattner7f02f722007-08-24 05:35:26 +00001193 Result.E = E;
1194 return Result;
1195}
1196
Chris Lattner3ccf7742007-08-26 21:41:21 +00001197Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner1f1ded92007-08-24 21:00:35 +00001198 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001199 bool Ignore = TestAndClearIgnoreResultAssign();
Chris Lattner1f1ded92007-08-24 21:00:35 +00001200 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
1201
1202 BinOpInfo OpInfo;
1203
Eli Friedmanab3a8522009-03-28 01:22:36 +00001204 if (E->getComputationResultType()->isAnyComplexType()) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001205 // This needs to go through the complex expression emitter, but it's a tad
1206 // complicated to do that... I'm leaving it out for now. (Note that we do
1207 // actually need the imaginary part of the RHS for multiplication and
1208 // division.)
Eli Friedmanab3a8522009-03-28 01:22:36 +00001209 CGF.ErrorUnsupported(E, "complex compound assignment");
Owen Anderson03e20502009-07-30 23:11:26 +00001210 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Eli Friedmanab3a8522009-03-28 01:22:36 +00001211 }
1212
Mike Stumpcc0442f2009-05-22 19:07:20 +00001213 // Emit the RHS first. __block variables need to have the rhs evaluated
1214 // first, plus this should improve codegen a little.
1215 OpInfo.RHS = Visit(E->getRHS());
1216 OpInfo.Ty = E->getComputationResultType();
1217 OpInfo.E = E;
Eli Friedmanab3a8522009-03-28 01:22:36 +00001218 // Load/convert the LHS.
Chris Lattner1f1ded92007-08-24 21:00:35 +00001219 LValue LHSLV = EmitLValue(E->getLHS());
1220 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00001221 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
1222 E->getComputationLHSType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001223
Chris Lattner1f1ded92007-08-24 21:00:35 +00001224 // Expand the binary operator.
1225 Value *Result = (this->*Func)(OpInfo);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001226
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001227 // Convert the result back to the LHS type.
Eli Friedmanab3a8522009-03-28 01:22:36 +00001228 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
1229
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001230 // Store the result value into the LHS lvalue. Bit-fields are handled
1231 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
1232 // 'An assignment expression has the value of the left operand after the
1233 // assignment...'.
Mike Stump7f79f9b2009-05-29 15:46:01 +00001234 if (LHSLV.isBitfield()) {
1235 if (!LHSLV.isVolatileQualified()) {
1236 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy,
1237 &Result);
1238 return Result;
1239 } else
1240 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy);
1241 } else
Daniel Dunbared3849b2008-11-19 09:36:46 +00001242 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy);
Mike Stump7f79f9b2009-05-29 15:46:01 +00001243 if (Ignore)
1244 return 0;
1245 return EmitLoadOfLValue(LHSLV, E->getType());
Chris Lattner1f1ded92007-08-24 21:00:35 +00001246}
1247
1248
Chris Lattner7f02f722007-08-24 05:35:26 +00001249Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Nate Begemanb3ab8dc2007-12-30 01:28:16 +00001250 if (Ops.LHS->getType()->isFPOrFPVector())
Chris Lattner7f02f722007-08-24 05:35:26 +00001251 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner1f1ded92007-08-24 21:00:35 +00001252 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner7f02f722007-08-24 05:35:26 +00001253 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
1254 else
1255 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
1256}
1257
1258Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
1259 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner1f1ded92007-08-24 21:00:35 +00001260 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner7f02f722007-08-24 05:35:26 +00001261 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
1262 else
1263 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
1264}
1265
Mike Stump2add4732009-04-01 20:28:16 +00001266Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
1267 unsigned IID;
1268 unsigned OpID = 0;
Mike Stump5d8b2cf2009-04-02 01:03:55 +00001269
Mike Stump035cf892009-04-02 18:15:54 +00001270 switch (Ops.E->getOpcode()) {
1271 case BinaryOperator::Add:
1272 case BinaryOperator::AddAssign:
1273 OpID = 1;
1274 IID = llvm::Intrinsic::sadd_with_overflow;
1275 break;
1276 case BinaryOperator::Sub:
1277 case BinaryOperator::SubAssign:
1278 OpID = 2;
1279 IID = llvm::Intrinsic::ssub_with_overflow;
1280 break;
1281 case BinaryOperator::Mul:
1282 case BinaryOperator::MulAssign:
1283 OpID = 3;
1284 IID = llvm::Intrinsic::smul_with_overflow;
1285 break;
1286 default:
1287 assert(false && "Unsupported operation for overflow detection");
Daniel Dunbarab4eff62009-04-08 16:23:09 +00001288 IID = 0;
Mike Stump2add4732009-04-01 20:28:16 +00001289 }
Mike Stump035cf892009-04-02 18:15:54 +00001290 OpID <<= 1;
1291 OpID |= 1;
1292
Mike Stump2add4732009-04-01 20:28:16 +00001293 const llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
1294
1295 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, &opTy, 1);
1296
1297 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
1298 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
1299 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
1300
1301 // Branch in case of overflow.
1302 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
1303 llvm::BasicBlock *overflowBB =
1304 CGF.createBasicBlock("overflow", CGF.CurFn);
1305 llvm::BasicBlock *continueBB =
1306 CGF.createBasicBlock("overflow.continue", CGF.CurFn);
1307
1308 Builder.CreateCondBr(overflow, overflowBB, continueBB);
1309
1310 // Handle overflow
1311
1312 Builder.SetInsertPoint(overflowBB);
1313
1314 // Handler is:
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001315 // long long *__overflow_handler)(long long a, long long b, char op,
Mike Stump2add4732009-04-01 20:28:16 +00001316 // char width)
1317 std::vector<const llvm::Type*> handerArgTypes;
Owen Anderson0032b272009-08-13 21:57:51 +00001318 handerArgTypes.push_back(llvm::Type::getInt64Ty(VMContext));
1319 handerArgTypes.push_back(llvm::Type::getInt64Ty(VMContext));
1320 handerArgTypes.push_back(llvm::Type::getInt8Ty(VMContext));
1321 handerArgTypes.push_back(llvm::Type::getInt8Ty(VMContext));
1322 llvm::FunctionType *handlerTy = llvm::FunctionType::get(
1323 llvm::Type::getInt64Ty(VMContext), handerArgTypes, false);
Mike Stump2add4732009-04-01 20:28:16 +00001324 llvm::Value *handlerFunction =
1325 CGF.CGM.getModule().getOrInsertGlobal("__overflow_handler",
Owen Anderson96e0fc72009-07-29 22:16:19 +00001326 llvm::PointerType::getUnqual(handlerTy));
Mike Stump2add4732009-04-01 20:28:16 +00001327 handlerFunction = Builder.CreateLoad(handlerFunction);
1328
1329 llvm::Value *handlerResult = Builder.CreateCall4(handlerFunction,
Owen Anderson0032b272009-08-13 21:57:51 +00001330 Builder.CreateSExt(Ops.LHS, llvm::Type::getInt64Ty(VMContext)),
1331 Builder.CreateSExt(Ops.RHS, llvm::Type::getInt64Ty(VMContext)),
1332 llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext), OpID),
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001333 llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext),
Mike Stump2add4732009-04-01 20:28:16 +00001334 cast<llvm::IntegerType>(opTy)->getBitWidth()));
1335
1336 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
1337
1338 Builder.CreateBr(continueBB);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001339
Mike Stump2add4732009-04-01 20:28:16 +00001340 // Set up the continuation
1341 Builder.SetInsertPoint(continueBB);
1342 // Get the correct result
1343 llvm::PHINode *phi = Builder.CreatePHI(opTy);
1344 phi->reserveOperandSpace(2);
1345 phi->addIncoming(result, initialBB);
1346 phi->addIncoming(handlerResult, overflowBB);
1347
1348 return phi;
1349}
Chris Lattner7f02f722007-08-24 05:35:26 +00001350
1351Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001352 if (!Ops.Ty->isAnyPointerType()) {
Chris Lattner87415d22009-06-17 06:36:24 +00001353 if (CGF.getContext().getLangOptions().OverflowChecking &&
1354 Ops.Ty->isSignedIntegerType())
Mike Stump2add4732009-04-01 20:28:16 +00001355 return EmitOverflowCheckedBinOp(Ops);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001356
Chris Lattner87415d22009-06-17 06:36:24 +00001357 if (Ops.LHS->getType()->isFPOrFPVector())
1358 return Builder.CreateFAdd(Ops.LHS, Ops.RHS, "add");
Dan Gohmanbf933a02009-08-12 01:16:29 +00001359
1360 // Signed integer overflow is undefined behavior.
1361 if (Ops.Ty->isSignedIntegerType())
1362 return Builder.CreateNSWAdd(Ops.LHS, Ops.RHS, "add");
1363
Chris Lattner7f02f722007-08-24 05:35:26 +00001364 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Mike Stump2add4732009-04-01 20:28:16 +00001365 }
Eli Friedmandaa24a22009-03-28 02:45:41 +00001366
Steve Naroff14108da2009-07-10 23:34:53 +00001367 if (Ops.Ty->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001368 Ops.Ty->getAs<PointerType>()->isVariableArrayType()) {
Eli Friedmandaa24a22009-03-28 02:45:41 +00001369 // The amount of the addition needs to account for the VLA size
1370 CGF.ErrorUnsupported(Ops.E, "VLA pointer addition");
1371 }
Chris Lattner8f925282008-01-03 06:36:51 +00001372 Value *Ptr, *Idx;
1373 Expr *IdxExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00001374 const PointerType *PT = Ops.E->getLHS()->getType()->getAs<PointerType>();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001375 const ObjCObjectPointerType *OPT =
John McCall183700f2009-09-21 23:43:11 +00001376 Ops.E->getLHS()->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00001377 if (PT || OPT) {
Chris Lattner8f925282008-01-03 06:36:51 +00001378 Ptr = Ops.LHS;
1379 Idx = Ops.RHS;
1380 IdxExp = Ops.E->getRHS();
Steve Naroff14108da2009-07-10 23:34:53 +00001381 } else { // int + pointer
Ted Kremenek6217b802009-07-29 21:53:49 +00001382 PT = Ops.E->getRHS()->getType()->getAs<PointerType>();
John McCall183700f2009-09-21 23:43:11 +00001383 OPT = Ops.E->getRHS()->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00001384 assert((PT || OPT) && "Invalid add expr");
Chris Lattner8f925282008-01-03 06:36:51 +00001385 Ptr = Ops.RHS;
1386 Idx = Ops.LHS;
1387 IdxExp = Ops.E->getLHS();
1388 }
1389
1390 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
Sanjiv Gupta7cabee52009-04-24 02:40:57 +00001391 if (Width < CGF.LLVMPointerWidth) {
Chris Lattner8f925282008-01-03 06:36:51 +00001392 // Zero or sign extend the pointer value based on whether the index is
1393 // signed or not.
Owen Anderson0032b272009-08-13 21:57:51 +00001394 const llvm::Type *IdxType =
1395 llvm::IntegerType::get(VMContext, CGF.LLVMPointerWidth);
Chris Lattner96196622008-07-26 22:37:01 +00001396 if (IdxExp->getType()->isSignedIntegerType())
Chris Lattner8f925282008-01-03 06:36:51 +00001397 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1398 else
1399 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1400 }
Steve Naroff14108da2009-07-10 23:34:53 +00001401 const QualType ElementType = PT ? PT->getPointeeType() : OPT->getPointeeType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001402 // Handle interface types, which are not represented with a concrete type.
Daniel Dunbar2a866252009-04-25 05:08:32 +00001403 if (const ObjCInterfaceType *OIT = dyn_cast<ObjCInterfaceType>(ElementType)) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001404 llvm::Value *InterfaceSize =
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001405 llvm::ConstantInt::get(Idx->getType(),
Daniel Dunbar2a866252009-04-25 05:08:32 +00001406 CGF.getContext().getTypeSize(OIT) / 8);
1407 Idx = Builder.CreateMul(Idx, InterfaceSize);
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00001408 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
Daniel Dunbar2a866252009-04-25 05:08:32 +00001409 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
1410 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
1411 return Builder.CreateBitCast(Res, Ptr->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001412 }
Daniel Dunbar2a866252009-04-25 05:08:32 +00001413
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001414 // Explicitly handle GNU void* and function pointer arithmetic extensions. The
1415 // GNU void* casts amount to no-ops since our void* type is i8*, but this is
1416 // future proof.
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001417 if (ElementType->isVoidType() || ElementType->isFunctionType()) {
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00001418 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001419 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
Daniel Dunbar2a866252009-04-25 05:08:32 +00001420 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001421 return Builder.CreateBitCast(Res, Ptr->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001422 }
1423
Dan Gohman664f8932009-08-12 00:33:55 +00001424 return Builder.CreateInBoundsGEP(Ptr, Idx, "add.ptr");
Chris Lattner7f02f722007-08-24 05:35:26 +00001425}
1426
1427Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
Mike Stump2add4732009-04-01 20:28:16 +00001428 if (!isa<llvm::PointerType>(Ops.LHS->getType())) {
Mike Stump035cf892009-04-02 18:15:54 +00001429 if (CGF.getContext().getLangOptions().OverflowChecking
1430 && Ops.Ty->isSignedIntegerType())
Mike Stump2add4732009-04-01 20:28:16 +00001431 return EmitOverflowCheckedBinOp(Ops);
Chris Lattner87415d22009-06-17 06:36:24 +00001432
1433 if (Ops.LHS->getType()->isFPOrFPVector())
1434 return Builder.CreateFSub(Ops.LHS, Ops.RHS, "sub");
Chris Lattner7f02f722007-08-24 05:35:26 +00001435 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
Mike Stump2add4732009-04-01 20:28:16 +00001436 }
Chris Lattner1f1ded92007-08-24 21:00:35 +00001437
Steve Naroff14108da2009-07-10 23:34:53 +00001438 if (Ops.E->getLHS()->getType()->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001439 Ops.E->getLHS()->getType()->getAs<PointerType>()->isVariableArrayType()) {
Eli Friedmandaa24a22009-03-28 02:45:41 +00001440 // The amount of the addition needs to account for the VLA size for
1441 // ptr-int
1442 // The amount of the division needs to account for the VLA size for
1443 // ptr-ptr.
1444 CGF.ErrorUnsupported(Ops.E, "VLA pointer subtraction");
1445 }
1446
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001447 const QualType LHSType = Ops.E->getLHS()->getType();
Steve Naroff14108da2009-07-10 23:34:53 +00001448 const QualType LHSElementType = LHSType->getPointeeType();
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001449 if (!isa<llvm::PointerType>(Ops.RHS->getType())) {
1450 // pointer - int
1451 Value *Idx = Ops.RHS;
1452 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
Sanjiv Gupta7cabee52009-04-24 02:40:57 +00001453 if (Width < CGF.LLVMPointerWidth) {
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001454 // Zero or sign extend the pointer value based on whether the index is
1455 // signed or not.
Owen Anderson0032b272009-08-13 21:57:51 +00001456 const llvm::Type *IdxType =
1457 llvm::IntegerType::get(VMContext, CGF.LLVMPointerWidth);
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001458 if (Ops.E->getRHS()->getType()->isSignedIntegerType())
1459 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1460 else
1461 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1462 }
1463 Idx = Builder.CreateNeg(Idx, "sub.ptr.neg");
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001464
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001465 // Handle interface types, which are not represented with a concrete type.
1466 if (const ObjCInterfaceType *OIT =
Daniel Dunbar2a866252009-04-25 05:08:32 +00001467 dyn_cast<ObjCInterfaceType>(LHSElementType)) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001468 llvm::Value *InterfaceSize =
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001469 llvm::ConstantInt::get(Idx->getType(),
Daniel Dunbar2a866252009-04-25 05:08:32 +00001470 CGF.getContext().getTypeSize(OIT) / 8);
1471 Idx = Builder.CreateMul(Idx, InterfaceSize);
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00001472 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
Daniel Dunbar2a866252009-04-25 05:08:32 +00001473 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1474 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "add.ptr");
1475 return Builder.CreateBitCast(Res, Ops.LHS->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001476 }
Daniel Dunbar2a866252009-04-25 05:08:32 +00001477
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001478 // Explicitly handle GNU void* and function pointer arithmetic
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001479 // extensions. The GNU void* casts amount to no-ops since our void* type is
1480 // i8*, but this is future proof.
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001481 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00001482 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001483 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1484 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "sub.ptr");
1485 return Builder.CreateBitCast(Res, Ops.LHS->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001486 }
1487
Dan Gohman664f8932009-08-12 00:33:55 +00001488 return Builder.CreateInBoundsGEP(Ops.LHS, Idx, "sub.ptr");
Daniel Dunbar820b0332008-08-05 00:47:03 +00001489 } else {
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001490 // pointer - pointer
1491 Value *LHS = Ops.LHS;
1492 Value *RHS = Ops.RHS;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001493
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001494 uint64_t ElementSize;
Daniel Dunbar820b0332008-08-05 00:47:03 +00001495
Chris Lattnere5ed1512009-02-11 07:21:43 +00001496 // Handle GCC extension for pointer arithmetic on void* and function pointer
1497 // types.
1498 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001499 ElementSize = 1;
1500 } else {
1501 ElementSize = CGF.getContext().getTypeSize(LHSElementType) / 8;
1502 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001503
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001504 const llvm::Type *ResultType = ConvertType(Ops.Ty);
1505 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
1506 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1507 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001508
Chris Lattnere5ed1512009-02-11 07:21:43 +00001509 // Optimize out the shift for element size of 1.
1510 if (ElementSize == 1)
1511 return BytesBetween;
Dan Gohmandf110942009-08-11 22:40:09 +00001512
1513 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001514 // pointer difference in C is only defined in the case where both operands
1515 // are pointing to elements of an array.
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001516 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
Dan Gohmandf110942009-08-11 22:40:09 +00001517 return Builder.CreateExactSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
Chris Lattner7f02f722007-08-24 05:35:26 +00001518 }
Chris Lattner7f02f722007-08-24 05:35:26 +00001519}
1520
1521Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
1522 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1523 // RHS to the same size as the LHS.
1524 Value *RHS = Ops.RHS;
1525 if (Ops.LHS->getType() != RHS->getType())
1526 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001527
Chris Lattner7f02f722007-08-24 05:35:26 +00001528 return Builder.CreateShl(Ops.LHS, RHS, "shl");
1529}
1530
1531Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
1532 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1533 // RHS to the same size as the LHS.
1534 Value *RHS = Ops.RHS;
1535 if (Ops.LHS->getType() != RHS->getType())
1536 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001537
Chris Lattner1f1ded92007-08-24 21:00:35 +00001538 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner7f02f722007-08-24 05:35:26 +00001539 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
1540 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
1541}
1542
1543Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
1544 unsigned SICmpOpc, unsigned FCmpOpc) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001545 TestAndClearIgnoreResultAssign();
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001546 Value *Result;
Chris Lattner7f02f722007-08-24 05:35:26 +00001547 QualType LHSTy = E->getLHS()->getType();
Eli Friedmanb81c7862009-12-11 07:36:43 +00001548 if (LHSTy->isMemberFunctionPointerType()) {
1549 Value *LHSPtr = CGF.EmitAnyExprToTemp(E->getLHS()).getAggregateAddr();
1550 Value *RHSPtr = CGF.EmitAnyExprToTemp(E->getRHS()).getAggregateAddr();
1551 llvm::Value *LHSFunc = Builder.CreateStructGEP(LHSPtr, 0);
1552 LHSFunc = Builder.CreateLoad(LHSFunc);
1553 llvm::Value *RHSFunc = Builder.CreateStructGEP(RHSPtr, 0);
1554 RHSFunc = Builder.CreateLoad(RHSFunc);
1555 Value *ResultF = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1556 LHSFunc, RHSFunc, "cmp.func");
1557 Value *NullPtr = llvm::Constant::getNullValue(LHSFunc->getType());
1558 Value *ResultNull = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1559 LHSFunc, NullPtr, "cmp.null");
1560 llvm::Value *LHSAdj = Builder.CreateStructGEP(LHSPtr, 1);
1561 LHSAdj = Builder.CreateLoad(LHSAdj);
1562 llvm::Value *RHSAdj = Builder.CreateStructGEP(RHSPtr, 1);
1563 RHSAdj = Builder.CreateLoad(RHSAdj);
1564 Value *ResultA = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1565 LHSAdj, RHSAdj, "cmp.adj");
1566 if (E->getOpcode() == BinaryOperator::EQ) {
1567 Result = Builder.CreateOr(ResultNull, ResultA, "or.na");
1568 Result = Builder.CreateAnd(Result, ResultF, "and.f");
1569 } else {
1570 assert(E->getOpcode() == BinaryOperator::NE &&
1571 "Member pointer comparison other than == or != ?");
1572 Result = Builder.CreateAnd(ResultNull, ResultA, "and.na");
1573 Result = Builder.CreateOr(Result, ResultF, "or.f");
1574 }
1575 } else if (!LHSTy->isAnyComplexType()) {
Chris Lattner7f02f722007-08-24 05:35:26 +00001576 Value *LHS = Visit(E->getLHS());
1577 Value *RHS = Visit(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001578
Eli Friedman1360d4a2009-07-22 06:07:16 +00001579 if (LHS->getType()->isFPOrFPVector()) {
Nate Begeman7a66d7b2008-07-25 20:16:05 +00001580 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00001581 LHS, RHS, "cmp");
Eli Friedmanec2c1262008-05-29 15:09:15 +00001582 } else if (LHSTy->isSignedIntegerType()) {
1583 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00001584 LHS, RHS, "cmp");
1585 } else {
Eli Friedmanec2c1262008-05-29 15:09:15 +00001586 // Unsigned integers and pointers.
1587 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00001588 LHS, RHS, "cmp");
1589 }
Chris Lattner9c10fcf2009-07-08 01:08:03 +00001590
1591 // If this is a vector comparison, sign extend the result to the appropriate
1592 // vector integer type and return it (don't convert to bool).
1593 if (LHSTy->isVectorType())
1594 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001595
Chris Lattner7f02f722007-08-24 05:35:26 +00001596 } else {
1597 // Complex Comparison: can only be an equality comparison.
1598 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
1599 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001600
John McCall183700f2009-09-21 23:43:11 +00001601 QualType CETy = LHSTy->getAs<ComplexType>()->getElementType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001602
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001603 Value *ResultR, *ResultI;
Chris Lattner7f02f722007-08-24 05:35:26 +00001604 if (CETy->isRealFloatingType()) {
1605 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1606 LHS.first, RHS.first, "cmp.r");
1607 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1608 LHS.second, RHS.second, "cmp.i");
1609 } else {
1610 // Complex comparisons can only be equality comparisons. As such, signed
1611 // and unsigned opcodes are the same.
1612 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1613 LHS.first, RHS.first, "cmp.r");
1614 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1615 LHS.second, RHS.second, "cmp.i");
1616 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001617
Chris Lattner7f02f722007-08-24 05:35:26 +00001618 if (E->getOpcode() == BinaryOperator::EQ) {
1619 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1620 } else {
1621 assert(E->getOpcode() == BinaryOperator::NE &&
1622 "Complex comparison other than == or != ?");
1623 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1624 }
1625 }
Nuno Lopes32f62092009-01-11 23:22:37 +00001626
1627 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
Chris Lattner7f02f722007-08-24 05:35:26 +00001628}
1629
1630Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001631 bool Ignore = TestAndClearIgnoreResultAssign();
1632
1633 // __block variables need to have the rhs evaluated first, plus this should
1634 // improve codegen just a little.
Chris Lattner7f02f722007-08-24 05:35:26 +00001635 Value *RHS = Visit(E->getRHS());
Mike Stump99459b62009-05-21 21:05:15 +00001636 LValue LHS = EmitLValue(E->getLHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001637
Daniel Dunbared3849b2008-11-19 09:36:46 +00001638 // Store the value into the LHS. Bit-fields are handled specially
Daniel Dunbar371d16f2008-11-19 11:54:05 +00001639 // because the result is altered by the store, i.e., [C99 6.5.16p1]
1640 // 'An assignment expression has the value of the left operand after
Eli Friedmandaa24a22009-03-28 02:45:41 +00001641 // the assignment...'.
Mike Stump7f79f9b2009-05-29 15:46:01 +00001642 if (LHS.isBitfield()) {
1643 if (!LHS.isVolatileQualified()) {
1644 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType(),
1645 &RHS);
1646 return RHS;
1647 } else
1648 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType());
1649 } else
Daniel Dunbared3849b2008-11-19 09:36:46 +00001650 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
Mike Stump7f79f9b2009-05-29 15:46:01 +00001651 if (Ignore)
1652 return 0;
1653 return EmitLoadOfLValue(LHS, E->getType());
Chris Lattner7f02f722007-08-24 05:35:26 +00001654}
1655
1656Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
Chris Lattner7804bcb2009-10-17 04:24:20 +00001657 const llvm::Type *ResTy = ConvertType(E->getType());
1658
Chris Lattner20eb09d2008-11-12 08:26:50 +00001659 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
1660 // If we have 1 && X, just emit X without inserting the control flow.
1661 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1662 if (Cond == 1) { // If we have 1 && X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00001663 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner7804bcb2009-10-17 04:24:20 +00001664 // ZExt result to int or bool.
1665 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
Chris Lattner0946ccd2008-11-11 07:41:27 +00001666 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001667
Chris Lattner7804bcb2009-10-17 04:24:20 +00001668 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
Chris Lattner20eb09d2008-11-12 08:26:50 +00001669 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner7804bcb2009-10-17 04:24:20 +00001670 return llvm::Constant::getNullValue(ResTy);
Chris Lattner0946ccd2008-11-11 07:41:27 +00001671 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001672
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00001673 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
1674 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
Chris Lattner20eb09d2008-11-12 08:26:50 +00001675
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001676 // Branch on the LHS first. If it is false, go to the failure (cont) block.
1677 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
1678
1679 // Any edges into the ContBlock are now from an (indeterminate number of)
1680 // edges from this first condition. All of these values will be false. Start
1681 // setting up the PHI node in the Cont Block for this.
Owen Anderson0032b272009-08-13 21:57:51 +00001682 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext),
1683 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001684 PN->reserveOperandSpace(2); // Normal case, two inputs.
1685 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1686 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00001687 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001688
Anders Carlssona36bf8f2009-11-20 17:27:56 +00001689 CGF.StartConditionalBranch();
Chris Lattner7f02f722007-08-24 05:35:26 +00001690 CGF.EmitBlock(RHSBlock);
1691 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Anders Carlssona36bf8f2009-11-20 17:27:56 +00001692 CGF.FinishConditionalBranch();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001693
Chris Lattner7f02f722007-08-24 05:35:26 +00001694 // Reaquire the RHS block, as there may be subblocks inserted.
1695 RHSBlock = Builder.GetInsertBlock();
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001696
1697 // Emit an unconditional branch from this block to ContBlock. Insert an entry
1698 // into the phi node for the edge with the value of RHSCond.
Chris Lattner7f02f722007-08-24 05:35:26 +00001699 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00001700 PN->addIncoming(RHSCond, RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001701
Chris Lattner7f02f722007-08-24 05:35:26 +00001702 // ZExt result to int.
Chris Lattner7804bcb2009-10-17 04:24:20 +00001703 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00001704}
1705
1706Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
Chris Lattner7804bcb2009-10-17 04:24:20 +00001707 const llvm::Type *ResTy = ConvertType(E->getType());
1708
Chris Lattner20eb09d2008-11-12 08:26:50 +00001709 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
1710 // If we have 0 || X, just emit X without inserting the control flow.
1711 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1712 if (Cond == -1) { // If we have 0 || X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00001713 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner7804bcb2009-10-17 04:24:20 +00001714 // ZExt result to int or bool.
1715 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
Chris Lattner0946ccd2008-11-11 07:41:27 +00001716 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001717
Chris Lattner7804bcb2009-10-17 04:24:20 +00001718 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
Chris Lattner20eb09d2008-11-12 08:26:50 +00001719 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner7804bcb2009-10-17 04:24:20 +00001720 return llvm::ConstantInt::get(ResTy, 1);
Chris Lattner0946ccd2008-11-11 07:41:27 +00001721 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001722
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00001723 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
1724 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001725
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001726 // Branch on the LHS first. If it is true, go to the success (cont) block.
1727 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
1728
1729 // Any edges into the ContBlock are now from an (indeterminate number of)
1730 // edges from this first condition. All of these values will be true. Start
1731 // setting up the PHI node in the Cont Block for this.
Owen Anderson0032b272009-08-13 21:57:51 +00001732 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext),
1733 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001734 PN->reserveOperandSpace(2); // Normal case, two inputs.
1735 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1736 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00001737 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001738
Anders Carlssona36bf8f2009-11-20 17:27:56 +00001739 CGF.StartConditionalBranch();
Anders Carlsson33da07d2009-06-04 02:53:13 +00001740
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001741 // Emit the RHS condition as a bool value.
Chris Lattner7f02f722007-08-24 05:35:26 +00001742 CGF.EmitBlock(RHSBlock);
1743 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001744
Anders Carlssona36bf8f2009-11-20 17:27:56 +00001745 CGF.FinishConditionalBranch();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001746
Chris Lattner7f02f722007-08-24 05:35:26 +00001747 // Reaquire the RHS block, as there may be subblocks inserted.
1748 RHSBlock = Builder.GetInsertBlock();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001749
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001750 // Emit an unconditional branch from this block to ContBlock. Insert an entry
1751 // into the phi node for the edge with the value of RHSCond.
1752 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00001753 PN->addIncoming(RHSCond, RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001754
Chris Lattner7f02f722007-08-24 05:35:26 +00001755 // ZExt result to int.
Chris Lattner7804bcb2009-10-17 04:24:20 +00001756 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00001757}
1758
1759Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
1760 CGF.EmitStmt(E->getLHS());
Daniel Dunbara448fb22008-11-11 23:11:34 +00001761 CGF.EnsureInsertPoint();
Chris Lattner7f02f722007-08-24 05:35:26 +00001762 return Visit(E->getRHS());
1763}
1764
1765//===----------------------------------------------------------------------===//
1766// Other Operators
1767//===----------------------------------------------------------------------===//
1768
Chris Lattner9802a512008-11-12 08:55:54 +00001769/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
1770/// expression is cheap enough and side-effect-free enough to evaluate
1771/// unconditionally instead of conditionally. This is used to convert control
1772/// flow into selects in some cases.
Mike Stumpdf317bf2009-11-03 23:25:48 +00001773static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
1774 CodeGenFunction &CGF) {
Chris Lattner9802a512008-11-12 08:55:54 +00001775 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
Mike Stumpdf317bf2009-11-03 23:25:48 +00001776 return isCheapEnoughToEvaluateUnconditionally(PE->getSubExpr(), CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001777
Chris Lattner9802a512008-11-12 08:55:54 +00001778 // TODO: Allow anything we can constant fold to an integer or fp constant.
1779 if (isa<IntegerLiteral>(E) || isa<CharacterLiteral>(E) ||
1780 isa<FloatingLiteral>(E))
1781 return true;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001782
Chris Lattner9802a512008-11-12 08:55:54 +00001783 // Non-volatile automatic variables too, to get "cond ? X : Y" where
1784 // X and Y are local variables.
1785 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1786 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Mike Stumpdf317bf2009-11-03 23:25:48 +00001787 if (VD->hasLocalStorage() && !(CGF.getContext()
1788 .getCanonicalType(VD->getType())
1789 .isVolatileQualified()))
Chris Lattner9802a512008-11-12 08:55:54 +00001790 return true;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001791
Chris Lattner9802a512008-11-12 08:55:54 +00001792 return false;
1793}
1794
1795
Chris Lattner7f02f722007-08-24 05:35:26 +00001796Value *ScalarExprEmitter::
1797VisitConditionalOperator(const ConditionalOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001798 TestAndClearIgnoreResultAssign();
Chris Lattner31a09842008-11-12 08:04:58 +00001799 // If the condition constant folds and can be elided, try to avoid emitting
1800 // the condition and the dead arm.
1801 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getCond())){
Chris Lattnerc657e922008-11-11 18:56:45 +00001802 Expr *Live = E->getLHS(), *Dead = E->getRHS();
Chris Lattner31a09842008-11-12 08:04:58 +00001803 if (Cond == -1)
Chris Lattnerc657e922008-11-11 18:56:45 +00001804 std::swap(Live, Dead);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001805
Chris Lattner31a09842008-11-12 08:04:58 +00001806 // If the dead side doesn't have labels we need, and if the Live side isn't
1807 // the gnu missing ?: extension (which we could handle, but don't bother
1808 // to), just emit the Live part.
1809 if ((!Dead || !CGF.ContainsLabel(Dead)) && // No labels in dead part
1810 Live) // Live part isn't missing.
1811 return Visit(Live);
Chris Lattnerc657e922008-11-11 18:56:45 +00001812 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001813
1814
Chris Lattner9802a512008-11-12 08:55:54 +00001815 // If this is a really simple expression (like x ? 4 : 5), emit this as a
1816 // select instead of as control flow. We can only do this if it is cheap and
Chris Lattner531a5502008-11-16 06:16:27 +00001817 // safe to evaluate the LHS and RHS unconditionally.
Mike Stumpdf317bf2009-11-03 23:25:48 +00001818 if (E->getLHS() && isCheapEnoughToEvaluateUnconditionally(E->getLHS(),
1819 CGF) &&
1820 isCheapEnoughToEvaluateUnconditionally(E->getRHS(), CGF)) {
Chris Lattner9802a512008-11-12 08:55:54 +00001821 llvm::Value *CondV = CGF.EvaluateExprAsBool(E->getCond());
1822 llvm::Value *LHS = Visit(E->getLHS());
1823 llvm::Value *RHS = Visit(E->getRHS());
1824 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
1825 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001826
1827
Daniel Dunbarbe65abc2008-11-12 10:13:37 +00001828 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
1829 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00001830 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
Chris Lattner035cf422008-11-12 08:08:13 +00001831 Value *CondVal = 0;
Chris Lattner31a09842008-11-12 08:04:58 +00001832
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001833 // If we don't have the GNU missing condition extension, emit a branch on bool
1834 // the normal way.
Chris Lattner12d152f2009-02-13 23:35:32 +00001835 if (E->getLHS()) {
1836 // Otherwise, just use EmitBranchOnBoolExpr to get small and simple code for
1837 // the branch on bool.
1838 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
1839 } else {
1840 // Otherwise, for the ?: extension, evaluate the conditional and then
1841 // convert it to bool the hard way. We do this explicitly because we need
1842 // the unconverted value for the missing middle value of the ?:.
Chris Lattner035cf422008-11-12 08:08:13 +00001843 CondVal = CGF.EmitScalarExpr(E->getCond());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001844
Chris Lattner12d152f2009-02-13 23:35:32 +00001845 // In some cases, EmitScalarConversion will delete the "CondVal" expression
1846 // if there are no extra uses (an optimization). Inhibit this by making an
1847 // extra dead use, because we're going to add a use of CondVal later. We
1848 // don't use the builder for this, because we don't want it to get optimized
1849 // away. This leaves dead code, but the ?: extension isn't common.
1850 new llvm::BitCastInst(CondVal, CondVal->getType(), "dummy?:holder",
1851 Builder.GetInsertBlock());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001852
Chris Lattner035cf422008-11-12 08:08:13 +00001853 Value *CondBoolVal =
1854 CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
1855 CGF.getContext().BoolTy);
1856 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
Chris Lattner035cf422008-11-12 08:08:13 +00001857 }
Anders Carlssonfb6fa302009-06-04 03:00:32 +00001858
Anders Carlssona36bf8f2009-11-20 17:27:56 +00001859 CGF.StartConditionalBranch();
Chris Lattner7f02f722007-08-24 05:35:26 +00001860 CGF.EmitBlock(LHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001861
Chris Lattner7f02f722007-08-24 05:35:26 +00001862 // Handle the GNU extension for missing LHS.
Chris Lattnera21ddb32007-11-26 01:40:58 +00001863 Value *LHS;
1864 if (E->getLHS())
Eli Friedman856226c2008-05-16 20:38:39 +00001865 LHS = Visit(E->getLHS());
Chris Lattnera21ddb32007-11-26 01:40:58 +00001866 else // Perform promotions, to handle cases like "short ?: int"
1867 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001868
Anders Carlssona36bf8f2009-11-20 17:27:56 +00001869 CGF.FinishConditionalBranch();
Chris Lattner7f02f722007-08-24 05:35:26 +00001870 LHSBlock = Builder.GetInsertBlock();
Daniel Dunbard57a8712008-11-11 09:41:28 +00001871 CGF.EmitBranch(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001872
Anders Carlssona36bf8f2009-11-20 17:27:56 +00001873 CGF.StartConditionalBranch();
Chris Lattner7f02f722007-08-24 05:35:26 +00001874 CGF.EmitBlock(RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001875
Eli Friedman856226c2008-05-16 20:38:39 +00001876 Value *RHS = Visit(E->getRHS());
Anders Carlssona36bf8f2009-11-20 17:27:56 +00001877 CGF.FinishConditionalBranch();
Chris Lattner7f02f722007-08-24 05:35:26 +00001878 RHSBlock = Builder.GetInsertBlock();
Daniel Dunbard57a8712008-11-11 09:41:28 +00001879 CGF.EmitBranch(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001880
Chris Lattner7f02f722007-08-24 05:35:26 +00001881 CGF.EmitBlock(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001882
Eli Friedman48daf592009-12-07 20:25:53 +00001883 // If the LHS or RHS is a throw expression, it will be legitimately null.
1884 if (!LHS)
1885 return RHS;
1886 if (!RHS)
1887 return LHS;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001888
Chris Lattner7f02f722007-08-24 05:35:26 +00001889 // Create a PHI node for the real part.
1890 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
1891 PN->reserveOperandSpace(2);
1892 PN->addIncoming(LHS, LHSBlock);
1893 PN->addIncoming(RHS, RHSBlock);
1894 return PN;
1895}
1896
1897Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Eli Friedman79769322009-03-04 05:52:32 +00001898 return Visit(E->getChosenSubExpr(CGF.getContext()));
Chris Lattner7f02f722007-08-24 05:35:26 +00001899}
1900
Chris Lattner2202bce2007-11-30 17:56:23 +00001901Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Eli Friedman4fd0aa52009-01-20 17:46:04 +00001902 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlssonddf7cac2008-11-04 05:30:00 +00001903 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
1904
1905 // If EmitVAArg fails, we fall back to the LLVM instruction.
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001906 if (!ArgPtr)
Anders Carlssonddf7cac2008-11-04 05:30:00 +00001907 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
1908
Mike Stump7f79f9b2009-05-29 15:46:01 +00001909 // FIXME Volatility.
Anders Carlssonddf7cac2008-11-04 05:30:00 +00001910 return Builder.CreateLoad(ArgPtr);
Anders Carlsson7c50aca2007-10-15 20:28:48 +00001911}
1912
Mike Stumpdf6b68c2009-02-12 18:29:15 +00001913Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *BE) {
Mike Stump08920992009-03-07 02:35:30 +00001914 return CGF.BuildBlockLiteralTmp(BE);
Mike Stumpdf6b68c2009-02-12 18:29:15 +00001915}
1916
Chris Lattner7f02f722007-08-24 05:35:26 +00001917//===----------------------------------------------------------------------===//
1918// Entry Point into this File
1919//===----------------------------------------------------------------------===//
1920
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001921/// EmitScalarExpr - Emit the computation of the specified expression of scalar
1922/// type, ignoring the result.
Mike Stump7f79f9b2009-05-29 15:46:01 +00001923Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
Chris Lattner7f02f722007-08-24 05:35:26 +00001924 assert(E && !hasAggregateLLVMType(E->getType()) &&
1925 "Invalid scalar expression to emit");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001926
Mike Stump7f79f9b2009-05-29 15:46:01 +00001927 return ScalarExprEmitter(*this, IgnoreResultAssign)
1928 .Visit(const_cast<Expr*>(E));
Chris Lattner7f02f722007-08-24 05:35:26 +00001929}
Chris Lattner3707b252007-08-26 06:48:56 +00001930
1931/// EmitScalarConversion - Emit a conversion from the specified type to the
1932/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001933Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
1934 QualType DstTy) {
Chris Lattner3707b252007-08-26 06:48:56 +00001935 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
1936 "Invalid scalar expression to emit");
1937 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
1938}
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001939
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001940/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
1941/// type to the specified destination type, where the destination type is an
1942/// LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001943Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
1944 QualType SrcTy,
1945 QualType DstTy) {
Chris Lattner9b2dc282008-04-04 16:54:41 +00001946 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001947 "Invalid complex -> scalar conversion");
1948 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
1949 DstTy);
1950}
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001951
1952Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) {
1953 assert(V1->getType() == V2->getType() &&
1954 "Vector operands must be of the same type");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001955 unsigned NumElements =
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001956 cast<llvm::VectorType>(V1->getType())->getNumElements();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001957
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001958 va_list va;
1959 va_start(va, V2);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001960
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001961 llvm::SmallVector<llvm::Constant*, 16> Args;
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001962 for (unsigned i = 0; i < NumElements; i++) {
1963 int n = va_arg(va, int);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001964 assert(n >= 0 && n < (int)NumElements * 2 &&
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001965 "Vector shuffle index out of bounds!");
Owen Anderson0032b272009-08-13 21:57:51 +00001966 Args.push_back(llvm::ConstantInt::get(
1967 llvm::Type::getInt32Ty(VMContext), n));
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001968 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001969
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001970 const char *Name = va_arg(va, const char *);
1971 va_end(va);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001972
Owen Anderson4a289322009-07-28 21:22:35 +00001973 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001974
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001975 return Builder.CreateShuffleVector(V1, V2, Mask, Name);
1976}
1977
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001978llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals,
Chris Lattner345f7202008-07-26 20:15:14 +00001979 unsigned NumVals, bool isSplat) {
Anders Carlsson6086bbd2007-12-15 21:23:30 +00001980 llvm::Value *Vec
Owen Anderson03e20502009-07-30 23:11:26 +00001981 = llvm::UndefValue::get(llvm::VectorType::get(Vals[0]->getType(), NumVals));
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001982
Chris Lattner345f7202008-07-26 20:15:14 +00001983 for (unsigned i = 0, e = NumVals; i != e; ++i) {
Nate Begeman4119d1a2007-12-30 02:59:45 +00001984 llvm::Value *Val = isSplat ? Vals[0] : Vals[i];
Owen Anderson0032b272009-08-13 21:57:51 +00001985 llvm::Value *Idx = llvm::ConstantInt::get(
1986 llvm::Type::getInt32Ty(VMContext), i);
Nate Begeman4119d1a2007-12-30 02:59:45 +00001987 Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp");
Anders Carlsson6086bbd2007-12-15 21:23:30 +00001988 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001989
1990 return Vec;
Anders Carlsson6086bbd2007-12-15 21:23:30 +00001991}
Fariborz Jahanian820bca42009-12-09 23:35:29 +00001992
1993LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
1994 llvm::Value *V;
1995 // object->isa or (*object).isa
1996 // Generate code as for: *(Class*)object
1997 Expr *BaseExpr = E->getBase();
1998 if (E->isArrow())
1999 V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr);
2000 else
2001 V = EmitLValue(BaseExpr).getAddress();
2002
2003 // build Class* type
2004 const llvm::Type *ClassPtrTy = ConvertType(E->getType());
2005 ClassPtrTy = ClassPtrTy->getPointerTo();
2006 V = Builder.CreateBitCast(V, ClassPtrTy);
2007 LValue LV = LValue::MakeAddr(V, MakeQualifiers(E->getType()));
2008 return LV;
2009}
2010