blob: 2bd39c1bd6b9c841730e2a939b1772c465cd5c0a [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"
17#include "clang/AST/StmtVisitor.h"
Chris Lattnerd54d1f22008-04-20 00:50:39 +000018#include "clang/Basic/TargetInfo.h"
Chris Lattner9fba49a2007-08-24 05:35:26 +000019#include "llvm/Constants.h"
20#include "llvm/Function.h"
Anders Carlsson36f07d82007-10-29 05:01:08 +000021#include "llvm/GlobalVariable.h"
Anders Carlsson36760332007-10-15 20:28:48 +000022#include "llvm/Intrinsics.h"
Chris Lattner9fba49a2007-08-24 05:35:26 +000023#include "llvm/Support/Compiler.h"
Chris Lattnerc2126682008-01-03 07:05:49 +000024#include <cstdarg>
Ted Kremenek03cf4df2007-12-10 23:44:32 +000025
Chris Lattner9fba49a2007-08-24 05:35:26 +000026using namespace clang;
27using namespace CodeGen;
28using llvm::Value;
29
30//===----------------------------------------------------------------------===//
31// Scalar Expression Emitter
32//===----------------------------------------------------------------------===//
33
34struct BinOpInfo {
35 Value *LHS;
36 Value *RHS;
Chris Lattner660e31d2007-08-24 21:00:35 +000037 QualType Ty; // Computation Type.
Chris Lattner9fba49a2007-08-24 05:35:26 +000038 const BinaryOperator *E;
39};
40
41namespace {
42class VISIBILITY_HIDDEN ScalarExprEmitter
43 : public StmtVisitor<ScalarExprEmitter, Value*> {
44 CodeGenFunction &CGF;
Chris Lattnerfaf23db2008-08-08 19:57:58 +000045 llvm::IRBuilder<> &Builder;
Chris Lattnercbfb5512008-03-01 08:45:05 +000046 CGObjCRuntime *Runtime;
47
Chris Lattner9fba49a2007-08-24 05:35:26 +000048public:
49
Chris Lattnercbfb5512008-03-01 08:45:05 +000050 ScalarExprEmitter(CodeGenFunction &cgf) : CGF(cgf),
51 Builder(CGF.Builder),
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000052 Runtime(0) {
53 if (CGF.CGM.hasObjCRuntime())
54 Runtime = &CGF.CGM.getObjCRuntime();
Chris Lattner9fba49a2007-08-24 05:35:26 +000055 }
Chris Lattner9fba49a2007-08-24 05:35:26 +000056
57 //===--------------------------------------------------------------------===//
58 // Utilities
59 //===--------------------------------------------------------------------===//
60
61 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
62 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
63
64 Value *EmitLoadOfLValue(LValue LV, QualType T) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +000065 return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +000066 }
67
68 /// EmitLoadOfLValue - Given an expression with complex type that represents a
69 /// value l-value, this method emits the address of the l-value, then loads
70 /// and returns the result.
71 Value *EmitLoadOfLValue(const Expr *E) {
72 // FIXME: Volatile
73 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);
Chris Lattner4e05d1e2007-08-26 06:48:56 +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 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000115 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
116 return llvm::ConstantInt::get(ConvertType(E->getType()),
Steve Naroff85f0dc52007-10-15 20:41:53 +0000117 CGF.getContext().typesAreCompatible(
118 E->getArgType1(), E->getArgType2()));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000119 }
120 Value *VisitSizeOfAlignOfTypeExpr(const SizeOfAlignOfTypeExpr *E) {
121 return EmitSizeAlignOf(E->getArgumentType(), E->getType(), E->isSizeOf());
122 }
Daniel Dunbar879788d2008-08-04 16:51:22 +0000123 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
124 Value *V = llvm::ConstantInt::get(llvm::Type::Int32Ty,
125 CGF.GetIDForAddrOfLabel(E->getLabel()));
126 return Builder.CreateIntToPtr(V,
127 llvm::PointerType::getUnqual(llvm::Type::Int8Ty));
128 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000129
130 // l-values.
131 Value *VisitDeclRefExpr(DeclRefExpr *E) {
132 if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(E->getDecl()))
133 return llvm::ConstantInt::get(EC->getInitVal());
134 return EmitLoadOfLValue(E);
135 }
Chris Lattnercbfb5512008-03-01 08:45:05 +0000136 Value *VisitObjCMessageExpr(ObjCMessageExpr *E);
Chris Lattnerc61e9f82008-03-30 23:25:33 +0000137 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { return EmitLoadOfLValue(E);}
Chris Lattner9fba49a2007-08-24 05:35:26 +0000138 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmand0e9d092008-05-14 19:38:39 +0000139 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000140 Value *VisitMemberExpr(Expr *E) { return EmitLoadOfLValue(E); }
Nate Begemanaf6ed502008-04-18 23:10:10 +0000141 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Eli Friedmanf3c2cb42008-05-13 23:18:27 +0000142 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { return EmitLoadOfLValue(E); }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000143 Value *VisitStringLiteral(Expr *E) { return EmitLValue(E).getAddress(); }
Chris Lattner69909292008-08-10 01:53:14 +0000144 Value *VisitPredefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); }
Devang Patel01ab1302007-10-24 17:18:43 +0000145
146 Value *VisitInitListExpr(InitListExpr *E) {
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000147 unsigned NumInitElements = E->getNumInits();
148
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000149 const llvm::VectorType *VType =
Anders Carlsson35ab4f92008-01-29 01:15:48 +0000150 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
151
152 // We have a scalar in braces. Just use the first element.
153 if (!VType)
154 return Visit(E->getInit(0));
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000155
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000156 unsigned NumVectorElements = VType->getNumElements();
157 const llvm::Type *ElementType = VType->getElementType();
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000158
159 // Emit individual vector element stores.
160 llvm::Value *V = llvm::UndefValue::get(VType);
161
Anders Carlsson323d5682007-12-18 02:45:33 +0000162 // Emit initializers
163 unsigned i;
164 for (i = 0; i < NumInitElements; ++i) {
Devang Patel32c39832007-10-24 18:05:48 +0000165 Value *NewV = Visit(E->getInit(i));
166 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
167 V = Builder.CreateInsertElement(V, NewV, Idx);
Devang Patel01ab1302007-10-24 17:18:43 +0000168 }
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000169
170 // Emit remaining default initializers
171 for (/* Do not initialize i*/; i < NumVectorElements; ++i) {
172 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
173 llvm::Value *NewV = llvm::Constant::getNullValue(ElementType);
174 V = Builder.CreateInsertElement(V, NewV, Idx);
175 }
176
Devang Patel32c39832007-10-24 18:05:48 +0000177 return V;
Devang Patel01ab1302007-10-24 17:18:43 +0000178 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000179
Chris Lattner9fba49a2007-08-24 05:35:26 +0000180 Value *VisitImplicitCastExpr(const ImplicitCastExpr *E);
181 Value *VisitCastExpr(const CastExpr *E) {
182 return EmitCastExpr(E->getSubExpr(), E->getType());
183 }
184 Value *EmitCastExpr(const Expr *E, QualType T);
185
186 Value *VisitCallExpr(const CallExpr *E) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000187 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000188 }
189
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000190 Value *VisitStmtExpr(const StmtExpr *E);
191
Chris Lattner9fba49a2007-08-24 05:35:26 +0000192 // Unary Operators.
193 Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre);
194 Value *VisitUnaryPostDec(const UnaryOperator *E) {
195 return VisitPrePostIncDec(E, false, false);
196 }
197 Value *VisitUnaryPostInc(const UnaryOperator *E) {
198 return VisitPrePostIncDec(E, true, false);
199 }
200 Value *VisitUnaryPreDec(const UnaryOperator *E) {
201 return VisitPrePostIncDec(E, false, true);
202 }
203 Value *VisitUnaryPreInc(const UnaryOperator *E) {
204 return VisitPrePostIncDec(E, true, true);
205 }
206 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
207 return EmitLValue(E->getSubExpr()).getAddress();
208 }
209 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
210 Value *VisitUnaryPlus(const UnaryOperator *E) {
211 return Visit(E->getSubExpr());
212 }
213 Value *VisitUnaryMinus (const UnaryOperator *E);
214 Value *VisitUnaryNot (const UnaryOperator *E);
215 Value *VisitUnaryLNot (const UnaryOperator *E);
216 Value *VisitUnarySizeOf (const UnaryOperator *E) {
217 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), true);
218 }
219 Value *VisitUnaryAlignOf (const UnaryOperator *E) {
220 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), false);
221 }
222 Value *EmitSizeAlignOf(QualType TypeToSize, QualType RetType,
Chris Lattnercfac88d2008-04-02 17:35:06 +0000223 bool isSizeOf);
Chris Lattner01211af2007-08-24 21:20:17 +0000224 Value *VisitUnaryReal (const UnaryOperator *E);
225 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000226 Value *VisitUnaryExtension(const UnaryOperator *E) {
227 return Visit(E->getSubExpr());
228 }
Anders Carlsson52774ad2008-01-29 15:56:48 +0000229 Value *VisitUnaryOffsetOf(const UnaryOperator *E);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000230 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
231 return Visit(DAE->getExpr());
232 }
Anders Carlsson52774ad2008-01-29 15:56:48 +0000233
Chris Lattner9fba49a2007-08-24 05:35:26 +0000234 // Binary Operators.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000235 Value *EmitMul(const BinOpInfo &Ops) {
236 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
237 }
238 Value *EmitDiv(const BinOpInfo &Ops);
239 Value *EmitRem(const BinOpInfo &Ops);
240 Value *EmitAdd(const BinOpInfo &Ops);
241 Value *EmitSub(const BinOpInfo &Ops);
242 Value *EmitShl(const BinOpInfo &Ops);
243 Value *EmitShr(const BinOpInfo &Ops);
244 Value *EmitAnd(const BinOpInfo &Ops) {
245 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
246 }
247 Value *EmitXor(const BinOpInfo &Ops) {
248 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
249 }
250 Value *EmitOr (const BinOpInfo &Ops) {
251 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
252 }
253
Chris Lattner660e31d2007-08-24 21:00:35 +0000254 BinOpInfo EmitBinOps(const BinaryOperator *E);
Chris Lattner0d965302007-08-26 21:41:21 +0000255 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000256 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
257
258 // Binary operators and binary compound assignment operators.
259#define HANDLEBINOP(OP) \
Chris Lattner0d965302007-08-26 21:41:21 +0000260 Value *VisitBin ## OP(const BinaryOperator *E) { \
261 return Emit ## OP(EmitBinOps(E)); \
262 } \
263 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
264 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner660e31d2007-08-24 21:00:35 +0000265 }
266 HANDLEBINOP(Mul);
267 HANDLEBINOP(Div);
268 HANDLEBINOP(Rem);
269 HANDLEBINOP(Add);
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000270 HANDLEBINOP(Sub);
Chris Lattner660e31d2007-08-24 21:00:35 +0000271 HANDLEBINOP(Shl);
272 HANDLEBINOP(Shr);
273 HANDLEBINOP(And);
274 HANDLEBINOP(Xor);
275 HANDLEBINOP(Or);
276#undef HANDLEBINOP
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000277
Chris Lattner9fba49a2007-08-24 05:35:26 +0000278 // Comparisons.
279 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
280 unsigned SICmpOpc, unsigned FCmpOpc);
281#define VISITCOMP(CODE, UI, SI, FP) \
282 Value *VisitBin##CODE(const BinaryOperator *E) { \
283 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
284 llvm::FCmpInst::FP); }
285 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
286 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
287 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
288 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
289 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
290 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
291#undef VISITCOMP
292
293 Value *VisitBinAssign (const BinaryOperator *E);
294
295 Value *VisitBinLAnd (const BinaryOperator *E);
296 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000297 Value *VisitBinComma (const BinaryOperator *E);
298
299 // Other Operators.
300 Value *VisitConditionalOperator(const ConditionalOperator *CO);
301 Value *VisitChooseExpr(ChooseExpr *CE);
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000302 Value *VisitOverloadExpr(OverloadExpr *OE);
Anders Carlsson36760332007-10-15 20:28:48 +0000303 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000304 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
305 return CGF.EmitObjCStringLiteral(E);
306 }
Anders Carlsson36f07d82007-10-29 05:01:08 +0000307 Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000308};
309} // end anonymous namespace.
310
311//===----------------------------------------------------------------------===//
312// Utilities
313//===----------------------------------------------------------------------===//
314
Chris Lattnerd8d44222007-08-26 16:42:57 +0000315/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +0000316/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +0000317Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
318 assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs");
319
320 if (SrcType->isRealFloatingType()) {
321 // Compare against 0.0 for fp scalars.
322 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattnerd8d44222007-08-26 16:42:57 +0000323 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
324 }
325
326 assert((SrcType->isIntegerType() || SrcType->isPointerType()) &&
327 "Unknown scalar type to convert");
328
329 // Because of the type rules of C, we often end up computing a logical value,
330 // then zero extending it to int, then wanting it as a logical value again.
331 // Optimize this common case.
332 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
333 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
334 Value *Result = ZI->getOperand(0);
Eli Friedman24f33972008-01-29 18:13:51 +0000335 // If there aren't any more uses, zap the instruction to save space.
336 // Note that there can be more uses, for example if this
337 // is the result of an assignment.
338 if (ZI->use_empty())
339 ZI->eraseFromParent();
Chris Lattnerd8d44222007-08-26 16:42:57 +0000340 return Result;
341 }
342 }
343
344 // Compare against an integer or pointer null.
345 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
346 return Builder.CreateICmpNE(Src, Zero, "tobool");
347}
348
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000349/// EmitScalarConversion - Emit a conversion from the specified type to the
350/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000351Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
352 QualType DstType) {
Chris Lattnerc154ac12008-07-26 22:37:01 +0000353 SrcType = CGF.getContext().getCanonicalType(SrcType);
354 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000355 if (SrcType == DstType) return Src;
Chris Lattnere133d7f2007-08-26 07:21:11 +0000356
357 if (DstType->isVoidType()) return 0;
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000358
359 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnerc39c3652007-08-26 16:52:28 +0000360 if (DstType->isBooleanType())
361 return EmitConversionToBool(Src, SrcType);
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000362
363 const llvm::Type *DstTy = ConvertType(DstType);
364
365 // Ignore conversions like int -> uint.
366 if (Src->getType() == DstTy)
367 return Src;
368
369 // Handle pointer conversions next: pointers can only be converted to/from
370 // other pointers and integers.
371 if (isa<PointerType>(DstType)) {
372 // The source value may be an integer, or a pointer.
373 if (isa<llvm::PointerType>(Src->getType()))
374 return Builder.CreateBitCast(Src, DstTy, "conv");
375 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
376 return Builder.CreateIntToPtr(Src, DstTy, "conv");
377 }
378
379 if (isa<PointerType>(SrcType)) {
380 // Must be an ptr to int cast.
381 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson44db38f2007-10-31 23:18:02 +0000382 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000383 }
384
Nate Begemanaf6ed502008-04-18 23:10:10 +0000385 // A scalar can be splatted to an extended vector of the same element type
386 if (DstType->isExtVectorType() && !isa<VectorType>(SrcType) &&
Chris Lattner4f025a42008-02-02 04:51:41 +0000387 cast<llvm::VectorType>(DstTy)->getElementType() == Src->getType())
Nate Begemanec2d1062007-12-30 02:59:45 +0000388 return CGF.EmitVector(&Src, DstType->getAsVectorType()->getNumElements(),
389 true);
Nate Begemanec2d1062007-12-30 02:59:45 +0000390
Chris Lattner4f025a42008-02-02 04:51:41 +0000391 // Allow bitcast from vector to integer/fp of the same size.
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000392 if (isa<llvm::VectorType>(Src->getType()) ||
Chris Lattner4f025a42008-02-02 04:51:41 +0000393 isa<llvm::VectorType>(DstTy))
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000394 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000395
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000396 // Finally, we have the arithmetic types: real int/float.
397 if (isa<llvm::IntegerType>(Src->getType())) {
398 bool InputSigned = SrcType->isSignedIntegerType();
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000399 if (isa<llvm::IntegerType>(DstTy))
400 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
401 else if (InputSigned)
402 return Builder.CreateSIToFP(Src, DstTy, "conv");
403 else
404 return Builder.CreateUIToFP(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000405 }
406
407 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
408 if (isa<llvm::IntegerType>(DstTy)) {
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000409 if (DstType->isSignedIntegerType())
410 return Builder.CreateFPToSI(Src, DstTy, "conv");
411 else
412 return Builder.CreateFPToUI(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000413 }
414
415 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000416 if (DstTy->getTypeID() < Src->getType()->getTypeID())
417 return Builder.CreateFPTrunc(Src, DstTy, "conv");
418 else
419 return Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000420}
421
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000422/// EmitComplexToScalarConversion - Emit a conversion from the specified
423/// complex type to the specified destination type, where the destination
424/// type is an LLVM scalar type.
425Value *ScalarExprEmitter::
426EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
427 QualType SrcTy, QualType DstTy) {
Chris Lattnerc39c3652007-08-26 16:52:28 +0000428 // Get the source element type.
Chris Lattnerc154ac12008-07-26 22:37:01 +0000429 SrcTy = SrcTy->getAsComplexType()->getElementType();
Chris Lattnerc39c3652007-08-26 16:52:28 +0000430
431 // Handle conversions to bool first, they are special: comparisons against 0.
432 if (DstTy->isBooleanType()) {
433 // Complex != 0 -> (Real != 0) | (Imag != 0)
434 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
435 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
436 return Builder.CreateOr(Src.first, Src.second, "tobool");
437 }
438
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000439 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
440 // the imaginary part of the complex value is discarded and the value of the
441 // real part is converted according to the conversion rules for the
442 // corresponding real type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000443 return EmitScalarConversion(Src.first, SrcTy, DstTy);
444}
445
446
Chris Lattner9fba49a2007-08-24 05:35:26 +0000447//===----------------------------------------------------------------------===//
448// Visitor Methods
449//===----------------------------------------------------------------------===//
450
451Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Chris Lattnere8f49632007-12-02 01:49:16 +0000452 CGF.WarnUnsupported(E, "scalar expression");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000453 if (E->getType()->isVoidType())
454 return 0;
455 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
456}
457
Eli Friedmand0e9d092008-05-14 19:38:39 +0000458Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
459 llvm::SmallVector<llvm::Constant*, 32> indices;
460 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
461 indices.push_back(cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i))));
462 }
463 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
464 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
465 Value* SV = llvm::ConstantVector::get(indices.begin(), indices.size());
466 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
467}
468
Chris Lattnercbfb5512008-03-01 08:45:05 +0000469Value *ScalarExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
470 // Only the lookup mechanism and first two arguments of the method
471 // implementation vary between runtimes. We can get the receiver and
472 // arguments in generic code.
473
474 // Find the receiver
Chris Lattnerc61e9f82008-03-30 23:25:33 +0000475 llvm::Value *Receiver = CGF.EmitScalarExpr(E->getReceiver());
Chris Lattnercbfb5512008-03-01 08:45:05 +0000476
477 // Process the arguments
Chris Lattnerc61e9f82008-03-30 23:25:33 +0000478 unsigned ArgC = E->getNumArgs();
Chris Lattnercbfb5512008-03-01 08:45:05 +0000479 llvm::SmallVector<llvm::Value*, 16> Args;
Chris Lattnerc61e9f82008-03-30 23:25:33 +0000480 for (unsigned i = 0; i != ArgC; ++i) {
Chris Lattnercbfb5512008-03-01 08:45:05 +0000481 Expr *ArgExpr = E->getArg(i);
482 QualType ArgTy = ArgExpr->getType();
483 if (!CGF.hasAggregateLLVMType(ArgTy)) {
484 // Scalar argument is passed by-value.
485 Args.push_back(CGF.EmitScalarExpr(ArgExpr));
Chris Lattnerde0908b2008-04-04 16:54:41 +0000486 } else if (ArgTy->isAnyComplexType()) {
Chris Lattnercbfb5512008-03-01 08:45:05 +0000487 // Make a temporary alloca to pass the argument.
488 llvm::Value *DestMem = CGF.CreateTempAlloca(ConvertType(ArgTy));
489 CGF.EmitComplexExprIntoAddr(ArgExpr, DestMem, false);
490 Args.push_back(DestMem);
491 } else {
492 llvm::Value *DestMem = CGF.CreateTempAlloca(ConvertType(ArgTy));
493 CGF.EmitAggExpr(ArgExpr, DestMem, false);
494 Args.push_back(DestMem);
495 }
496 }
497
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000498 return Runtime->GenerateMessageSend(Builder, ConvertType(E->getType()),
Chris Lattner6e6a5972008-04-04 04:07:35 +0000499 CGF.LoadObjCSelf(),
Chris Lattner8384c142008-06-26 04:42:20 +0000500 Receiver, E->getSelector(),
Chris Lattnerc61e9f82008-03-30 23:25:33 +0000501 &Args[0], Args.size());
Chris Lattnercbfb5512008-03-01 08:45:05 +0000502}
503
Chris Lattner9fba49a2007-08-24 05:35:26 +0000504Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
505 // Emit subscript expressions in rvalue context's. For most cases, this just
506 // loads the lvalue formed by the subscript expr. However, we have to be
507 // careful, because the base of a vector subscript is occasionally an rvalue,
508 // so we can't get it as an lvalue.
509 if (!E->getBase()->getType()->isVectorType())
510 return EmitLoadOfLValue(E);
511
512 // Handle the vector case. The base must be a vector, the index must be an
513 // integer value.
514 Value *Base = Visit(E->getBase());
515 Value *Idx = Visit(E->getIdx());
516
517 // FIXME: Convert Idx to i32 type.
518 return Builder.CreateExtractElement(Base, Idx, "vecext");
519}
520
521/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
522/// also handle things like function to pointer-to-function decay, and array to
523/// pointer decay.
524Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
525 const Expr *Op = E->getSubExpr();
526
527 // If this is due to array->pointer conversion, emit the array expression as
528 // an l-value.
529 if (Op->getType()->isArrayType()) {
530 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
531 // will not true when we add support for VLAs.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000532 Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000533
534 assert(isa<llvm::PointerType>(V->getType()) &&
535 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
536 ->getElementType()) &&
537 "Doesn't support VLAs yet!");
Chris Lattner07307562008-03-19 05:19:41 +0000538 V = Builder.CreateStructGEP(V, 0, "arraydecay");
Chris Lattnere54443b2007-12-12 04:13:20 +0000539
540 // The resultant pointer type can be implicitly casted to other pointer
Chris Lattner3b8f5c62008-07-23 06:31:27 +0000541 // types as well (e.g. void*) and can be implicitly converted to integer.
542 const llvm::Type *DestTy = ConvertType(E->getType());
543 if (V->getType() != DestTy) {
544 if (isa<llvm::PointerType>(DestTy))
545 V = Builder.CreateBitCast(V, DestTy, "ptrconv");
546 else {
547 assert(isa<llvm::IntegerType>(DestTy) && "Unknown array decay");
548 V = Builder.CreatePtrToInt(V, DestTy, "ptrconv");
549 }
550 }
Chris Lattnere54443b2007-12-12 04:13:20 +0000551 return V;
552
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000553 } else if (E->getType()->isReferenceType()) {
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000554 return EmitLValue(Op).getAddress();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000555 }
556
557 return EmitCastExpr(Op, E->getType());
558}
559
560
561// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
562// have to handle a more broad range of conversions than explicit casts, as they
563// handle things like function to ptr-to-function decay etc.
564Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
Chris Lattner82e10392007-08-26 07:26:12 +0000565 // Handle cases where the source is an non-complex type.
Chris Lattner77288792008-02-16 23:55:16 +0000566
567 if (!CGF.hasAggregateLLVMType(E->getType())) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000568 Value *Src = Visit(const_cast<Expr*>(E));
569
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000570 // Use EmitScalarConversion to perform the conversion.
571 return EmitScalarConversion(Src, E->getType(), DestTy);
572 }
Chris Lattner77288792008-02-16 23:55:16 +0000573
Chris Lattnerde0908b2008-04-04 16:54:41 +0000574 if (E->getType()->isAnyComplexType()) {
Chris Lattner77288792008-02-16 23:55:16 +0000575 // Handle cases where the source is a complex type.
576 return EmitComplexToScalarConversion(CGF.EmitComplexExpr(E), E->getType(),
577 DestTy);
578 }
Chris Lattnerd579f7f2007-08-26 07:16:41 +0000579
Chris Lattner77288792008-02-16 23:55:16 +0000580 // Okay, this is a cast from an aggregate. It must be a cast to void. Just
581 // evaluate the result and return.
582 CGF.EmitAggExpr(E, 0, false);
583 return 0;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000584}
585
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000586Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
Chris Lattner09cee852008-07-26 20:23:23 +0000587 return CGF.EmitCompoundStmt(*E->getSubStmt(),
588 !E->getType()->isVoidType()).getScalarVal();
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000589}
590
591
Chris Lattner9fba49a2007-08-24 05:35:26 +0000592//===----------------------------------------------------------------------===//
593// Unary Operators
594//===----------------------------------------------------------------------===//
595
596Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattner855e3d72007-08-24 16:24:49 +0000597 bool isInc, bool isPre) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000598 LValue LV = EmitLValue(E->getSubExpr());
599 // FIXME: Handle volatile!
Chris Lattner0dc11f62007-08-26 05:10:16 +0000600 Value *InVal = CGF.EmitLoadOfLValue(LV, // false
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000601 E->getSubExpr()->getType()).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000602
603 int AmountVal = isInc ? 1 : -1;
604
605 Value *NextVal;
Chris Lattner0dc11f62007-08-26 05:10:16 +0000606 if (isa<llvm::PointerType>(InVal->getType())) {
607 // FIXME: This isn't right for VLAs.
608 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
Chris Lattner07307562008-03-19 05:19:41 +0000609 NextVal = Builder.CreateGEP(InVal, NextVal, "ptrincdec");
Chris Lattner0dc11f62007-08-26 05:10:16 +0000610 } else {
611 // Add the inc/dec to the real part.
612 if (isa<llvm::IntegerType>(InVal->getType()))
613 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000614 else if (InVal->getType() == llvm::Type::FloatTy)
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000615 NextVal =
Chris Lattner70c38672008-04-20 00:45:53 +0000616 llvm::ConstantFP::get(llvm::APFloat(static_cast<float>(AmountVal)));
Chris Lattnerd54d1f22008-04-20 00:50:39 +0000617 else if (InVal->getType() == llvm::Type::DoubleTy)
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000618 NextVal =
Chris Lattner70c38672008-04-20 00:45:53 +0000619 llvm::ConstantFP::get(llvm::APFloat(static_cast<double>(AmountVal)));
Chris Lattnerd54d1f22008-04-20 00:50:39 +0000620 else {
621 llvm::APFloat F(static_cast<float>(AmountVal));
Chris Lattner2a674dc2008-06-30 18:32:54 +0000622 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero);
Chris Lattnerd54d1f22008-04-20 00:50:39 +0000623 NextVal = llvm::ConstantFP::get(F);
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000624 }
Chris Lattner0dc11f62007-08-26 05:10:16 +0000625 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
626 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000627
628 // Store the updated result through the lvalue.
629 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV,
630 E->getSubExpr()->getType());
631
632 // If this is a postinc, return the value read from memory, otherwise use the
633 // updated value.
634 return isPre ? NextVal : InVal;
635}
636
637
638Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
639 Value *Op = Visit(E->getSubExpr());
640 return Builder.CreateNeg(Op, "neg");
641}
642
643Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
644 Value *Op = Visit(E->getSubExpr());
645 return Builder.CreateNot(Op, "neg");
646}
647
648Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
649 // Compare operand to zero.
650 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
651
652 // Invert value.
653 // TODO: Could dynamically modify easy computations here. For example, if
654 // the operand is an icmp ne, turn into icmp eq.
655 BoolVal = Builder.CreateNot(BoolVal, "lnot");
656
657 // ZExt result to int.
658 return Builder.CreateZExt(BoolVal, CGF.LLVMIntTy, "lnot.ext");
659}
660
661/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
662/// an integer (RetType).
663Value *ScalarExprEmitter::EmitSizeAlignOf(QualType TypeToSize,
Chris Lattner01211af2007-08-24 21:20:17 +0000664 QualType RetType,bool isSizeOf){
Chris Lattner20515462008-02-21 05:45:29 +0000665 assert(RetType->isIntegerType() && "Result type must be an integer!");
666 uint32_t ResultWidth =
Chris Lattner8cd0e932008-03-05 18:54:05 +0000667 static_cast<uint32_t>(CGF.getContext().getTypeSize(RetType));
Chris Lattner20515462008-02-21 05:45:29 +0000668
Daniel Dunbarfdb7acd2008-07-22 01:35:47 +0000669 // sizeof(void) and __alignof__(void) = 1 as a gcc extension. Also
670 // for function types.
Daniel Dunbar1c73aa22008-07-22 19:44:18 +0000671 // FIXME: what is alignof a function type in gcc?
Daniel Dunbarfdb7acd2008-07-22 01:35:47 +0000672 if (TypeToSize->isVoidType() || TypeToSize->isFunctionType())
Chris Lattner20515462008-02-21 05:45:29 +0000673 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, 1));
674
Chris Lattner9fba49a2007-08-24 05:35:26 +0000675 /// FIXME: This doesn't handle VLAs yet!
Chris Lattner8cd0e932008-03-05 18:54:05 +0000676 std::pair<uint64_t, unsigned> Info = CGF.getContext().getTypeInfo(TypeToSize);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000677
678 uint64_t Val = isSizeOf ? Info.first : Info.second;
679 Val /= 8; // Return size in bytes, not bits.
680
Chris Lattner9fba49a2007-08-24 05:35:26 +0000681 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
682}
683
Chris Lattner01211af2007-08-24 21:20:17 +0000684Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
685 Expr *Op = E->getSubExpr();
Chris Lattnerde0908b2008-04-04 16:54:41 +0000686 if (Op->getType()->isAnyComplexType())
Chris Lattner01211af2007-08-24 21:20:17 +0000687 return CGF.EmitComplexExpr(Op).first;
688 return Visit(Op);
689}
690Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
691 Expr *Op = E->getSubExpr();
Chris Lattnerde0908b2008-04-04 16:54:41 +0000692 if (Op->getType()->isAnyComplexType())
Chris Lattner01211af2007-08-24 21:20:17 +0000693 return CGF.EmitComplexExpr(Op).second;
Chris Lattnerdb8a6c92007-08-26 05:29:21 +0000694
695 // __imag on a scalar returns zero. Emit it the subexpr to ensure side
696 // effects are evaluated.
697 CGF.EmitScalarExpr(Op);
698 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner01211af2007-08-24 21:20:17 +0000699}
700
Anders Carlsson52774ad2008-01-29 15:56:48 +0000701Value *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E)
702{
703 int64_t Val = E->evaluateOffsetOf(CGF.getContext());
704
705 assert(E->getType()->isIntegerType() && "Result type must be an integer!");
706
Chris Lattner8cd0e932008-03-05 18:54:05 +0000707 uint32_t ResultWidth =
708 static_cast<uint32_t>(CGF.getContext().getTypeSize(E->getType()));
Anders Carlsson52774ad2008-01-29 15:56:48 +0000709 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
710}
Chris Lattner01211af2007-08-24 21:20:17 +0000711
Chris Lattner9fba49a2007-08-24 05:35:26 +0000712//===----------------------------------------------------------------------===//
713// Binary Operators
714//===----------------------------------------------------------------------===//
715
716BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
717 BinOpInfo Result;
718 Result.LHS = Visit(E->getLHS());
719 Result.RHS = Visit(E->getRHS());
Chris Lattner660e31d2007-08-24 21:00:35 +0000720 Result.Ty = E->getType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000721 Result.E = E;
722 return Result;
723}
724
Chris Lattner0d965302007-08-26 21:41:21 +0000725Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000726 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
727 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
728
729 BinOpInfo OpInfo;
730
731 // Load the LHS and RHS operands.
732 LValue LHSLV = EmitLValue(E->getLHS());
733 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Chris Lattner9c9f4bb2007-08-26 22:37:40 +0000734
735 // Determine the computation type. If the RHS is complex, then this is one of
736 // the add/sub/mul/div operators. All of these operators can be computed in
737 // with just their real component even though the computation domain really is
738 // complex.
Chris Lattner0d965302007-08-26 21:41:21 +0000739 QualType ComputeType = E->getComputationType();
Chris Lattner660e31d2007-08-24 21:00:35 +0000740
Chris Lattner9c9f4bb2007-08-26 22:37:40 +0000741 // If the computation type is complex, then the RHS is complex. Emit the RHS.
742 if (const ComplexType *CT = ComputeType->getAsComplexType()) {
743 ComputeType = CT->getElementType();
744
745 // Emit the RHS, only keeping the real component.
746 OpInfo.RHS = CGF.EmitComplexExpr(E->getRHS()).first;
747 RHSTy = RHSTy->getAsComplexType()->getElementType();
748 } else {
749 // Otherwise the RHS is a simple scalar value.
750 OpInfo.RHS = Visit(E->getRHS());
751 }
752
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000753 QualType LComputeTy, RComputeTy, ResultTy;
754
755 // Compound assignment does not contain enough information about all
756 // the types involved for pointer arithmetic cases. Figure it out
757 // here for now.
758 if (E->getLHS()->getType()->isPointerType()) {
759 // Pointer arithmetic cases: ptr +=,-= int and ptr -= ptr,
760 assert((E->getOpcode() == BinaryOperator::AddAssign ||
761 E->getOpcode() == BinaryOperator::SubAssign) &&
762 "Invalid compound assignment operator on pointer type.");
763 LComputeTy = E->getLHS()->getType();
764
765 if (E->getRHS()->getType()->isPointerType()) {
766 // Degenerate case of (ptr -= ptr) allowed by GCC implicit cast
767 // extension, the conversion from the pointer difference back to
768 // the LHS type is handled at the end.
769 assert(E->getOpcode() == BinaryOperator::SubAssign &&
770 "Invalid compound assignment operator on pointer type.");
771 RComputeTy = E->getLHS()->getType();
772 ResultTy = CGF.getContext().getPointerDiffType();
773 } else {
774 RComputeTy = E->getRHS()->getType();
775 ResultTy = LComputeTy;
776 }
777 } else if (E->getRHS()->getType()->isPointerType()) {
778 // Degenerate case of (int += ptr) allowed by GCC implicit cast
779 // extension.
780 assert(E->getOpcode() == BinaryOperator::AddAssign &&
781 "Invalid compound assignment operator on pointer type.");
782 LComputeTy = E->getLHS()->getType();
783 RComputeTy = E->getRHS()->getType();
784 ResultTy = RComputeTy;
785 } else {
786 LComputeTy = RComputeTy = ResultTy = ComputeType;
Chris Lattner660e31d2007-08-24 21:00:35 +0000787 }
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000788
789 // Convert the LHS/RHS values to the computation type.
790 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, LComputeTy);
791 OpInfo.RHS = EmitScalarConversion(OpInfo.RHS, RHSTy, RComputeTy);
792 OpInfo.Ty = ResultTy;
Chris Lattner660e31d2007-08-24 21:00:35 +0000793 OpInfo.E = E;
794
795 // Expand the binary operator.
796 Value *Result = (this->*Func)(OpInfo);
797
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000798 // Convert the result back to the LHS type.
799 Result = EmitScalarConversion(Result, ResultTy, LHSTy);
Chris Lattner660e31d2007-08-24 21:00:35 +0000800
801 // Store the result value into the LHS lvalue.
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000802 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy);
Chris Lattner660e31d2007-08-24 21:00:35 +0000803
Eli Friedmanf9b930c2008-05-25 14:13:57 +0000804 // For bitfields, we need the value in the bitfield
805 // FIXME: This adds an extra bitfield load
806 if (LHSLV.isBitfield())
807 Result = EmitLoadOfLValue(LHSLV, LHSTy);
808
Chris Lattner660e31d2007-08-24 21:00:35 +0000809 return Result;
810}
811
812
Chris Lattner9fba49a2007-08-24 05:35:26 +0000813Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Nate Begemanaade3bf2007-12-30 01:28:16 +0000814 if (Ops.LHS->getType()->isFPOrFPVector())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000815 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner660e31d2007-08-24 21:00:35 +0000816 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000817 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
818 else
819 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
820}
821
822Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
823 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner660e31d2007-08-24 21:00:35 +0000824 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000825 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
826 else
827 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
828}
829
830
831Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000832 if (!Ops.Ty->isPointerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000833 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Chris Lattner660e31d2007-08-24 21:00:35 +0000834
835 // FIXME: What about a pointer to a VLA?
Chris Lattner17c0cb02008-01-03 06:36:51 +0000836 Value *Ptr, *Idx;
837 Expr *IdxExp;
838 if (isa<llvm::PointerType>(Ops.LHS->getType())) { // pointer + int
839 Ptr = Ops.LHS;
840 Idx = Ops.RHS;
841 IdxExp = Ops.E->getRHS();
842 } else { // int + pointer
843 Ptr = Ops.RHS;
844 Idx = Ops.LHS;
845 IdxExp = Ops.E->getLHS();
846 }
847
848 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
849 if (Width < CGF.LLVMPointerWidth) {
850 // Zero or sign extend the pointer value based on whether the index is
851 // signed or not.
852 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
Chris Lattnerc154ac12008-07-26 22:37:01 +0000853 if (IdxExp->getType()->isSignedIntegerType())
Chris Lattner17c0cb02008-01-03 06:36:51 +0000854 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
855 else
856 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
857 }
858
859 return Builder.CreateGEP(Ptr, Idx, "add.ptr");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000860}
861
862Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
863 if (!isa<llvm::PointerType>(Ops.LHS->getType()))
864 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
Chris Lattner660e31d2007-08-24 21:00:35 +0000865
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000866 if (!isa<llvm::PointerType>(Ops.RHS->getType())) {
867 // pointer - int
868 Value *Idx = Ops.RHS;
869 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
870 if (Width < CGF.LLVMPointerWidth) {
871 // Zero or sign extend the pointer value based on whether the index is
872 // signed or not.
873 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
874 if (Ops.E->getRHS()->getType()->isSignedIntegerType())
875 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
876 else
877 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
878 }
879 Idx = Builder.CreateNeg(Idx, "sub.ptr.neg");
880
881 // FIXME: The pointer could point to a VLA.
882 // The GNU void* - int case is automatically handled here because
883 // our LLVM type for void* is i8*.
884 return Builder.CreateGEP(Ops.LHS, Idx, "sub.ptr");
Daniel Dunbar0aac9f62008-08-05 00:47:03 +0000885 } else {
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000886 // pointer - pointer
887 Value *LHS = Ops.LHS;
888 Value *RHS = Ops.RHS;
Chris Lattner660e31d2007-08-24 21:00:35 +0000889
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000890 const QualType LHSType = Ops.E->getLHS()->getType();
891 const QualType LHSElementType = LHSType->getAsPointerType()->getPointeeType();
892 uint64_t ElementSize;
Daniel Dunbar0aac9f62008-08-05 00:47:03 +0000893
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000894 // Handle GCC extension for pointer arithmetic on void* types.
895 if (LHSElementType->isVoidType()) {
896 ElementSize = 1;
897 } else {
898 ElementSize = CGF.getContext().getTypeSize(LHSElementType) / 8;
899 }
900
901 const llvm::Type *ResultType = ConvertType(Ops.Ty);
902 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
903 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
904 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
905
906 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
907 // remainder. As such, we handle common power-of-two cases here to generate
908 // better code. See PR2247.
909 if (llvm::isPowerOf2_64(ElementSize)) {
910 Value *ShAmt =
911 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
912 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
913 }
914
915 // Otherwise, do a full sdiv.
916 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
917 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000918 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000919}
920
921Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
922 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
923 // RHS to the same size as the LHS.
924 Value *RHS = Ops.RHS;
925 if (Ops.LHS->getType() != RHS->getType())
926 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
927
928 return Builder.CreateShl(Ops.LHS, RHS, "shl");
929}
930
931Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
932 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
933 // RHS to the same size as the LHS.
934 Value *RHS = Ops.RHS;
935 if (Ops.LHS->getType() != RHS->getType())
936 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
937
Chris Lattner660e31d2007-08-24 21:00:35 +0000938 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000939 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
940 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
941}
942
943Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
944 unsigned SICmpOpc, unsigned FCmpOpc) {
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000945 Value *Result;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000946 QualType LHSTy = E->getLHS()->getType();
Nate Begeman1591bc52008-07-25 20:16:05 +0000947 if (!LHSTy->isAnyComplexType() && !LHSTy->isVectorType()) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000948 Value *LHS = Visit(E->getLHS());
949 Value *RHS = Visit(E->getRHS());
950
951 if (LHS->getType()->isFloatingPoint()) {
Nate Begeman1591bc52008-07-25 20:16:05 +0000952 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +0000953 LHS, RHS, "cmp");
Eli Friedman850ea372008-05-29 15:09:15 +0000954 } else if (LHSTy->isSignedIntegerType()) {
955 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +0000956 LHS, RHS, "cmp");
957 } else {
Eli Friedman850ea372008-05-29 15:09:15 +0000958 // Unsigned integers and pointers.
959 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +0000960 LHS, RHS, "cmp");
961 }
Nate Begeman1591bc52008-07-25 20:16:05 +0000962 } else if (LHSTy->isVectorType()) {
963 Value *LHS = Visit(E->getLHS());
964 Value *RHS = Visit(E->getRHS());
965
966 if (LHS->getType()->isFPOrFPVector()) {
967 Result = Builder.CreateVFCmp((llvm::CmpInst::Predicate)FCmpOpc,
968 LHS, RHS, "cmp");
969 } else if (LHSTy->isUnsignedIntegerType()) {
970 Result = Builder.CreateVICmp((llvm::CmpInst::Predicate)UICmpOpc,
971 LHS, RHS, "cmp");
972 } else {
973 // Signed integers and pointers.
974 Result = Builder.CreateVICmp((llvm::CmpInst::Predicate)SICmpOpc,
975 LHS, RHS, "cmp");
976 }
977 return Result;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000978 } else {
979 // Complex Comparison: can only be an equality comparison.
980 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
981 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
982
Chris Lattnerc154ac12008-07-26 22:37:01 +0000983 QualType CETy = LHSTy->getAsComplexType()->getElementType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000984
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000985 Value *ResultR, *ResultI;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000986 if (CETy->isRealFloatingType()) {
987 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
988 LHS.first, RHS.first, "cmp.r");
989 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
990 LHS.second, RHS.second, "cmp.i");
991 } else {
992 // Complex comparisons can only be equality comparisons. As such, signed
993 // and unsigned opcodes are the same.
994 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
995 LHS.first, RHS.first, "cmp.r");
996 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
997 LHS.second, RHS.second, "cmp.i");
998 }
999
1000 if (E->getOpcode() == BinaryOperator::EQ) {
1001 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1002 } else {
1003 assert(E->getOpcode() == BinaryOperator::NE &&
1004 "Complex comparison other than == or != ?");
1005 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1006 }
1007 }
1008
1009 // ZExt result to int.
1010 return Builder.CreateZExt(Result, CGF.LLVMIntTy, "cmp.ext");
1011}
1012
1013Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
1014 LValue LHS = EmitLValue(E->getLHS());
1015 Value *RHS = Visit(E->getRHS());
1016
1017 // Store the value into the LHS.
1018 // FIXME: Volatility!
1019 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
Eli Friedmanf9b930c2008-05-25 14:13:57 +00001020
1021 // For bitfields, we need the value in the bitfield
1022 // FIXME: This adds an extra bitfield load
1023 if (LHS.isBitfield())
1024 return EmitLoadOfLValue(LHS, E->getLHS()->getType());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001025 // Return the RHS.
1026 return RHS;
1027}
1028
1029Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
1030 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
1031
Gabor Greif815e2c12008-04-06 20:42:52 +00001032 llvm::BasicBlock *ContBlock = llvm::BasicBlock::Create("land_cont");
1033 llvm::BasicBlock *RHSBlock = llvm::BasicBlock::Create("land_rhs");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001034
1035 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
1036 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
1037
1038 CGF.EmitBlock(RHSBlock);
1039 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1040
1041 // Reaquire the RHS block, as there may be subblocks inserted.
1042 RHSBlock = Builder.GetInsertBlock();
1043 CGF.EmitBlock(ContBlock);
1044
1045 // Create a PHI node. If we just evaluted the LHS condition, the result is
1046 // false. If we evaluated both, the result is the RHS condition.
1047 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
1048 PN->reserveOperandSpace(2);
1049 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
1050 PN->addIncoming(RHSCond, RHSBlock);
1051
1052 // ZExt result to int.
1053 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
1054}
1055
1056Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
1057 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
1058
Gabor Greif815e2c12008-04-06 20:42:52 +00001059 llvm::BasicBlock *ContBlock = llvm::BasicBlock::Create("lor_cont");
1060 llvm::BasicBlock *RHSBlock = llvm::BasicBlock::Create("lor_rhs");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001061
1062 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
1063 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
1064
1065 CGF.EmitBlock(RHSBlock);
1066 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1067
1068 // Reaquire the RHS block, as there may be subblocks inserted.
1069 RHSBlock = Builder.GetInsertBlock();
1070 CGF.EmitBlock(ContBlock);
1071
1072 // Create a PHI node. If we just evaluted the LHS condition, the result is
1073 // true. If we evaluated both, the result is the RHS condition.
1074 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
1075 PN->reserveOperandSpace(2);
1076 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
1077 PN->addIncoming(RHSCond, RHSBlock);
1078
1079 // ZExt result to int.
1080 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
1081}
1082
1083Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
1084 CGF.EmitStmt(E->getLHS());
1085 return Visit(E->getRHS());
1086}
1087
1088//===----------------------------------------------------------------------===//
1089// Other Operators
1090//===----------------------------------------------------------------------===//
1091
1092Value *ScalarExprEmitter::
1093VisitConditionalOperator(const ConditionalOperator *E) {
Gabor Greif815e2c12008-04-06 20:42:52 +00001094 llvm::BasicBlock *LHSBlock = llvm::BasicBlock::Create("cond.?");
1095 llvm::BasicBlock *RHSBlock = llvm::BasicBlock::Create("cond.:");
1096 llvm::BasicBlock *ContBlock = llvm::BasicBlock::Create("cond.cont");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001097
Chris Lattner98a425c2007-11-26 01:40:58 +00001098 // Evaluate the conditional, then convert it to bool. We do this explicitly
1099 // because we need the unconverted value if this is a GNU ?: expression with
1100 // missing middle value.
1101 Value *CondVal = CGF.EmitScalarExpr(E->getCond());
Chris Lattnerc2126682008-01-03 07:05:49 +00001102 Value *CondBoolVal =CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
1103 CGF.getContext().BoolTy);
Chris Lattner98a425c2007-11-26 01:40:58 +00001104 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001105
1106 CGF.EmitBlock(LHSBlock);
1107
1108 // Handle the GNU extension for missing LHS.
Chris Lattner98a425c2007-11-26 01:40:58 +00001109 Value *LHS;
1110 if (E->getLHS())
Eli Friedmance8d7032008-05-16 20:38:39 +00001111 LHS = Visit(E->getLHS());
Chris Lattner98a425c2007-11-26 01:40:58 +00001112 else // Perform promotions, to handle cases like "short ?: int"
1113 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
1114
Chris Lattner9fba49a2007-08-24 05:35:26 +00001115 Builder.CreateBr(ContBlock);
1116 LHSBlock = Builder.GetInsertBlock();
1117
1118 CGF.EmitBlock(RHSBlock);
1119
Eli Friedmance8d7032008-05-16 20:38:39 +00001120 Value *RHS = Visit(E->getRHS());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001121 Builder.CreateBr(ContBlock);
1122 RHSBlock = Builder.GetInsertBlock();
1123
1124 CGF.EmitBlock(ContBlock);
1125
Nuno Lopesb62ff242008-06-04 19:15:45 +00001126 if (!LHS || !RHS) {
Chris Lattner307da022007-11-30 17:56:23 +00001127 assert(E->getType()->isVoidType() && "Non-void value should have a value");
1128 return 0;
1129 }
1130
Chris Lattner9fba49a2007-08-24 05:35:26 +00001131 // Create a PHI node for the real part.
1132 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
1133 PN->reserveOperandSpace(2);
1134 PN->addIncoming(LHS, LHSBlock);
1135 PN->addIncoming(RHS, RHSBlock);
1136 return PN;
1137}
1138
1139Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Chris Lattner9fba49a2007-08-24 05:35:26 +00001140 // Emit the LHS or RHS as appropriate.
Devang Patel0f2a8fb2007-10-30 20:59:40 +00001141 return
1142 Visit(E->isConditionTrue(CGF.getContext()) ? E->getLHS() : E->getRHS());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001143}
1144
Nate Begeman9f3bfb72008-01-17 17:46:27 +00001145Value *ScalarExprEmitter::VisitOverloadExpr(OverloadExpr *E) {
Nate Begemanbd881ef2008-01-30 20:50:20 +00001146 return CGF.EmitCallExpr(E->getFn(), E->arg_begin(),
Ted Kremenek2719e982008-06-17 02:43:46 +00001147 E->arg_end(CGF.getContext())).getScalarVal();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00001148}
1149
Chris Lattner307da022007-11-30 17:56:23 +00001150Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Anders Carlsson36760332007-10-15 20:28:48 +00001151 llvm::Value *ArgValue = EmitLValue(VE->getSubExpr()).getAddress();
1152
1153 llvm::Value *V = Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
1154 return V;
1155}
1156
Chris Lattner307da022007-11-30 17:56:23 +00001157Value *ScalarExprEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Anders Carlsson36f07d82007-10-29 05:01:08 +00001158 std::string str;
Fariborz Jahanian248db262008-01-22 22:44:46 +00001159 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
1160 CGF.getContext().getObjCEncodingForType(E->getEncodedType(), str,
1161 EncodingRecordTypes);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001162
1163 llvm::Constant *C = llvm::ConstantArray::get(str);
1164 C = new llvm::GlobalVariable(C->getType(), true,
1165 llvm::GlobalValue::InternalLinkage,
1166 C, ".str", &CGF.CGM.getModule());
1167 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
1168 llvm::Constant *Zeros[] = { Zero, Zero };
1169 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
1170
1171 return C;
1172}
1173
Chris Lattner9fba49a2007-08-24 05:35:26 +00001174//===----------------------------------------------------------------------===//
1175// Entry Point into this File
1176//===----------------------------------------------------------------------===//
1177
1178/// EmitComplexExpr - Emit the computation of the specified expression of
1179/// complex type, ignoring the result.
1180Value *CodeGenFunction::EmitScalarExpr(const Expr *E) {
1181 assert(E && !hasAggregateLLVMType(E->getType()) &&
1182 "Invalid scalar expression to emit");
1183
1184 return ScalarExprEmitter(*this).Visit(const_cast<Expr*>(E));
1185}
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001186
1187/// EmitScalarConversion - Emit a conversion from the specified type to the
1188/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001189Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
1190 QualType DstTy) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001191 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
1192 "Invalid scalar expression to emit");
1193 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
1194}
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001195
1196/// EmitComplexToScalarConversion - Emit a conversion from the specified
1197/// complex type to the specified destination type, where the destination
1198/// type is an LLVM scalar type.
1199Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
1200 QualType SrcTy,
1201 QualType DstTy) {
Chris Lattnerde0908b2008-04-04 16:54:41 +00001202 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001203 "Invalid complex -> scalar conversion");
1204 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
1205 DstTy);
1206}
Anders Carlssona9234fe2007-12-10 19:35:18 +00001207
1208Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) {
1209 assert(V1->getType() == V2->getType() &&
1210 "Vector operands must be of the same type");
Anders Carlssona9234fe2007-12-10 19:35:18 +00001211 unsigned NumElements =
1212 cast<llvm::VectorType>(V1->getType())->getNumElements();
1213
1214 va_list va;
1215 va_start(va, V2);
1216
1217 llvm::SmallVector<llvm::Constant*, 16> Args;
Anders Carlssona9234fe2007-12-10 19:35:18 +00001218 for (unsigned i = 0; i < NumElements; i++) {
1219 int n = va_arg(va, int);
Anders Carlssona9234fe2007-12-10 19:35:18 +00001220 assert(n >= 0 && n < (int)NumElements * 2 &&
1221 "Vector shuffle index out of bounds!");
Anders Carlssona9234fe2007-12-10 19:35:18 +00001222 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, n));
1223 }
1224
1225 const char *Name = va_arg(va, const char *);
1226 va_end(va);
1227
1228 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
1229
1230 return Builder.CreateShuffleVector(V1, V2, Mask, Name);
1231}
1232
Anders Carlsson68b8be92007-12-15 21:23:30 +00001233llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals,
Chris Lattnera23eb7b2008-07-26 20:15:14 +00001234 unsigned NumVals, bool isSplat) {
Anders Carlsson68b8be92007-12-15 21:23:30 +00001235 llvm::Value *Vec
Chris Lattnera23eb7b2008-07-26 20:15:14 +00001236 = llvm::UndefValue::get(llvm::VectorType::get(Vals[0]->getType(), NumVals));
Anders Carlsson68b8be92007-12-15 21:23:30 +00001237
Chris Lattnera23eb7b2008-07-26 20:15:14 +00001238 for (unsigned i = 0, e = NumVals; i != e; ++i) {
Nate Begemanec2d1062007-12-30 02:59:45 +00001239 llvm::Value *Val = isSplat ? Vals[0] : Vals[i];
Anders Carlsson68b8be92007-12-15 21:23:30 +00001240 llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
Nate Begemanec2d1062007-12-30 02:59:45 +00001241 Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp");
Anders Carlsson68b8be92007-12-15 21:23:30 +00001242 }
1243
1244 return Vec;
1245}