blob: e14d40c3b6d376c97a346cd087b4d19306fc768f [file] [log] [blame]
Chris Lattner9fba49a2007-08-24 05:35:26 +00001//===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-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 Lattner9fba49a2007-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"
15#include "CodeGenModule.h"
Daniel Dunbareee5cd12008-08-11 05:00:27 +000016#include "clang/AST/ASTContext.h"
Daniel Dunbarfa456242008-08-12 05:08:18 +000017#include "clang/AST/DeclObjC.h"
Eli Friedmanccffea92009-01-24 22:38:55 +000018#include "clang/AST/RecordLayout.h"
Daniel Dunbareee5cd12008-08-11 05:00:27 +000019#include "clang/AST/StmtVisitor.h"
Chris Lattnerd54d1f22008-04-20 00:50:39 +000020#include "clang/Basic/TargetInfo.h"
Chris Lattner9fba49a2007-08-24 05:35:26 +000021#include "llvm/Constants.h"
22#include "llvm/Function.h"
Anders Carlsson36f07d82007-10-29 05:01:08 +000023#include "llvm/GlobalVariable.h"
Anders Carlsson36760332007-10-15 20:28:48 +000024#include "llvm/Intrinsics.h"
Mike Stumpdb789912009-04-01 20:28:16 +000025#include "llvm/Module.h"
Chris Lattner9fba49a2007-08-24 05:35:26 +000026#include "llvm/Support/Compiler.h"
Chris Lattner7f80bb32008-11-12 08:38:24 +000027#include "llvm/Support/CFG.h"
Mike Stumpfca5da02009-02-21 20:00:35 +000028#include "llvm/Target/TargetData.h"
Chris Lattnerc2126682008-01-03 07:05:49 +000029#include <cstdarg>
Ted Kremenek03cf4df2007-12-10 23:44:32 +000030
Chris Lattner9fba49a2007-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 Lattner660e31d2007-08-24 21:00:35 +000042 QualType Ty; // Computation Type.
Chris Lattner9fba49a2007-08-24 05:35:26 +000043 const BinaryOperator *E;
44};
45
46namespace {
47class VISIBILITY_HIDDEN ScalarExprEmitter
48 : public StmtVisitor<ScalarExprEmitter, Value*> {
49 CodeGenFunction &CGF;
Daniel Dunbard916e6e2008-11-01 01:53:16 +000050 CGBuilderTy &Builder;
Chris Lattnercbfb5512008-03-01 08:45:05 +000051
Chris Lattner9fba49a2007-08-24 05:35:26 +000052public:
53
Chris Lattnercbfb5512008-03-01 08:45:05 +000054 ScalarExprEmitter(CodeGenFunction &cgf) : CGF(cgf),
Daniel Dunbarf1f7f192008-08-20 00:28:19 +000055 Builder(CGF.Builder) {
Chris Lattner9fba49a2007-08-24 05:35:26 +000056 }
Chris Lattner9fba49a2007-08-24 05:35:26 +000057
58 //===--------------------------------------------------------------------===//
59 // Utilities
60 //===--------------------------------------------------------------------===//
61
62 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
63 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
64
65 Value *EmitLoadOfLValue(LValue LV, QualType T) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +000066 return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +000067 }
68
69 /// EmitLoadOfLValue - Given an expression with complex type that represents a
70 /// value l-value, this method emits the address of the l-value, then loads
71 /// and returns the result.
72 Value *EmitLoadOfLValue(const Expr *E) {
Chris Lattner9fba49a2007-08-24 05:35:26 +000073 return EmitLoadOfLValue(EmitLValue(E), E->getType());
74 }
75
Chris Lattnerd8d44222007-08-26 16:42:57 +000076 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +000077 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +000078 Value *EmitConversionToBool(Value *Src, QualType DstTy);
79
Chris Lattner4e05d1e2007-08-26 06:48:56 +000080 /// EmitScalarConversion - Emit a conversion from the specified type to the
81 /// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +000082 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
83
84 /// EmitComplexToScalarConversion - Emit a conversion from the specified
85 /// complex type to the specified destination type, where the destination
86 /// type is an LLVM scalar type.
87 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
88 QualType SrcTy, QualType DstTy);
Mike Stump4eb81dc2009-02-12 18:29:15 +000089
Chris Lattner9fba49a2007-08-24 05:35:26 +000090 //===--------------------------------------------------------------------===//
91 // Visitor Methods
92 //===--------------------------------------------------------------------===//
93
94 Value *VisitStmt(Stmt *S) {
Ted Kremenekb3ee1932007-12-11 21:27:55 +000095 S->dump(CGF.getContext().getSourceManager());
Chris Lattner9fba49a2007-08-24 05:35:26 +000096 assert(0 && "Stmt can't have complex result type!");
97 return 0;
98 }
99 Value *VisitExpr(Expr *S);
100 Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
101
102 // Leaves.
103 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
104 return llvm::ConstantInt::get(E->getValue());
105 }
106 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Chris Lattner70c38672008-04-20 00:45:53 +0000107 return llvm::ConstantFP::get(E->getValue());
Chris Lattner9fba49a2007-08-24 05:35:26 +0000108 }
109 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
110 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
111 }
Nate Begemane9bfe6d2007-11-15 05:40:03 +0000112 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
113 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
114 }
Argiris Kirtzidis750eb972008-08-23 19:35:47 +0000115 Value *VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
116 return llvm::Constant::getNullValue(ConvertType(E->getType()));
117 }
Anders Carlsson774f9c72008-12-21 22:39:40 +0000118 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
119 return llvm::Constant::getNullValue(ConvertType(E->getType()));
120 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000121 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
122 return llvm::ConstantInt::get(ConvertType(E->getType()),
Steve Naroff85f0dc52007-10-15 20:41:53 +0000123 CGF.getContext().typesAreCompatible(
124 E->getArgType1(), E->getArgType2()));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000125 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000126 Value *VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
Daniel Dunbar879788d2008-08-04 16:51:22 +0000127 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
Daniel Dunbarb5fda0c2008-08-16 01:41:47 +0000128 llvm::Value *V =
129 llvm::ConstantInt::get(llvm::Type::Int32Ty,
130 CGF.GetIDForAddrOfLabel(E->getLabel()));
131
132 return Builder.CreateIntToPtr(V, ConvertType(E->getType()));
Daniel Dunbar879788d2008-08-04 16:51:22 +0000133 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000134
135 // l-values.
136 Value *VisitDeclRefExpr(DeclRefExpr *E) {
137 if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(E->getDecl()))
138 return llvm::ConstantInt::get(EC->getInitVal());
139 return EmitLoadOfLValue(E);
140 }
Daniel Dunbar91cc4022008-08-27 06:57:25 +0000141 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
142 return CGF.EmitObjCSelectorExpr(E);
143 }
144 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
145 return CGF.EmitObjCProtocolExpr(E);
146 }
147 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
148 return EmitLoadOfLValue(E);
149 }
Daniel Dunbar5e105892008-08-23 10:51:21 +0000150 Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
Daniel Dunbare6c31752008-08-29 08:11:39 +0000151 return EmitLoadOfLValue(E);
Daniel Dunbar91cc4022008-08-27 06:57:25 +0000152 }
Fariborz Jahanianb0973da2008-11-22 22:30:21 +0000153 Value *VisitObjCKVCRefExpr(ObjCKVCRefExpr *E) {
154 return EmitLoadOfLValue(E);
155 }
Daniel Dunbar91cc4022008-08-27 06:57:25 +0000156 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
157 return CGF.EmitObjCMessageExpr(E).getScalarVal();
Daniel Dunbar5e105892008-08-23 10:51:21 +0000158 }
159
Chris Lattner9fba49a2007-08-24 05:35:26 +0000160 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmand0e9d092008-05-14 19:38:39 +0000161 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000162 Value *VisitMemberExpr(Expr *E) { return EmitLoadOfLValue(E); }
Nate Begemanaf6ed502008-04-18 23:10:10 +0000163 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Chris Lattnera9177982008-10-26 23:53:12 +0000164 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
165 return EmitLoadOfLValue(E);
166 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000167 Value *VisitStringLiteral(Expr *E) { return EmitLValue(E).getAddress(); }
Chris Lattnerc5d32632009-02-24 22:18:39 +0000168 Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
169 return EmitLValue(E).getAddress();
170 }
171
Chris Lattner69909292008-08-10 01:53:14 +0000172 Value *VisitPredefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); }
Devang Patel01ab1302007-10-24 17:18:43 +0000173
174 Value *VisitInitListExpr(InitListExpr *E) {
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000175 unsigned NumInitElements = E->getNumInits();
176
Douglas Gregor9fddded2009-01-29 19:42:23 +0000177 if (E->hadArrayRangeDesignator()) {
178 CGF.ErrorUnsupported(E, "GNU array range designator extension");
179 }
180
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000181 const llvm::VectorType *VType =
Anders Carlsson35ab4f92008-01-29 01:15:48 +0000182 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
183
184 // We have a scalar in braces. Just use the first element.
185 if (!VType)
186 return Visit(E->getInit(0));
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000187
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000188 unsigned NumVectorElements = VType->getNumElements();
189 const llvm::Type *ElementType = VType->getElementType();
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000190
191 // Emit individual vector element stores.
192 llvm::Value *V = llvm::UndefValue::get(VType);
193
Anders Carlsson323d5682007-12-18 02:45:33 +0000194 // Emit initializers
195 unsigned i;
196 for (i = 0; i < NumInitElements; ++i) {
Devang Patel32c39832007-10-24 18:05:48 +0000197 Value *NewV = Visit(E->getInit(i));
198 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
199 V = Builder.CreateInsertElement(V, NewV, Idx);
Devang Patel01ab1302007-10-24 17:18:43 +0000200 }
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000201
202 // Emit remaining default initializers
203 for (/* Do not initialize i*/; i < NumVectorElements; ++i) {
204 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
205 llvm::Value *NewV = llvm::Constant::getNullValue(ElementType);
206 V = Builder.CreateInsertElement(V, NewV, Idx);
207 }
208
Devang Patel32c39832007-10-24 18:05:48 +0000209 return V;
Devang Patel01ab1302007-10-24 17:18:43 +0000210 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000211
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000212 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
213 return llvm::Constant::getNullValue(ConvertType(E->getType()));
214 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000215 Value *VisitImplicitCastExpr(const ImplicitCastExpr *E);
Eli Friedmana7ef8e52009-04-20 03:54:15 +0000216 Value *VisitCastExpr(const CastExpr *E) {
217 // Make sure to evaluate VLA bounds now so that we have them for later.
218 if (E->getType()->isVariablyModifiedType())
219 CGF.EmitVLASize(E->getType());
220
Chris Lattner9fba49a2007-08-24 05:35:26 +0000221 return EmitCastExpr(E->getSubExpr(), E->getType());
222 }
223 Value *EmitCastExpr(const Expr *E, QualType T);
224
225 Value *VisitCallExpr(const CallExpr *E) {
Anders Carlssoncd295282009-05-27 03:37:57 +0000226 if (E->getCallReturnType()->isReferenceType())
227 return EmitLoadOfLValue(E);
228
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000229 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000230 }
Daniel Dunbara04840b2008-08-23 03:46:30 +0000231
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000232 Value *VisitStmtExpr(const StmtExpr *E);
Mike Stumpfca5da02009-02-21 20:00:35 +0000233
Mike Stump2b6933f2009-02-28 09:07:16 +0000234 Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E);
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000235
Chris Lattner9fba49a2007-08-24 05:35:26 +0000236 // Unary Operators.
237 Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre);
238 Value *VisitUnaryPostDec(const UnaryOperator *E) {
239 return VisitPrePostIncDec(E, false, false);
240 }
241 Value *VisitUnaryPostInc(const UnaryOperator *E) {
242 return VisitPrePostIncDec(E, true, false);
243 }
244 Value *VisitUnaryPreDec(const UnaryOperator *E) {
245 return VisitPrePostIncDec(E, false, true);
246 }
247 Value *VisitUnaryPreInc(const UnaryOperator *E) {
248 return VisitPrePostIncDec(E, true, true);
249 }
250 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
251 return EmitLValue(E->getSubExpr()).getAddress();
252 }
253 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
254 Value *VisitUnaryPlus(const UnaryOperator *E) {
255 return Visit(E->getSubExpr());
256 }
257 Value *VisitUnaryMinus (const UnaryOperator *E);
258 Value *VisitUnaryNot (const UnaryOperator *E);
259 Value *VisitUnaryLNot (const UnaryOperator *E);
Chris Lattner01211af2007-08-24 21:20:17 +0000260 Value *VisitUnaryReal (const UnaryOperator *E);
261 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000262 Value *VisitUnaryExtension(const UnaryOperator *E) {
263 return Visit(E->getSubExpr());
264 }
Anders Carlsson52774ad2008-01-29 15:56:48 +0000265 Value *VisitUnaryOffsetOf(const UnaryOperator *E);
Anders Carlsson49d4a572009-04-14 16:58:56 +0000266
267 // C++
Chris Lattner3e254fb2008-04-08 04:40:51 +0000268 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
269 return Visit(DAE->getExpr());
270 }
Anders Carlsson49d4a572009-04-14 16:58:56 +0000271 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
272 return CGF.LoadCXXThis();
273 }
Anders Carlsson52774ad2008-01-29 15:56:48 +0000274
Anders Carlsson272b5f52009-05-19 04:48:36 +0000275 Value *VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) {
276 // FIXME: Do something with the temporaries!
277 return Visit(E->getSubExpr());
278 }
279
Chris Lattner9fba49a2007-08-24 05:35:26 +0000280 // Binary Operators.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000281 Value *EmitMul(const BinOpInfo &Ops) {
Mike Stumpf71b7742009-04-02 18:15:54 +0000282 if (CGF.getContext().getLangOptions().OverflowChecking
283 && Ops.Ty->isSignedIntegerType())
Mike Stumpdb789912009-04-01 20:28:16 +0000284 return EmitOverflowCheckedBinOp(Ops);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000285 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
286 }
Mike Stumpdb789912009-04-01 20:28:16 +0000287 /// Create a binary op that checks for overflow.
288 /// Currently only supports +, - and *.
289 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000290 Value *EmitDiv(const BinOpInfo &Ops);
291 Value *EmitRem(const BinOpInfo &Ops);
292 Value *EmitAdd(const BinOpInfo &Ops);
293 Value *EmitSub(const BinOpInfo &Ops);
294 Value *EmitShl(const BinOpInfo &Ops);
295 Value *EmitShr(const BinOpInfo &Ops);
296 Value *EmitAnd(const BinOpInfo &Ops) {
297 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
298 }
299 Value *EmitXor(const BinOpInfo &Ops) {
300 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
301 }
302 Value *EmitOr (const BinOpInfo &Ops) {
303 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
304 }
305
Chris Lattner660e31d2007-08-24 21:00:35 +0000306 BinOpInfo EmitBinOps(const BinaryOperator *E);
Chris Lattner0d965302007-08-26 21:41:21 +0000307 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000308 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
309
310 // Binary operators and binary compound assignment operators.
311#define HANDLEBINOP(OP) \
Chris Lattner0d965302007-08-26 21:41:21 +0000312 Value *VisitBin ## OP(const BinaryOperator *E) { \
313 return Emit ## OP(EmitBinOps(E)); \
314 } \
315 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
316 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner660e31d2007-08-24 21:00:35 +0000317 }
318 HANDLEBINOP(Mul);
319 HANDLEBINOP(Div);
320 HANDLEBINOP(Rem);
321 HANDLEBINOP(Add);
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000322 HANDLEBINOP(Sub);
Chris Lattner660e31d2007-08-24 21:00:35 +0000323 HANDLEBINOP(Shl);
324 HANDLEBINOP(Shr);
325 HANDLEBINOP(And);
326 HANDLEBINOP(Xor);
327 HANDLEBINOP(Or);
328#undef HANDLEBINOP
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000329
Chris Lattner9fba49a2007-08-24 05:35:26 +0000330 // Comparisons.
331 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
332 unsigned SICmpOpc, unsigned FCmpOpc);
333#define VISITCOMP(CODE, UI, SI, FP) \
334 Value *VisitBin##CODE(const BinaryOperator *E) { \
335 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
336 llvm::FCmpInst::FP); }
337 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
338 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
339 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
340 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
341 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
342 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
343#undef VISITCOMP
344
345 Value *VisitBinAssign (const BinaryOperator *E);
346
347 Value *VisitBinLAnd (const BinaryOperator *E);
348 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000349 Value *VisitBinComma (const BinaryOperator *E);
350
351 // Other Operators.
Mike Stump4eb81dc2009-02-12 18:29:15 +0000352 Value *VisitBlockExpr(const BlockExpr *BE);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000353 Value *VisitConditionalOperator(const ConditionalOperator *CO);
354 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson36760332007-10-15 20:28:48 +0000355 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000356 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
357 return CGF.EmitObjCStringLiteral(E);
358 }
359};
360} // end anonymous namespace.
361
362//===----------------------------------------------------------------------===//
363// Utilities
364//===----------------------------------------------------------------------===//
365
Chris Lattnerd8d44222007-08-26 16:42:57 +0000366/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +0000367/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +0000368Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
369 assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs");
370
371 if (SrcType->isRealFloatingType()) {
372 // Compare against 0.0 for fp scalars.
373 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattnerd8d44222007-08-26 16:42:57 +0000374 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
375 }
376
Daniel Dunbar5d54eed2008-08-25 10:38:11 +0000377 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
Chris Lattnerd8d44222007-08-26 16:42:57 +0000378 "Unknown scalar type to convert");
379
380 // Because of the type rules of C, we often end up computing a logical value,
381 // then zero extending it to int, then wanting it as a logical value again.
382 // Optimize this common case.
383 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
384 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
385 Value *Result = ZI->getOperand(0);
Eli Friedman24f33972008-01-29 18:13:51 +0000386 // If there aren't any more uses, zap the instruction to save space.
387 // Note that there can be more uses, for example if this
388 // is the result of an assignment.
389 if (ZI->use_empty())
390 ZI->eraseFromParent();
Chris Lattnerd8d44222007-08-26 16:42:57 +0000391 return Result;
392 }
393 }
394
395 // Compare against an integer or pointer null.
396 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
397 return Builder.CreateICmpNE(Src, Zero, "tobool");
398}
399
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000400/// EmitScalarConversion - Emit a conversion from the specified type to the
401/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000402Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
403 QualType DstType) {
Chris Lattnerc154ac12008-07-26 22:37:01 +0000404 SrcType = CGF.getContext().getCanonicalType(SrcType);
405 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000406 if (SrcType == DstType) return Src;
Chris Lattnere133d7f2007-08-26 07:21:11 +0000407
408 if (DstType->isVoidType()) return 0;
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000409
410 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnerc39c3652007-08-26 16:52:28 +0000411 if (DstType->isBooleanType())
412 return EmitConversionToBool(Src, SrcType);
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000413
414 const llvm::Type *DstTy = ConvertType(DstType);
415
416 // Ignore conversions like int -> uint.
417 if (Src->getType() == DstTy)
418 return Src;
419
Daniel Dunbar238335f2008-08-25 09:51:32 +0000420 // Handle pointer conversions next: pointers can only be converted
421 // to/from other pointers and integers. Check for pointer types in
422 // terms of LLVM, as some native types (like Obj-C id) may map to a
423 // pointer type.
424 if (isa<llvm::PointerType>(DstTy)) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000425 // The source value may be an integer, or a pointer.
426 if (isa<llvm::PointerType>(Src->getType()))
427 return Builder.CreateBitCast(Src, DstTy, "conv");
428 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Eli Friedman35bcec82009-03-04 04:02:35 +0000429 // First, convert to the correct width so that we control the kind of
430 // extension.
431 const llvm::Type *MiddleTy = llvm::IntegerType::get(CGF.LLVMPointerWidth);
432 bool InputSigned = SrcType->isSignedIntegerType();
433 llvm::Value* IntResult =
434 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
435 // Then, cast to pointer.
436 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000437 }
438
Daniel Dunbar238335f2008-08-25 09:51:32 +0000439 if (isa<llvm::PointerType>(Src->getType())) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000440 // Must be an ptr to int cast.
441 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson44db38f2007-10-31 23:18:02 +0000442 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000443 }
444
Nate Begemanaf6ed502008-04-18 23:10:10 +0000445 // A scalar can be splatted to an extended vector of the same element type
Nate Begeman7903d052009-01-18 06:42:49 +0000446 if (DstType->isExtVectorType() && !isa<VectorType>(SrcType)) {
447 // Cast the scalar to element type
448 QualType EltTy = DstType->getAsExtVectorType()->getElementType();
449 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
450
451 // Insert the element in element zero of an undef vector
452 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
453 llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
454 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
455
456 // Splat the element across to all elements
457 llvm::SmallVector<llvm::Constant*, 16> Args;
458 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
459 for (unsigned i = 0; i < NumElements; i++)
460 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
461
462 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
463 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
464 return Yay;
465 }
Nate Begemanec2d1062007-12-30 02:59:45 +0000466
Chris Lattner4f025a42008-02-02 04:51:41 +0000467 // Allow bitcast from vector to integer/fp of the same size.
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000468 if (isa<llvm::VectorType>(Src->getType()) ||
Chris Lattner4f025a42008-02-02 04:51:41 +0000469 isa<llvm::VectorType>(DstTy))
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000470 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000471
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000472 // Finally, we have the arithmetic types: real int/float.
473 if (isa<llvm::IntegerType>(Src->getType())) {
474 bool InputSigned = SrcType->isSignedIntegerType();
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000475 if (isa<llvm::IntegerType>(DstTy))
476 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
477 else if (InputSigned)
478 return Builder.CreateSIToFP(Src, DstTy, "conv");
479 else
480 return Builder.CreateUIToFP(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000481 }
482
483 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
484 if (isa<llvm::IntegerType>(DstTy)) {
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000485 if (DstType->isSignedIntegerType())
486 return Builder.CreateFPToSI(Src, DstTy, "conv");
487 else
488 return Builder.CreateFPToUI(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000489 }
490
491 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000492 if (DstTy->getTypeID() < Src->getType()->getTypeID())
493 return Builder.CreateFPTrunc(Src, DstTy, "conv");
494 else
495 return Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000496}
497
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000498/// EmitComplexToScalarConversion - Emit a conversion from the specified
499/// complex type to the specified destination type, where the destination
500/// type is an LLVM scalar type.
501Value *ScalarExprEmitter::
502EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
503 QualType SrcTy, QualType DstTy) {
Chris Lattnerc39c3652007-08-26 16:52:28 +0000504 // Get the source element type.
Chris Lattnerc154ac12008-07-26 22:37:01 +0000505 SrcTy = SrcTy->getAsComplexType()->getElementType();
Chris Lattnerc39c3652007-08-26 16:52:28 +0000506
507 // Handle conversions to bool first, they are special: comparisons against 0.
508 if (DstTy->isBooleanType()) {
509 // Complex != 0 -> (Real != 0) | (Imag != 0)
510 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
511 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
512 return Builder.CreateOr(Src.first, Src.second, "tobool");
513 }
514
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000515 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
516 // the imaginary part of the complex value is discarded and the value of the
517 // real part is converted according to the conversion rules for the
518 // corresponding real type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000519 return EmitScalarConversion(Src.first, SrcTy, DstTy);
520}
521
522
Chris Lattner9fba49a2007-08-24 05:35:26 +0000523//===----------------------------------------------------------------------===//
524// Visitor Methods
525//===----------------------------------------------------------------------===//
526
527Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbar9503b782008-08-16 00:56:44 +0000528 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000529 if (E->getType()->isVoidType())
530 return 0;
531 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
532}
533
Eli Friedmand0e9d092008-05-14 19:38:39 +0000534Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
535 llvm::SmallVector<llvm::Constant*, 32> indices;
536 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
537 indices.push_back(cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i))));
538 }
539 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
540 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
541 Value* SV = llvm::ConstantVector::get(indices.begin(), indices.size());
542 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
543}
544
Chris Lattner9fba49a2007-08-24 05:35:26 +0000545Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
546 // Emit subscript expressions in rvalue context's. For most cases, this just
547 // loads the lvalue formed by the subscript expr. However, we have to be
548 // careful, because the base of a vector subscript is occasionally an rvalue,
549 // so we can't get it as an lvalue.
550 if (!E->getBase()->getType()->isVectorType())
551 return EmitLoadOfLValue(E);
552
553 // Handle the vector case. The base must be a vector, the index must be an
554 // integer value.
555 Value *Base = Visit(E->getBase());
556 Value *Idx = Visit(E->getIdx());
Eli Friedman4a0073b2009-03-28 02:45:41 +0000557 bool IdxSigned = E->getIdx()->getType()->isSignedIntegerType();
Eli Friedmand4531942009-03-28 03:27:06 +0000558 Idx = Builder.CreateIntCast(Idx, llvm::Type::Int32Ty, IdxSigned,
559 "vecidxcast");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000560 return Builder.CreateExtractElement(Base, Idx, "vecext");
561}
562
563/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
564/// also handle things like function to pointer-to-function decay, and array to
565/// pointer decay.
566Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
567 const Expr *Op = E->getSubExpr();
568
569 // If this is due to array->pointer conversion, emit the array expression as
570 // an l-value.
571 if (Op->getType()->isArrayType()) {
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000572 Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
Eli Friedman8fef47e2008-12-20 23:11:59 +0000573
Eli Friedman4a0073b2009-03-28 02:45:41 +0000574 // Note that VLA pointers are always decayed, so we don't need to do
575 // anything here.
Eli Friedman8fef47e2008-12-20 23:11:59 +0000576 if (!Op->getType()->isVariableArrayType()) {
577 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
578 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
579 ->getElementType()) &&
580 "Expected pointer to array");
581 V = Builder.CreateStructGEP(V, 0, "arraydecay");
Daniel Dunbar952f4732008-08-29 17:28:43 +0000582 }
Chris Lattnere54443b2007-12-12 04:13:20 +0000583
584 // The resultant pointer type can be implicitly casted to other pointer
Chris Lattner3b8f5c62008-07-23 06:31:27 +0000585 // types as well (e.g. void*) and can be implicitly converted to integer.
586 const llvm::Type *DestTy = ConvertType(E->getType());
587 if (V->getType() != DestTy) {
588 if (isa<llvm::PointerType>(DestTy))
589 V = Builder.CreateBitCast(V, DestTy, "ptrconv");
590 else {
591 assert(isa<llvm::IntegerType>(DestTy) && "Unknown array decay");
592 V = Builder.CreatePtrToInt(V, DestTy, "ptrconv");
593 }
594 }
Chris Lattnere54443b2007-12-12 04:13:20 +0000595 return V;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000596 }
Eli Friedman4a0073b2009-03-28 02:45:41 +0000597
Chris Lattner9fba49a2007-08-24 05:35:26 +0000598 return EmitCastExpr(Op, E->getType());
599}
600
601
602// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
603// have to handle a more broad range of conversions than explicit casts, as they
604// handle things like function to ptr-to-function decay etc.
605Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
Chris Lattner82e10392007-08-26 07:26:12 +0000606 // Handle cases where the source is an non-complex type.
Chris Lattner77288792008-02-16 23:55:16 +0000607
608 if (!CGF.hasAggregateLLVMType(E->getType())) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000609 Value *Src = Visit(const_cast<Expr*>(E));
610
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000611 // Use EmitScalarConversion to perform the conversion.
612 return EmitScalarConversion(Src, E->getType(), DestTy);
613 }
Chris Lattner77288792008-02-16 23:55:16 +0000614
Chris Lattnerde0908b2008-04-04 16:54:41 +0000615 if (E->getType()->isAnyComplexType()) {
Chris Lattner77288792008-02-16 23:55:16 +0000616 // Handle cases where the source is a complex type.
617 return EmitComplexToScalarConversion(CGF.EmitComplexExpr(E), E->getType(),
618 DestTy);
619 }
Chris Lattnerd579f7f2007-08-26 07:16:41 +0000620
Chris Lattner77288792008-02-16 23:55:16 +0000621 // Okay, this is a cast from an aggregate. It must be a cast to void. Just
622 // evaluate the result and return.
623 CGF.EmitAggExpr(E, 0, false);
624 return 0;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000625}
626
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000627Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
Chris Lattner09cee852008-07-26 20:23:23 +0000628 return CGF.EmitCompoundStmt(*E->getSubStmt(),
629 !E->getType()->isVoidType()).getScalarVal();
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000630}
631
Mike Stump2b6933f2009-02-28 09:07:16 +0000632Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
633 return Builder.CreateLoad(CGF.GetAddrOfBlockDecl(E), false, "tmp");
Mike Stumpfca5da02009-02-21 20:00:35 +0000634}
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000635
Chris Lattner9fba49a2007-08-24 05:35:26 +0000636//===----------------------------------------------------------------------===//
637// Unary Operators
638//===----------------------------------------------------------------------===//
639
640Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattner855e3d72007-08-24 16:24:49 +0000641 bool isInc, bool isPre) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000642 LValue LV = EmitLValue(E->getSubExpr());
Eli Friedman6a259872009-03-23 03:00:06 +0000643 QualType ValTy = E->getSubExpr()->getType();
644 Value *InVal = CGF.EmitLoadOfLValue(LV, ValTy).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000645
646 int AmountVal = isInc ? 1 : -1;
Eli Friedman4a0073b2009-03-28 02:45:41 +0000647
648 if (ValTy->isPointerType() &&
649 ValTy->getAsPointerType()->isVariableArrayType()) {
650 // The amount of the addition/subtraction needs to account for the VLA size
651 CGF.ErrorUnsupported(E, "VLA pointer inc/dec");
652 }
653
Chris Lattner9fba49a2007-08-24 05:35:26 +0000654 Value *NextVal;
Chris Lattner8360c612009-03-18 04:25:13 +0000655 if (const llvm::PointerType *PT =
656 dyn_cast<llvm::PointerType>(InVal->getType())) {
Chris Lattner8360c612009-03-18 04:25:13 +0000657 llvm::Constant *Inc =llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
658 if (!isa<llvm::FunctionType>(PT->getElementType())) {
659 NextVal = Builder.CreateGEP(InVal, Inc, "ptrincdec");
660 } else {
661 const llvm::Type *i8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
662 NextVal = Builder.CreateBitCast(InVal, i8Ty, "tmp");
663 NextVal = Builder.CreateGEP(NextVal, Inc, "ptrincdec");
664 NextVal = Builder.CreateBitCast(NextVal, InVal->getType());
665 }
Chris Lattner49083172009-02-11 07:40:06 +0000666 } else if (InVal->getType() == llvm::Type::Int1Ty && isInc) {
667 // Bool++ is an interesting case, due to promotion rules, we get:
668 // Bool++ -> Bool = Bool+1 -> Bool = (int)Bool+1 ->
669 // Bool = ((int)Bool+1) != 0
670 // An interesting aspect of this is that increment is always true.
671 // Decrement does not have this property.
672 NextVal = llvm::ConstantInt::getTrue();
Chris Lattner0dc11f62007-08-26 05:10:16 +0000673 } else {
674 // Add the inc/dec to the real part.
675 if (isa<llvm::IntegerType>(InVal->getType()))
676 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000677 else if (InVal->getType() == llvm::Type::FloatTy)
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000678 NextVal =
Chris Lattner70c38672008-04-20 00:45:53 +0000679 llvm::ConstantFP::get(llvm::APFloat(static_cast<float>(AmountVal)));
Chris Lattnerd54d1f22008-04-20 00:50:39 +0000680 else if (InVal->getType() == llvm::Type::DoubleTy)
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000681 NextVal =
Chris Lattner70c38672008-04-20 00:45:53 +0000682 llvm::ConstantFP::get(llvm::APFloat(static_cast<double>(AmountVal)));
Chris Lattnerd54d1f22008-04-20 00:50:39 +0000683 else {
684 llvm::APFloat F(static_cast<float>(AmountVal));
Dale Johannesen2461f612008-10-09 23:02:32 +0000685 bool ignored;
686 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
687 &ignored);
Chris Lattnerd54d1f22008-04-20 00:50:39 +0000688 NextVal = llvm::ConstantFP::get(F);
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000689 }
Chris Lattner0dc11f62007-08-26 05:10:16 +0000690 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
691 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000692
693 // Store the updated result through the lvalue.
Eli Friedman6a259872009-03-23 03:00:06 +0000694 if (LV.isBitfield())
695 CGF.EmitStoreThroughBitfieldLValue(RValue::get(NextVal), LV, ValTy,
696 &NextVal);
697 else
698 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV, ValTy);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000699
700 // If this is a postinc, return the value read from memory, otherwise use the
701 // updated value.
702 return isPre ? NextVal : InVal;
703}
704
705
706Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
707 Value *Op = Visit(E->getSubExpr());
708 return Builder.CreateNeg(Op, "neg");
709}
710
711Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
712 Value *Op = Visit(E->getSubExpr());
713 return Builder.CreateNot(Op, "neg");
714}
715
716Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
717 // Compare operand to zero.
718 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
719
720 // Invert value.
721 // TODO: Could dynamically modify easy computations here. For example, if
722 // the operand is an icmp ne, turn into icmp eq.
723 BoolVal = Builder.CreateNot(BoolVal, "lnot");
724
Anders Carlsson62943f32009-05-19 18:44:53 +0000725 // ZExt result to the expr type.
726 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000727}
728
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000729/// VisitSizeOfAlignOfExpr - Return the size or alignment of the type of
730/// argument of the sizeof expression as an integer.
731Value *
732ScalarExprEmitter::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000733 QualType TypeToSize = E->getTypeOfArgument();
Eli Friedman5a2c38f2009-01-24 22:19:05 +0000734 if (E->isSizeOf()) {
735 if (const VariableArrayType *VAT =
736 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
737 if (E->isArgumentType()) {
738 // sizeof(type) - make sure to emit the VLA size.
739 CGF.EmitVLASize(TypeToSize);
Eli Friedman04659bd2009-04-20 03:21:44 +0000740 } else {
741 // C99 6.5.3.4p2: If the argument is an expression of type
742 // VLA, it is evaluated.
743 CGF.EmitAnyExpr(E->getArgumentExpr());
Eli Friedman5a2c38f2009-01-24 22:19:05 +0000744 }
Anders Carlssond309f572009-01-30 16:41:04 +0000745
Anders Carlsson8f30de92009-02-05 19:43:10 +0000746 return CGF.GetVLASize(VAT);
Anders Carlsson6cb99b72008-12-21 03:33:21 +0000747 }
Anders Carlsson9be6aaf2008-12-12 07:38:43 +0000748 }
Eli Friedman5a2c38f2009-01-24 22:19:05 +0000749
750 // If this isn't sizeof(vla), the result must be constant; use the
751 // constant folding logic so we don't have to duplicate it here.
752 Expr::EvalResult Result;
753 E->Evaluate(Result, CGF.getContext());
754 return llvm::ConstantInt::get(Result.Val.getInt());
Chris Lattner9fba49a2007-08-24 05:35:26 +0000755}
756
Chris Lattner01211af2007-08-24 21:20:17 +0000757Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
758 Expr *Op = E->getSubExpr();
Chris Lattnerde0908b2008-04-04 16:54:41 +0000759 if (Op->getType()->isAnyComplexType())
Chris Lattner01211af2007-08-24 21:20:17 +0000760 return CGF.EmitComplexExpr(Op).first;
761 return Visit(Op);
762}
763Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
764 Expr *Op = E->getSubExpr();
Chris Lattnerde0908b2008-04-04 16:54:41 +0000765 if (Op->getType()->isAnyComplexType())
Chris Lattner01211af2007-08-24 21:20:17 +0000766 return CGF.EmitComplexExpr(Op).second;
Chris Lattnerdb8a6c92007-08-26 05:29:21 +0000767
768 // __imag on a scalar returns zero. Emit it the subexpr to ensure side
769 // effects are evaluated.
770 CGF.EmitScalarExpr(Op);
771 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner01211af2007-08-24 21:20:17 +0000772}
773
Anders Carlsson52774ad2008-01-29 15:56:48 +0000774Value *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E)
775{
Eli Friedman342d9432009-02-27 06:44:11 +0000776 Value* ResultAsPtr = EmitLValue(E->getSubExpr()).getAddress();
Eli Friedmanccffea92009-01-24 22:38:55 +0000777 const llvm::Type* ResultType = ConvertType(E->getType());
Eli Friedman342d9432009-02-27 06:44:11 +0000778 return Builder.CreatePtrToInt(ResultAsPtr, ResultType, "offsetof");
Anders Carlsson52774ad2008-01-29 15:56:48 +0000779}
Chris Lattner01211af2007-08-24 21:20:17 +0000780
Chris Lattner9fba49a2007-08-24 05:35:26 +0000781//===----------------------------------------------------------------------===//
782// Binary Operators
783//===----------------------------------------------------------------------===//
784
785BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
786 BinOpInfo Result;
787 Result.LHS = Visit(E->getLHS());
788 Result.RHS = Visit(E->getRHS());
Chris Lattner660e31d2007-08-24 21:00:35 +0000789 Result.Ty = E->getType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000790 Result.E = E;
791 return Result;
792}
793
Chris Lattner0d965302007-08-26 21:41:21 +0000794Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000795 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
796 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
797
798 BinOpInfo OpInfo;
799
Eli Friedman3cd92882009-03-28 01:22:36 +0000800 if (E->getComputationResultType()->isAnyComplexType()) {
Eli Friedman4a0073b2009-03-28 02:45:41 +0000801 // This needs to go through the complex expression emitter, but
Eli Friedman3cd92882009-03-28 01:22:36 +0000802 // it's a tad complicated to do that... I'm leaving it out for now.
803 // (Note that we do actually need the imaginary part of the RHS for
804 // multiplication and division.)
805 CGF.ErrorUnsupported(E, "complex compound assignment");
806 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
807 }
808
Mike Stump8d962262009-05-22 19:07:20 +0000809 // Emit the RHS first. __block variables need to have the rhs evaluated
810 // first, plus this should improve codegen a little.
811 OpInfo.RHS = Visit(E->getRHS());
812 OpInfo.Ty = E->getComputationResultType();
813 OpInfo.E = E;
Eli Friedman3cd92882009-03-28 01:22:36 +0000814 // Load/convert the LHS.
Chris Lattner660e31d2007-08-24 21:00:35 +0000815 LValue LHSLV = EmitLValue(E->getLHS());
816 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Eli Friedman3cd92882009-03-28 01:22:36 +0000817 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
818 E->getComputationLHSType());
Chris Lattner660e31d2007-08-24 21:00:35 +0000819
820 // Expand the binary operator.
821 Value *Result = (this->*Func)(OpInfo);
822
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000823 // Convert the result back to the LHS type.
Eli Friedman3cd92882009-03-28 01:22:36 +0000824 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
825
Daniel Dunbar2668dd12008-11-19 09:36:46 +0000826 // Store the result value into the LHS lvalue. Bit-fields are
Daniel Dunbar2710fc92008-11-19 11:54:05 +0000827 // handled specially because the result is altered by the store,
828 // i.e., [C99 6.5.16p1] 'An assignment expression has the value of
829 // the left operand after the assignment...'.
Eli Friedmanf9b930c2008-05-25 14:13:57 +0000830 if (LHSLV.isBitfield())
Daniel Dunbar2668dd12008-11-19 09:36:46 +0000831 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy,
832 &Result);
833 else
834 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy);
835
Chris Lattner660e31d2007-08-24 21:00:35 +0000836 return Result;
837}
838
839
Chris Lattner9fba49a2007-08-24 05:35:26 +0000840Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Nate Begemanaade3bf2007-12-30 01:28:16 +0000841 if (Ops.LHS->getType()->isFPOrFPVector())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000842 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner660e31d2007-08-24 21:00:35 +0000843 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000844 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
845 else
846 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
847}
848
849Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
850 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner660e31d2007-08-24 21:00:35 +0000851 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000852 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
853 else
854 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
855}
856
Mike Stumpdb789912009-04-01 20:28:16 +0000857Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
858 unsigned IID;
859 unsigned OpID = 0;
Mike Stump0f595bb2009-04-02 01:03:55 +0000860
Mike Stumpf71b7742009-04-02 18:15:54 +0000861 switch (Ops.E->getOpcode()) {
862 case BinaryOperator::Add:
863 case BinaryOperator::AddAssign:
864 OpID = 1;
865 IID = llvm::Intrinsic::sadd_with_overflow;
866 break;
867 case BinaryOperator::Sub:
868 case BinaryOperator::SubAssign:
869 OpID = 2;
870 IID = llvm::Intrinsic::ssub_with_overflow;
871 break;
872 case BinaryOperator::Mul:
873 case BinaryOperator::MulAssign:
874 OpID = 3;
875 IID = llvm::Intrinsic::smul_with_overflow;
876 break;
877 default:
878 assert(false && "Unsupported operation for overflow detection");
Daniel Dunbar96e909b2009-04-08 16:23:09 +0000879 IID = 0;
Mike Stumpdb789912009-04-01 20:28:16 +0000880 }
Mike Stumpf71b7742009-04-02 18:15:54 +0000881 OpID <<= 1;
882 OpID |= 1;
883
Mike Stumpdb789912009-04-01 20:28:16 +0000884 const llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
885
886 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, &opTy, 1);
887
888 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
889 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
890 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
891
892 // Branch in case of overflow.
893 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
894 llvm::BasicBlock *overflowBB =
895 CGF.createBasicBlock("overflow", CGF.CurFn);
896 llvm::BasicBlock *continueBB =
897 CGF.createBasicBlock("overflow.continue", CGF.CurFn);
898
899 Builder.CreateCondBr(overflow, overflowBB, continueBB);
900
901 // Handle overflow
902
903 Builder.SetInsertPoint(overflowBB);
904
905 // Handler is:
906 // long long *__overflow_handler)(long long a, long long b, char op,
907 // char width)
908 std::vector<const llvm::Type*> handerArgTypes;
909 handerArgTypes.push_back(llvm::Type::Int64Ty);
910 handerArgTypes.push_back(llvm::Type::Int64Ty);
911 handerArgTypes.push_back(llvm::Type::Int8Ty);
912 handerArgTypes.push_back(llvm::Type::Int8Ty);
913 llvm::FunctionType *handlerTy = llvm::FunctionType::get(llvm::Type::Int64Ty,
914 handerArgTypes, false);
915 llvm::Value *handlerFunction =
916 CGF.CGM.getModule().getOrInsertGlobal("__overflow_handler",
917 llvm::PointerType::getUnqual(handlerTy));
918 handlerFunction = Builder.CreateLoad(handlerFunction);
919
920 llvm::Value *handlerResult = Builder.CreateCall4(handlerFunction,
921 Builder.CreateSExt(Ops.LHS, llvm::Type::Int64Ty),
922 Builder.CreateSExt(Ops.RHS, llvm::Type::Int64Ty),
923 llvm::ConstantInt::get(llvm::Type::Int8Ty, OpID),
924 llvm::ConstantInt::get(llvm::Type::Int8Ty,
925 cast<llvm::IntegerType>(opTy)->getBitWidth()));
926
927 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
928
929 Builder.CreateBr(continueBB);
930
931 // Set up the continuation
932 Builder.SetInsertPoint(continueBB);
933 // Get the correct result
934 llvm::PHINode *phi = Builder.CreatePHI(opTy);
935 phi->reserveOperandSpace(2);
936 phi->addIncoming(result, initialBB);
937 phi->addIncoming(handlerResult, overflowBB);
938
939 return phi;
940}
Chris Lattner9fba49a2007-08-24 05:35:26 +0000941
942Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Mike Stumpdb789912009-04-01 20:28:16 +0000943 if (!Ops.Ty->isPointerType()) {
Mike Stumpf71b7742009-04-02 18:15:54 +0000944 if (CGF.getContext().getLangOptions().OverflowChecking
945 && Ops.Ty->isSignedIntegerType())
Mike Stumpdb789912009-04-01 20:28:16 +0000946 return EmitOverflowCheckedBinOp(Ops);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000947 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Mike Stumpdb789912009-04-01 20:28:16 +0000948 }
Eli Friedman4a0073b2009-03-28 02:45:41 +0000949
950 if (Ops.Ty->getAsPointerType()->isVariableArrayType()) {
951 // The amount of the addition needs to account for the VLA size
952 CGF.ErrorUnsupported(Ops.E, "VLA pointer addition");
953 }
Chris Lattner17c0cb02008-01-03 06:36:51 +0000954 Value *Ptr, *Idx;
955 Expr *IdxExp;
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +0000956 const PointerType *PT;
957 if ((PT = Ops.E->getLHS()->getType()->getAsPointerType())) {
Chris Lattner17c0cb02008-01-03 06:36:51 +0000958 Ptr = Ops.LHS;
959 Idx = Ops.RHS;
960 IdxExp = Ops.E->getRHS();
961 } else { // int + pointer
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +0000962 PT = Ops.E->getRHS()->getType()->getAsPointerType();
963 assert(PT && "Invalid add expr");
Chris Lattner17c0cb02008-01-03 06:36:51 +0000964 Ptr = Ops.RHS;
965 Idx = Ops.LHS;
966 IdxExp = Ops.E->getLHS();
967 }
968
969 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
Sanjiv Guptacee8fea2009-04-24 02:40:57 +0000970 if (Width < CGF.LLVMPointerWidth) {
Chris Lattner17c0cb02008-01-03 06:36:51 +0000971 // Zero or sign extend the pointer value based on whether the index is
972 // signed or not.
Sanjiv Guptacee8fea2009-04-24 02:40:57 +0000973 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
Chris Lattnerc154ac12008-07-26 22:37:01 +0000974 if (IdxExp->getType()->isSignedIntegerType())
Chris Lattner17c0cb02008-01-03 06:36:51 +0000975 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
976 else
977 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
978 }
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +0000979
Daniel Dunbar6864c0d2009-04-25 05:08:32 +0000980 const QualType ElementType = PT->getPointeeType();
981 // Handle interface types, which are not represented with a concrete
982 // type.
983 if (const ObjCInterfaceType *OIT = dyn_cast<ObjCInterfaceType>(ElementType)) {
984 llvm::Value *InterfaceSize =
985 llvm::ConstantInt::get(Idx->getType(),
986 CGF.getContext().getTypeSize(OIT) / 8);
987 Idx = Builder.CreateMul(Idx, InterfaceSize);
988 const llvm::Type *i8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
989 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
990 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
991 return Builder.CreateBitCast(Res, Ptr->getType());
992 }
993
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +0000994 // Explicitly handle GNU void* and function pointer arithmetic
995 // extensions. The GNU void* casts amount to no-ops since our void*
996 // type is i8*, but this is future proof.
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +0000997 if (ElementType->isVoidType() || ElementType->isFunctionType()) {
998 const llvm::Type *i8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
999 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
Daniel Dunbar6864c0d2009-04-25 05:08:32 +00001000 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001001 return Builder.CreateBitCast(Res, Ptr->getType());
1002 }
Chris Lattner17c0cb02008-01-03 06:36:51 +00001003
1004 return Builder.CreateGEP(Ptr, Idx, "add.ptr");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001005}
1006
1007Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
Mike Stumpdb789912009-04-01 20:28:16 +00001008 if (!isa<llvm::PointerType>(Ops.LHS->getType())) {
Mike Stumpf71b7742009-04-02 18:15:54 +00001009 if (CGF.getContext().getLangOptions().OverflowChecking
1010 && Ops.Ty->isSignedIntegerType())
Mike Stumpdb789912009-04-01 20:28:16 +00001011 return EmitOverflowCheckedBinOp(Ops);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001012 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
Mike Stumpdb789912009-04-01 20:28:16 +00001013 }
Chris Lattner660e31d2007-08-24 21:00:35 +00001014
Eli Friedman4a0073b2009-03-28 02:45:41 +00001015 if (Ops.E->getLHS()->getType()->getAsPointerType()->isVariableArrayType()) {
1016 // The amount of the addition needs to account for the VLA size for
1017 // ptr-int
1018 // The amount of the division needs to account for the VLA size for
1019 // ptr-ptr.
1020 CGF.ErrorUnsupported(Ops.E, "VLA pointer subtraction");
1021 }
1022
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001023 const QualType LHSType = Ops.E->getLHS()->getType();
1024 const QualType LHSElementType = LHSType->getAsPointerType()->getPointeeType();
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001025 if (!isa<llvm::PointerType>(Ops.RHS->getType())) {
1026 // pointer - int
1027 Value *Idx = Ops.RHS;
1028 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
Sanjiv Guptacee8fea2009-04-24 02:40:57 +00001029 if (Width < CGF.LLVMPointerWidth) {
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001030 // Zero or sign extend the pointer value based on whether the index is
1031 // signed or not.
Sanjiv Guptacee8fea2009-04-24 02:40:57 +00001032 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001033 if (Ops.E->getRHS()->getType()->isSignedIntegerType())
1034 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1035 else
1036 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1037 }
1038 Idx = Builder.CreateNeg(Idx, "sub.ptr.neg");
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001039
Daniel Dunbar6864c0d2009-04-25 05:08:32 +00001040 // Handle interface types, which are not represented with a concrete
1041 // type.
1042 if (const ObjCInterfaceType *OIT =
1043 dyn_cast<ObjCInterfaceType>(LHSElementType)) {
1044 llvm::Value *InterfaceSize =
1045 llvm::ConstantInt::get(Idx->getType(),
1046 CGF.getContext().getTypeSize(OIT) / 8);
1047 Idx = Builder.CreateMul(Idx, InterfaceSize);
1048 const llvm::Type *i8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
1049 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1050 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "add.ptr");
1051 return Builder.CreateBitCast(Res, Ops.LHS->getType());
1052 }
1053
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001054 // Explicitly handle GNU void* and function pointer arithmetic
1055 // extensions. The GNU void* casts amount to no-ops since our
1056 // void* type is i8*, but this is future proof.
1057 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
1058 const llvm::Type *i8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
1059 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1060 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "sub.ptr");
1061 return Builder.CreateBitCast(Res, Ops.LHS->getType());
1062 }
1063
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001064 return Builder.CreateGEP(Ops.LHS, Idx, "sub.ptr");
Daniel Dunbar0aac9f62008-08-05 00:47:03 +00001065 } else {
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001066 // pointer - pointer
1067 Value *LHS = Ops.LHS;
1068 Value *RHS = Ops.RHS;
Chris Lattner660e31d2007-08-24 21:00:35 +00001069
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001070 uint64_t ElementSize;
Daniel Dunbar0aac9f62008-08-05 00:47:03 +00001071
Chris Lattner6d2e3492009-02-11 07:21:43 +00001072 // Handle GCC extension for pointer arithmetic on void* and function pointer
1073 // types.
1074 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001075 ElementSize = 1;
1076 } else {
1077 ElementSize = CGF.getContext().getTypeSize(LHSElementType) / 8;
1078 }
1079
1080 const llvm::Type *ResultType = ConvertType(Ops.Ty);
1081 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
1082 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1083 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
1084
Chris Lattner6d2e3492009-02-11 07:21:43 +00001085 // Optimize out the shift for element size of 1.
1086 if (ElementSize == 1)
1087 return BytesBetween;
1088
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001089 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
1090 // remainder. As such, we handle common power-of-two cases here to generate
1091 // better code. See PR2247.
1092 if (llvm::isPowerOf2_64(ElementSize)) {
1093 Value *ShAmt =
1094 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
1095 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
1096 }
1097
1098 // Otherwise, do a full sdiv.
1099 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
1100 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001101 }
Chris Lattner9fba49a2007-08-24 05:35:26 +00001102}
1103
1104Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
1105 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1106 // RHS to the same size as the LHS.
1107 Value *RHS = Ops.RHS;
1108 if (Ops.LHS->getType() != RHS->getType())
1109 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
1110
1111 return Builder.CreateShl(Ops.LHS, RHS, "shl");
1112}
1113
1114Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
1115 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1116 // RHS to the same size as the LHS.
1117 Value *RHS = Ops.RHS;
1118 if (Ops.LHS->getType() != RHS->getType())
1119 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
1120
Chris Lattner660e31d2007-08-24 21:00:35 +00001121 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +00001122 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
1123 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
1124}
1125
1126Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
1127 unsigned SICmpOpc, unsigned FCmpOpc) {
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001128 Value *Result;
Chris Lattner9fba49a2007-08-24 05:35:26 +00001129 QualType LHSTy = E->getLHS()->getType();
Nate Begeman1591bc52008-07-25 20:16:05 +00001130 if (!LHSTy->isAnyComplexType() && !LHSTy->isVectorType()) {
Chris Lattner9fba49a2007-08-24 05:35:26 +00001131 Value *LHS = Visit(E->getLHS());
1132 Value *RHS = Visit(E->getRHS());
1133
1134 if (LHS->getType()->isFloatingPoint()) {
Nate Begeman1591bc52008-07-25 20:16:05 +00001135 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +00001136 LHS, RHS, "cmp");
Eli Friedman850ea372008-05-29 15:09:15 +00001137 } else if (LHSTy->isSignedIntegerType()) {
1138 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +00001139 LHS, RHS, "cmp");
1140 } else {
Eli Friedman850ea372008-05-29 15:09:15 +00001141 // Unsigned integers and pointers.
1142 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +00001143 LHS, RHS, "cmp");
1144 }
Nate Begeman1591bc52008-07-25 20:16:05 +00001145 } else if (LHSTy->isVectorType()) {
1146 Value *LHS = Visit(E->getLHS());
1147 Value *RHS = Visit(E->getRHS());
1148
1149 if (LHS->getType()->isFPOrFPVector()) {
1150 Result = Builder.CreateVFCmp((llvm::CmpInst::Predicate)FCmpOpc,
1151 LHS, RHS, "cmp");
1152 } else if (LHSTy->isUnsignedIntegerType()) {
1153 Result = Builder.CreateVICmp((llvm::CmpInst::Predicate)UICmpOpc,
1154 LHS, RHS, "cmp");
1155 } else {
1156 // Signed integers and pointers.
1157 Result = Builder.CreateVICmp((llvm::CmpInst::Predicate)SICmpOpc,
1158 LHS, RHS, "cmp");
1159 }
1160 return Result;
Chris Lattner9fba49a2007-08-24 05:35:26 +00001161 } else {
1162 // Complex Comparison: can only be an equality comparison.
1163 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
1164 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
1165
Chris Lattnerc154ac12008-07-26 22:37:01 +00001166 QualType CETy = LHSTy->getAsComplexType()->getElementType();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001167
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001168 Value *ResultR, *ResultI;
Chris Lattner9fba49a2007-08-24 05:35:26 +00001169 if (CETy->isRealFloatingType()) {
1170 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1171 LHS.first, RHS.first, "cmp.r");
1172 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1173 LHS.second, RHS.second, "cmp.i");
1174 } else {
1175 // Complex comparisons can only be equality comparisons. As such, signed
1176 // and unsigned opcodes are the same.
1177 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1178 LHS.first, RHS.first, "cmp.r");
1179 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1180 LHS.second, RHS.second, "cmp.i");
1181 }
1182
1183 if (E->getOpcode() == BinaryOperator::EQ) {
1184 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1185 } else {
1186 assert(E->getOpcode() == BinaryOperator::NE &&
1187 "Complex comparison other than == or != ?");
1188 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1189 }
1190 }
Nuno Lopes92577002009-01-11 23:22:37 +00001191
1192 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001193}
1194
1195Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Mike Stump68df15c2009-05-21 21:05:15 +00001196 // __block variables need to have the rhs evaluated first, plus
1197 // this should improve codegen just a little.
Chris Lattner9fba49a2007-08-24 05:35:26 +00001198 Value *RHS = Visit(E->getRHS());
Mike Stump68df15c2009-05-21 21:05:15 +00001199 LValue LHS = EmitLValue(E->getLHS());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001200
Daniel Dunbar2668dd12008-11-19 09:36:46 +00001201 // Store the value into the LHS. Bit-fields are handled specially
Daniel Dunbar2710fc92008-11-19 11:54:05 +00001202 // because the result is altered by the store, i.e., [C99 6.5.16p1]
1203 // 'An assignment expression has the value of the left operand after
Eli Friedman4a0073b2009-03-28 02:45:41 +00001204 // the assignment...'.
Eli Friedmanf9b930c2008-05-25 14:13:57 +00001205 if (LHS.isBitfield())
Daniel Dunbar2668dd12008-11-19 09:36:46 +00001206 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType(),
1207 &RHS);
1208 else
1209 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
Daniel Dunbare6c31752008-08-29 08:11:39 +00001210
Chris Lattner9fba49a2007-08-24 05:35:26 +00001211 // Return the RHS.
1212 return RHS;
1213}
1214
1215Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
Chris Lattner715c2a72008-11-12 08:26:50 +00001216 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
1217 // If we have 1 && X, just emit X without inserting the control flow.
1218 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1219 if (Cond == 1) { // If we have 1 && X, just emit X.
Chris Lattner3f73d0d2008-11-11 07:41:27 +00001220 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1221 // ZExt result to int.
1222 return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "land.ext");
1223 }
Chris Lattner715c2a72008-11-12 08:26:50 +00001224
1225 // 0 && RHS: If it is safe, just elide the RHS, and return 0.
1226 if (!CGF.ContainsLabel(E->getRHS()))
1227 return llvm::Constant::getNullValue(CGF.LLVMIntTy);
Chris Lattner3f73d0d2008-11-11 07:41:27 +00001228 }
1229
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +00001230 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
1231 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
Chris Lattner715c2a72008-11-12 08:26:50 +00001232
Chris Lattner7f80bb32008-11-12 08:38:24 +00001233 // Branch on the LHS first. If it is false, go to the failure (cont) block.
1234 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
1235
1236 // Any edges into the ContBlock are now from an (indeterminate number of)
1237 // edges from this first condition. All of these values will be false. Start
1238 // setting up the PHI node in the Cont Block for this.
1239 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::Int1Ty, "", ContBlock);
1240 PN->reserveOperandSpace(2); // Normal case, two inputs.
1241 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1242 PI != PE; ++PI)
1243 PN->addIncoming(llvm::ConstantInt::getFalse(), *PI);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001244
1245 CGF.EmitBlock(RHSBlock);
1246 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1247
1248 // Reaquire the RHS block, as there may be subblocks inserted.
1249 RHSBlock = Builder.GetInsertBlock();
Chris Lattner7f80bb32008-11-12 08:38:24 +00001250
1251 // Emit an unconditional branch from this block to ContBlock. Insert an entry
1252 // into the phi node for the edge with the value of RHSCond.
Chris Lattner9fba49a2007-08-24 05:35:26 +00001253 CGF.EmitBlock(ContBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001254 PN->addIncoming(RHSCond, RHSBlock);
1255
1256 // ZExt result to int.
1257 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
1258}
1259
1260Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
Chris Lattner715c2a72008-11-12 08:26:50 +00001261 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
1262 // If we have 0 || X, just emit X without inserting the control flow.
1263 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1264 if (Cond == -1) { // If we have 0 || X, just emit X.
Chris Lattner3f73d0d2008-11-11 07:41:27 +00001265 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1266 // ZExt result to int.
1267 return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "lor.ext");
1268 }
Chris Lattner715c2a72008-11-12 08:26:50 +00001269
Eli Friedmanea137cd2008-12-02 16:02:46 +00001270 // 1 || RHS: If it is safe, just elide the RHS, and return 1.
Chris Lattner715c2a72008-11-12 08:26:50 +00001271 if (!CGF.ContainsLabel(E->getRHS()))
Eli Friedmanea137cd2008-12-02 16:02:46 +00001272 return llvm::ConstantInt::get(CGF.LLVMIntTy, 1);
Chris Lattner3f73d0d2008-11-11 07:41:27 +00001273 }
1274
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +00001275 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
1276 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001277
Chris Lattner7f80bb32008-11-12 08:38:24 +00001278 // Branch on the LHS first. If it is true, go to the success (cont) block.
1279 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
1280
1281 // Any edges into the ContBlock are now from an (indeterminate number of)
1282 // edges from this first condition. All of these values will be true. Start
1283 // setting up the PHI node in the Cont Block for this.
1284 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::Int1Ty, "", ContBlock);
1285 PN->reserveOperandSpace(2); // Normal case, two inputs.
1286 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1287 PI != PE; ++PI)
1288 PN->addIncoming(llvm::ConstantInt::getTrue(), *PI);
1289
1290 // Emit the RHS condition as a bool value.
Chris Lattner9fba49a2007-08-24 05:35:26 +00001291 CGF.EmitBlock(RHSBlock);
1292 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1293
1294 // Reaquire the RHS block, as there may be subblocks inserted.
1295 RHSBlock = Builder.GetInsertBlock();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001296
Chris Lattner7f80bb32008-11-12 08:38:24 +00001297 // Emit an unconditional branch from this block to ContBlock. Insert an entry
1298 // into the phi node for the edge with the value of RHSCond.
1299 CGF.EmitBlock(ContBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001300 PN->addIncoming(RHSCond, RHSBlock);
1301
1302 // ZExt result to int.
1303 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
1304}
1305
1306Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
1307 CGF.EmitStmt(E->getLHS());
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +00001308 CGF.EnsureInsertPoint();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001309 return Visit(E->getRHS());
1310}
1311
1312//===----------------------------------------------------------------------===//
1313// Other Operators
1314//===----------------------------------------------------------------------===//
1315
Chris Lattner504a5282008-11-12 08:55:54 +00001316/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
1317/// expression is cheap enough and side-effect-free enough to evaluate
1318/// unconditionally instead of conditionally. This is used to convert control
1319/// flow into selects in some cases.
1320static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E) {
1321 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
1322 return isCheapEnoughToEvaluateUnconditionally(PE->getSubExpr());
1323
1324 // TODO: Allow anything we can constant fold to an integer or fp constant.
1325 if (isa<IntegerLiteral>(E) || isa<CharacterLiteral>(E) ||
1326 isa<FloatingLiteral>(E))
1327 return true;
1328
1329 // Non-volatile automatic variables too, to get "cond ? X : Y" where
1330 // X and Y are local variables.
1331 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1332 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1333 if (VD->hasLocalStorage() && !VD->getType().isVolatileQualified())
1334 return true;
1335
1336 return false;
1337}
1338
1339
Chris Lattner9fba49a2007-08-24 05:35:26 +00001340Value *ScalarExprEmitter::
1341VisitConditionalOperator(const ConditionalOperator *E) {
Chris Lattner3d6606b2008-11-12 08:04:58 +00001342 // If the condition constant folds and can be elided, try to avoid emitting
1343 // the condition and the dead arm.
1344 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getCond())){
Chris Lattner044bffc2008-11-11 18:56:45 +00001345 Expr *Live = E->getLHS(), *Dead = E->getRHS();
Chris Lattner3d6606b2008-11-12 08:04:58 +00001346 if (Cond == -1)
Chris Lattner044bffc2008-11-11 18:56:45 +00001347 std::swap(Live, Dead);
Chris Lattner3d6606b2008-11-12 08:04:58 +00001348
1349 // If the dead side doesn't have labels we need, and if the Live side isn't
1350 // the gnu missing ?: extension (which we could handle, but don't bother
1351 // to), just emit the Live part.
1352 if ((!Dead || !CGF.ContainsLabel(Dead)) && // No labels in dead part
1353 Live) // Live part isn't missing.
1354 return Visit(Live);
Chris Lattner044bffc2008-11-11 18:56:45 +00001355 }
1356
Chris Lattner504a5282008-11-12 08:55:54 +00001357
1358 // If this is a really simple expression (like x ? 4 : 5), emit this as a
1359 // select instead of as control flow. We can only do this if it is cheap and
Chris Lattner1f11af22008-11-16 06:16:27 +00001360 // safe to evaluate the LHS and RHS unconditionally.
Chris Lattner504a5282008-11-12 08:55:54 +00001361 if (E->getLHS() && isCheapEnoughToEvaluateUnconditionally(E->getLHS()) &&
1362 isCheapEnoughToEvaluateUnconditionally(E->getRHS())) {
1363 llvm::Value *CondV = CGF.EvaluateExprAsBool(E->getCond());
1364 llvm::Value *LHS = Visit(E->getLHS());
1365 llvm::Value *RHS = Visit(E->getRHS());
1366 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
1367 }
1368
1369
Daniel Dunbarb23e9922008-11-12 10:13:37 +00001370 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
1371 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +00001372 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
Chris Lattner67e22462008-11-12 08:08:13 +00001373 Value *CondVal = 0;
Chris Lattner3d6606b2008-11-12 08:04:58 +00001374
Chris Lattner86031712009-02-13 23:35:32 +00001375 // If we don't have the GNU missing condition extension, emit a branch on
1376 // bool the normal way.
1377 if (E->getLHS()) {
1378 // Otherwise, just use EmitBranchOnBoolExpr to get small and simple code for
1379 // the branch on bool.
1380 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
1381 } else {
1382 // Otherwise, for the ?: extension, evaluate the conditional and then
1383 // convert it to bool the hard way. We do this explicitly because we need
1384 // the unconverted value for the missing middle value of the ?:.
Chris Lattner67e22462008-11-12 08:08:13 +00001385 CondVal = CGF.EmitScalarExpr(E->getCond());
Chris Lattner86031712009-02-13 23:35:32 +00001386
1387 // In some cases, EmitScalarConversion will delete the "CondVal" expression
1388 // if there are no extra uses (an optimization). Inhibit this by making an
1389 // extra dead use, because we're going to add a use of CondVal later. We
1390 // don't use the builder for this, because we don't want it to get optimized
1391 // away. This leaves dead code, but the ?: extension isn't common.
1392 new llvm::BitCastInst(CondVal, CondVal->getType(), "dummy?:holder",
1393 Builder.GetInsertBlock());
1394
Chris Lattner67e22462008-11-12 08:08:13 +00001395 Value *CondBoolVal =
1396 CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
1397 CGF.getContext().BoolTy);
1398 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
Chris Lattner67e22462008-11-12 08:08:13 +00001399 }
Chris Lattner9fba49a2007-08-24 05:35:26 +00001400
1401 CGF.EmitBlock(LHSBlock);
1402
1403 // Handle the GNU extension for missing LHS.
Chris Lattner98a425c2007-11-26 01:40:58 +00001404 Value *LHS;
1405 if (E->getLHS())
Eli Friedmance8d7032008-05-16 20:38:39 +00001406 LHS = Visit(E->getLHS());
Chris Lattner98a425c2007-11-26 01:40:58 +00001407 else // Perform promotions, to handle cases like "short ?: int"
1408 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
1409
Chris Lattner9fba49a2007-08-24 05:35:26 +00001410 LHSBlock = Builder.GetInsertBlock();
Daniel Dunbar5276caa2008-11-11 09:41:28 +00001411 CGF.EmitBranch(ContBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001412
1413 CGF.EmitBlock(RHSBlock);
1414
Eli Friedmance8d7032008-05-16 20:38:39 +00001415 Value *RHS = Visit(E->getRHS());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001416 RHSBlock = Builder.GetInsertBlock();
Daniel Dunbar5276caa2008-11-11 09:41:28 +00001417 CGF.EmitBranch(ContBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001418
1419 CGF.EmitBlock(ContBlock);
1420
Nuno Lopesb62ff242008-06-04 19:15:45 +00001421 if (!LHS || !RHS) {
Chris Lattner307da022007-11-30 17:56:23 +00001422 assert(E->getType()->isVoidType() && "Non-void value should have a value");
1423 return 0;
1424 }
1425
Chris Lattner9fba49a2007-08-24 05:35:26 +00001426 // Create a PHI node for the real part.
1427 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
1428 PN->reserveOperandSpace(2);
1429 PN->addIncoming(LHS, LHSBlock);
1430 PN->addIncoming(RHS, RHSBlock);
1431 return PN;
1432}
1433
1434Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Eli Friedmand540c112009-03-04 05:52:32 +00001435 return Visit(E->getChosenSubExpr(CGF.getContext()));
Chris Lattner9fba49a2007-08-24 05:35:26 +00001436}
1437
Chris Lattner307da022007-11-30 17:56:23 +00001438Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Eli Friedman8f5e8782009-01-20 17:46:04 +00001439 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlsson285611e2008-11-04 05:30:00 +00001440 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
1441
1442 // If EmitVAArg fails, we fall back to the LLVM instruction.
1443 if (!ArgPtr)
1444 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
1445
Anders Carlsson285611e2008-11-04 05:30:00 +00001446 return Builder.CreateLoad(ArgPtr);
Anders Carlsson36760332007-10-15 20:28:48 +00001447}
1448
Mike Stump4eb81dc2009-02-12 18:29:15 +00001449Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *BE) {
Mike Stump1fa52fe2009-03-07 02:35:30 +00001450 return CGF.BuildBlockLiteralTmp(BE);
Mike Stump4eb81dc2009-02-12 18:29:15 +00001451}
1452
Chris Lattner9fba49a2007-08-24 05:35:26 +00001453//===----------------------------------------------------------------------===//
1454// Entry Point into this File
1455//===----------------------------------------------------------------------===//
1456
1457/// EmitComplexExpr - Emit the computation of the specified expression of
1458/// complex type, ignoring the result.
1459Value *CodeGenFunction::EmitScalarExpr(const Expr *E) {
1460 assert(E && !hasAggregateLLVMType(E->getType()) &&
1461 "Invalid scalar expression to emit");
1462
1463 return ScalarExprEmitter(*this).Visit(const_cast<Expr*>(E));
1464}
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001465
1466/// EmitScalarConversion - Emit a conversion from the specified type to the
1467/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001468Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
1469 QualType DstTy) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001470 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
1471 "Invalid scalar expression to emit");
1472 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
1473}
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001474
1475/// EmitComplexToScalarConversion - Emit a conversion from the specified
1476/// complex type to the specified destination type, where the destination
1477/// type is an LLVM scalar type.
1478Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
1479 QualType SrcTy,
1480 QualType DstTy) {
Chris Lattnerde0908b2008-04-04 16:54:41 +00001481 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001482 "Invalid complex -> scalar conversion");
1483 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
1484 DstTy);
1485}
Anders Carlssona9234fe2007-12-10 19:35:18 +00001486
1487Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) {
1488 assert(V1->getType() == V2->getType() &&
1489 "Vector operands must be of the same type");
Anders Carlssona9234fe2007-12-10 19:35:18 +00001490 unsigned NumElements =
1491 cast<llvm::VectorType>(V1->getType())->getNumElements();
1492
1493 va_list va;
1494 va_start(va, V2);
1495
1496 llvm::SmallVector<llvm::Constant*, 16> Args;
Anders Carlssona9234fe2007-12-10 19:35:18 +00001497 for (unsigned i = 0; i < NumElements; i++) {
1498 int n = va_arg(va, int);
Anders Carlssona9234fe2007-12-10 19:35:18 +00001499 assert(n >= 0 && n < (int)NumElements * 2 &&
1500 "Vector shuffle index out of bounds!");
Anders Carlssona9234fe2007-12-10 19:35:18 +00001501 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, n));
1502 }
1503
1504 const char *Name = va_arg(va, const char *);
1505 va_end(va);
1506
1507 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
1508
1509 return Builder.CreateShuffleVector(V1, V2, Mask, Name);
1510}
1511
Anders Carlsson68b8be92007-12-15 21:23:30 +00001512llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals,
Chris Lattnera23eb7b2008-07-26 20:15:14 +00001513 unsigned NumVals, bool isSplat) {
Anders Carlsson68b8be92007-12-15 21:23:30 +00001514 llvm::Value *Vec
Chris Lattnera23eb7b2008-07-26 20:15:14 +00001515 = llvm::UndefValue::get(llvm::VectorType::get(Vals[0]->getType(), NumVals));
Anders Carlsson68b8be92007-12-15 21:23:30 +00001516
Chris Lattnera23eb7b2008-07-26 20:15:14 +00001517 for (unsigned i = 0, e = NumVals; i != e; ++i) {
Nate Begemanec2d1062007-12-30 02:59:45 +00001518 llvm::Value *Val = isSplat ? Vals[0] : Vals[i];
Anders Carlsson68b8be92007-12-15 21:23:30 +00001519 llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
Nate Begemanec2d1062007-12-30 02:59:45 +00001520 Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp");
Anders Carlsson68b8be92007-12-15 21:23:30 +00001521 }
1522
1523 return Vec;
1524}