blob: e408e9ff9ed3cbf9d73ba284a9d298fb3412d72e [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 Dunbar84bb85f2008-08-13 00:59:25 +000016#include "CGObjCRuntime.h"
Daniel Dunbareee5cd12008-08-11 05:00:27 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbarfa456242008-08-12 05:08:18 +000018#include "clang/AST/DeclObjC.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"
Chris Lattner9fba49a2007-08-24 05:35:26 +000025#include "llvm/Support/Compiler.h"
Chris Lattnerc2126682008-01-03 07:05:49 +000026#include <cstdarg>
Ted Kremenek03cf4df2007-12-10 23:44:32 +000027
Chris Lattner9fba49a2007-08-24 05:35:26 +000028using namespace clang;
29using namespace CodeGen;
30using llvm::Value;
31
32//===----------------------------------------------------------------------===//
33// Scalar Expression Emitter
34//===----------------------------------------------------------------------===//
35
36struct BinOpInfo {
37 Value *LHS;
38 Value *RHS;
Chris Lattner660e31d2007-08-24 21:00:35 +000039 QualType Ty; // Computation Type.
Chris Lattner9fba49a2007-08-24 05:35:26 +000040 const BinaryOperator *E;
41};
42
43namespace {
44class VISIBILITY_HIDDEN ScalarExprEmitter
45 : public StmtVisitor<ScalarExprEmitter, Value*> {
46 CodeGenFunction &CGF;
Chris Lattnerfaf23db2008-08-08 19:57:58 +000047 llvm::IRBuilder<> &Builder;
Chris Lattnercbfb5512008-03-01 08:45:05 +000048 CGObjCRuntime *Runtime;
49
Chris Lattner9fba49a2007-08-24 05:35:26 +000050public:
51
Chris Lattnercbfb5512008-03-01 08:45:05 +000052 ScalarExprEmitter(CodeGenFunction &cgf) : CGF(cgf),
53 Builder(CGF.Builder),
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000054 Runtime(0) {
55 if (CGF.CGM.hasObjCRuntime())
56 Runtime = &CGF.CGM.getObjCRuntime();
Chris Lattner9fba49a2007-08-24 05:35:26 +000057 }
Chris Lattner9fba49a2007-08-24 05:35:26 +000058
59 //===--------------------------------------------------------------------===//
60 // Utilities
61 //===--------------------------------------------------------------------===//
62
63 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
64 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
65
66 Value *EmitLoadOfLValue(LValue LV, QualType T) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +000067 return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +000068 }
69
70 /// EmitLoadOfLValue - Given an expression with complex type that represents a
71 /// value l-value, this method emits the address of the l-value, then loads
72 /// and returns the result.
73 Value *EmitLoadOfLValue(const Expr *E) {
74 // FIXME: Volatile
75 return EmitLoadOfLValue(EmitLValue(E), E->getType());
76 }
77
Chris Lattnerd8d44222007-08-26 16:42:57 +000078 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +000079 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +000080 Value *EmitConversionToBool(Value *Src, QualType DstTy);
81
Chris Lattner4e05d1e2007-08-26 06:48:56 +000082 /// EmitScalarConversion - Emit a conversion from the specified type to the
83 /// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +000084 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
85
86 /// EmitComplexToScalarConversion - Emit a conversion from the specified
87 /// complex type to the specified destination type, where the destination
88 /// type is an LLVM scalar type.
89 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
90 QualType SrcTy, QualType DstTy);
Chris Lattner4e05d1e2007-08-26 06:48:56 +000091
Chris Lattner9fba49a2007-08-24 05:35:26 +000092 //===--------------------------------------------------------------------===//
93 // Visitor Methods
94 //===--------------------------------------------------------------------===//
95
96 Value *VisitStmt(Stmt *S) {
Ted Kremenekb3ee1932007-12-11 21:27:55 +000097 S->dump(CGF.getContext().getSourceManager());
Chris Lattner9fba49a2007-08-24 05:35:26 +000098 assert(0 && "Stmt can't have complex result type!");
99 return 0;
100 }
101 Value *VisitExpr(Expr *S);
102 Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
103
104 // Leaves.
105 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
106 return llvm::ConstantInt::get(E->getValue());
107 }
108 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Chris Lattner70c38672008-04-20 00:45:53 +0000109 return llvm::ConstantFP::get(E->getValue());
Chris Lattner9fba49a2007-08-24 05:35:26 +0000110 }
111 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
112 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
113 }
Nate Begemane9bfe6d2007-11-15 05:40:03 +0000114 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
115 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
116 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000117 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
118 return llvm::ConstantInt::get(ConvertType(E->getType()),
Steve Naroff85f0dc52007-10-15 20:41:53 +0000119 CGF.getContext().typesAreCompatible(
120 E->getArgType1(), E->getArgType2()));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000121 }
122 Value *VisitSizeOfAlignOfTypeExpr(const SizeOfAlignOfTypeExpr *E) {
123 return EmitSizeAlignOf(E->getArgumentType(), E->getType(), E->isSizeOf());
124 }
Daniel Dunbar879788d2008-08-04 16:51:22 +0000125 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
126 Value *V = llvm::ConstantInt::get(llvm::Type::Int32Ty,
127 CGF.GetIDForAddrOfLabel(E->getLabel()));
128 return Builder.CreateIntToPtr(V,
129 llvm::PointerType::getUnqual(llvm::Type::Int8Ty));
130 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000131
132 // l-values.
133 Value *VisitDeclRefExpr(DeclRefExpr *E) {
134 if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(E->getDecl()))
135 return llvm::ConstantInt::get(EC->getInitVal());
136 return EmitLoadOfLValue(E);
137 }
Chris Lattnercbfb5512008-03-01 08:45:05 +0000138 Value *VisitObjCMessageExpr(ObjCMessageExpr *E);
Daniel Dunbara5a0cdb2008-08-12 03:55:34 +0000139 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E);
Daniel Dunbarfa456242008-08-12 05:08:18 +0000140 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E);
Chris Lattnerc61e9f82008-03-30 23:25:33 +0000141 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { return EmitLoadOfLValue(E);}
Chris Lattner9fba49a2007-08-24 05:35:26 +0000142 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmand0e9d092008-05-14 19:38:39 +0000143 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000144 Value *VisitMemberExpr(Expr *E) { return EmitLoadOfLValue(E); }
Nate Begemanaf6ed502008-04-18 23:10:10 +0000145 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Eli Friedmanf3c2cb42008-05-13 23:18:27 +0000146 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { return EmitLoadOfLValue(E); }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000147 Value *VisitStringLiteral(Expr *E) { return EmitLValue(E).getAddress(); }
Chris Lattner69909292008-08-10 01:53:14 +0000148 Value *VisitPredefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); }
Devang Patel01ab1302007-10-24 17:18:43 +0000149
150 Value *VisitInitListExpr(InitListExpr *E) {
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000151 unsigned NumInitElements = E->getNumInits();
152
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000153 const llvm::VectorType *VType =
Anders Carlsson35ab4f92008-01-29 01:15:48 +0000154 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
155
156 // We have a scalar in braces. Just use the first element.
157 if (!VType)
158 return Visit(E->getInit(0));
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000159
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000160 unsigned NumVectorElements = VType->getNumElements();
161 const llvm::Type *ElementType = VType->getElementType();
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000162
163 // Emit individual vector element stores.
164 llvm::Value *V = llvm::UndefValue::get(VType);
165
Anders Carlsson323d5682007-12-18 02:45:33 +0000166 // Emit initializers
167 unsigned i;
168 for (i = 0; i < NumInitElements; ++i) {
Devang Patel32c39832007-10-24 18:05:48 +0000169 Value *NewV = Visit(E->getInit(i));
170 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
171 V = Builder.CreateInsertElement(V, NewV, Idx);
Devang Patel01ab1302007-10-24 17:18:43 +0000172 }
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000173
174 // Emit remaining default initializers
175 for (/* Do not initialize i*/; i < NumVectorElements; ++i) {
176 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
177 llvm::Value *NewV = llvm::Constant::getNullValue(ElementType);
178 V = Builder.CreateInsertElement(V, NewV, Idx);
179 }
180
Devang Patel32c39832007-10-24 18:05:48 +0000181 return V;
Devang Patel01ab1302007-10-24 17:18:43 +0000182 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000183
Chris Lattner9fba49a2007-08-24 05:35:26 +0000184 Value *VisitImplicitCastExpr(const ImplicitCastExpr *E);
185 Value *VisitCastExpr(const CastExpr *E) {
186 return EmitCastExpr(E->getSubExpr(), E->getType());
187 }
188 Value *EmitCastExpr(const Expr *E, QualType T);
189
190 Value *VisitCallExpr(const CallExpr *E) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000191 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000192 }
193
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000194 Value *VisitStmtExpr(const StmtExpr *E);
195
Chris Lattner9fba49a2007-08-24 05:35:26 +0000196 // Unary Operators.
197 Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre);
198 Value *VisitUnaryPostDec(const UnaryOperator *E) {
199 return VisitPrePostIncDec(E, false, false);
200 }
201 Value *VisitUnaryPostInc(const UnaryOperator *E) {
202 return VisitPrePostIncDec(E, true, false);
203 }
204 Value *VisitUnaryPreDec(const UnaryOperator *E) {
205 return VisitPrePostIncDec(E, false, true);
206 }
207 Value *VisitUnaryPreInc(const UnaryOperator *E) {
208 return VisitPrePostIncDec(E, true, true);
209 }
210 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
211 return EmitLValue(E->getSubExpr()).getAddress();
212 }
213 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
214 Value *VisitUnaryPlus(const UnaryOperator *E) {
215 return Visit(E->getSubExpr());
216 }
217 Value *VisitUnaryMinus (const UnaryOperator *E);
218 Value *VisitUnaryNot (const UnaryOperator *E);
219 Value *VisitUnaryLNot (const UnaryOperator *E);
220 Value *VisitUnarySizeOf (const UnaryOperator *E) {
221 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), true);
222 }
223 Value *VisitUnaryAlignOf (const UnaryOperator *E) {
224 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), false);
225 }
226 Value *EmitSizeAlignOf(QualType TypeToSize, QualType RetType,
Chris Lattnercfac88d2008-04-02 17:35:06 +0000227 bool isSizeOf);
Chris Lattner01211af2007-08-24 21:20:17 +0000228 Value *VisitUnaryReal (const UnaryOperator *E);
229 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000230 Value *VisitUnaryExtension(const UnaryOperator *E) {
231 return Visit(E->getSubExpr());
232 }
Anders Carlsson52774ad2008-01-29 15:56:48 +0000233 Value *VisitUnaryOffsetOf(const UnaryOperator *E);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000234 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
235 return Visit(DAE->getExpr());
236 }
Anders Carlsson52774ad2008-01-29 15:56:48 +0000237
Chris Lattner9fba49a2007-08-24 05:35:26 +0000238 // Binary Operators.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000239 Value *EmitMul(const BinOpInfo &Ops) {
240 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
241 }
242 Value *EmitDiv(const BinOpInfo &Ops);
243 Value *EmitRem(const BinOpInfo &Ops);
244 Value *EmitAdd(const BinOpInfo &Ops);
245 Value *EmitSub(const BinOpInfo &Ops);
246 Value *EmitShl(const BinOpInfo &Ops);
247 Value *EmitShr(const BinOpInfo &Ops);
248 Value *EmitAnd(const BinOpInfo &Ops) {
249 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
250 }
251 Value *EmitXor(const BinOpInfo &Ops) {
252 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
253 }
254 Value *EmitOr (const BinOpInfo &Ops) {
255 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
256 }
257
Chris Lattner660e31d2007-08-24 21:00:35 +0000258 BinOpInfo EmitBinOps(const BinaryOperator *E);
Chris Lattner0d965302007-08-26 21:41:21 +0000259 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000260 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
261
262 // Binary operators and binary compound assignment operators.
263#define HANDLEBINOP(OP) \
Chris Lattner0d965302007-08-26 21:41:21 +0000264 Value *VisitBin ## OP(const BinaryOperator *E) { \
265 return Emit ## OP(EmitBinOps(E)); \
266 } \
267 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
268 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner660e31d2007-08-24 21:00:35 +0000269 }
270 HANDLEBINOP(Mul);
271 HANDLEBINOP(Div);
272 HANDLEBINOP(Rem);
273 HANDLEBINOP(Add);
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000274 HANDLEBINOP(Sub);
Chris Lattner660e31d2007-08-24 21:00:35 +0000275 HANDLEBINOP(Shl);
276 HANDLEBINOP(Shr);
277 HANDLEBINOP(And);
278 HANDLEBINOP(Xor);
279 HANDLEBINOP(Or);
280#undef HANDLEBINOP
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000281
Chris Lattner9fba49a2007-08-24 05:35:26 +0000282 // Comparisons.
283 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
284 unsigned SICmpOpc, unsigned FCmpOpc);
285#define VISITCOMP(CODE, UI, SI, FP) \
286 Value *VisitBin##CODE(const BinaryOperator *E) { \
287 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
288 llvm::FCmpInst::FP); }
289 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
290 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
291 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
292 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
293 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
294 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
295#undef VISITCOMP
296
297 Value *VisitBinAssign (const BinaryOperator *E);
298
299 Value *VisitBinLAnd (const BinaryOperator *E);
300 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000301 Value *VisitBinComma (const BinaryOperator *E);
302
303 // Other Operators.
304 Value *VisitConditionalOperator(const ConditionalOperator *CO);
305 Value *VisitChooseExpr(ChooseExpr *CE);
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000306 Value *VisitOverloadExpr(OverloadExpr *OE);
Anders Carlsson36760332007-10-15 20:28:48 +0000307 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000308 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
309 return CGF.EmitObjCStringLiteral(E);
310 }
Anders Carlsson36f07d82007-10-29 05:01:08 +0000311 Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000312};
313} // end anonymous namespace.
314
315//===----------------------------------------------------------------------===//
316// Utilities
317//===----------------------------------------------------------------------===//
318
Chris Lattnerd8d44222007-08-26 16:42:57 +0000319/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +0000320/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +0000321Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
322 assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs");
323
324 if (SrcType->isRealFloatingType()) {
325 // Compare against 0.0 for fp scalars.
326 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattnerd8d44222007-08-26 16:42:57 +0000327 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
328 }
329
330 assert((SrcType->isIntegerType() || SrcType->isPointerType()) &&
331 "Unknown scalar type to convert");
332
333 // Because of the type rules of C, we often end up computing a logical value,
334 // then zero extending it to int, then wanting it as a logical value again.
335 // Optimize this common case.
336 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
337 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
338 Value *Result = ZI->getOperand(0);
Eli Friedman24f33972008-01-29 18:13:51 +0000339 // If there aren't any more uses, zap the instruction to save space.
340 // Note that there can be more uses, for example if this
341 // is the result of an assignment.
342 if (ZI->use_empty())
343 ZI->eraseFromParent();
Chris Lattnerd8d44222007-08-26 16:42:57 +0000344 return Result;
345 }
346 }
347
348 // Compare against an integer or pointer null.
349 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
350 return Builder.CreateICmpNE(Src, Zero, "tobool");
351}
352
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000353/// EmitScalarConversion - Emit a conversion from the specified type to the
354/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000355Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
356 QualType DstType) {
Chris Lattnerc154ac12008-07-26 22:37:01 +0000357 SrcType = CGF.getContext().getCanonicalType(SrcType);
358 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000359 if (SrcType == DstType) return Src;
Chris Lattnere133d7f2007-08-26 07:21:11 +0000360
361 if (DstType->isVoidType()) return 0;
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000362
363 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnerc39c3652007-08-26 16:52:28 +0000364 if (DstType->isBooleanType())
365 return EmitConversionToBool(Src, SrcType);
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000366
367 const llvm::Type *DstTy = ConvertType(DstType);
368
369 // Ignore conversions like int -> uint.
370 if (Src->getType() == DstTy)
371 return Src;
372
373 // Handle pointer conversions next: pointers can only be converted to/from
374 // other pointers and integers.
375 if (isa<PointerType>(DstType)) {
376 // The source value may be an integer, or a pointer.
377 if (isa<llvm::PointerType>(Src->getType()))
378 return Builder.CreateBitCast(Src, DstTy, "conv");
379 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
380 return Builder.CreateIntToPtr(Src, DstTy, "conv");
381 }
382
383 if (isa<PointerType>(SrcType)) {
384 // Must be an ptr to int cast.
385 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson44db38f2007-10-31 23:18:02 +0000386 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000387 }
388
Nate Begemanaf6ed502008-04-18 23:10:10 +0000389 // A scalar can be splatted to an extended vector of the same element type
390 if (DstType->isExtVectorType() && !isa<VectorType>(SrcType) &&
Chris Lattner4f025a42008-02-02 04:51:41 +0000391 cast<llvm::VectorType>(DstTy)->getElementType() == Src->getType())
Nate Begemanec2d1062007-12-30 02:59:45 +0000392 return CGF.EmitVector(&Src, DstType->getAsVectorType()->getNumElements(),
393 true);
Nate Begemanec2d1062007-12-30 02:59:45 +0000394
Chris Lattner4f025a42008-02-02 04:51:41 +0000395 // Allow bitcast from vector to integer/fp of the same size.
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000396 if (isa<llvm::VectorType>(Src->getType()) ||
Chris Lattner4f025a42008-02-02 04:51:41 +0000397 isa<llvm::VectorType>(DstTy))
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000398 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000399
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000400 // Finally, we have the arithmetic types: real int/float.
401 if (isa<llvm::IntegerType>(Src->getType())) {
402 bool InputSigned = SrcType->isSignedIntegerType();
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000403 if (isa<llvm::IntegerType>(DstTy))
404 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
405 else if (InputSigned)
406 return Builder.CreateSIToFP(Src, DstTy, "conv");
407 else
408 return Builder.CreateUIToFP(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000409 }
410
411 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
412 if (isa<llvm::IntegerType>(DstTy)) {
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000413 if (DstType->isSignedIntegerType())
414 return Builder.CreateFPToSI(Src, DstTy, "conv");
415 else
416 return Builder.CreateFPToUI(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000417 }
418
419 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000420 if (DstTy->getTypeID() < Src->getType()->getTypeID())
421 return Builder.CreateFPTrunc(Src, DstTy, "conv");
422 else
423 return Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000424}
425
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000426/// EmitComplexToScalarConversion - Emit a conversion from the specified
427/// complex type to the specified destination type, where the destination
428/// type is an LLVM scalar type.
429Value *ScalarExprEmitter::
430EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
431 QualType SrcTy, QualType DstTy) {
Chris Lattnerc39c3652007-08-26 16:52:28 +0000432 // Get the source element type.
Chris Lattnerc154ac12008-07-26 22:37:01 +0000433 SrcTy = SrcTy->getAsComplexType()->getElementType();
Chris Lattnerc39c3652007-08-26 16:52:28 +0000434
435 // Handle conversions to bool first, they are special: comparisons against 0.
436 if (DstTy->isBooleanType()) {
437 // Complex != 0 -> (Real != 0) | (Imag != 0)
438 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
439 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
440 return Builder.CreateOr(Src.first, Src.second, "tobool");
441 }
442
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000443 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
444 // the imaginary part of the complex value is discarded and the value of the
445 // real part is converted according to the conversion rules for the
446 // corresponding real type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000447 return EmitScalarConversion(Src.first, SrcTy, DstTy);
448}
449
450
Chris Lattner9fba49a2007-08-24 05:35:26 +0000451//===----------------------------------------------------------------------===//
452// Visitor Methods
453//===----------------------------------------------------------------------===//
454
455Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbar9503b782008-08-16 00:56:44 +0000456 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000457 if (E->getType()->isVoidType())
458 return 0;
459 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
460}
461
Eli Friedmand0e9d092008-05-14 19:38:39 +0000462Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
463 llvm::SmallVector<llvm::Constant*, 32> indices;
464 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
465 indices.push_back(cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i))));
466 }
467 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
468 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
469 Value* SV = llvm::ConstantVector::get(indices.begin(), indices.size());
470 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
471}
472
Chris Lattnercbfb5512008-03-01 08:45:05 +0000473Value *ScalarExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
474 // Only the lookup mechanism and first two arguments of the method
475 // implementation vary between runtimes. We can get the receiver and
476 // arguments in generic code.
477
478 // Find the receiver
Chris Lattnerc61e9f82008-03-30 23:25:33 +0000479 llvm::Value *Receiver = CGF.EmitScalarExpr(E->getReceiver());
Chris Lattnercbfb5512008-03-01 08:45:05 +0000480
481 // Process the arguments
Chris Lattnerc61e9f82008-03-30 23:25:33 +0000482 unsigned ArgC = E->getNumArgs();
Chris Lattnercbfb5512008-03-01 08:45:05 +0000483 llvm::SmallVector<llvm::Value*, 16> Args;
Chris Lattnerc61e9f82008-03-30 23:25:33 +0000484 for (unsigned i = 0; i != ArgC; ++i) {
Chris Lattnercbfb5512008-03-01 08:45:05 +0000485 Expr *ArgExpr = E->getArg(i);
486 QualType ArgTy = ArgExpr->getType();
487 if (!CGF.hasAggregateLLVMType(ArgTy)) {
488 // Scalar argument is passed by-value.
489 Args.push_back(CGF.EmitScalarExpr(ArgExpr));
Chris Lattnerde0908b2008-04-04 16:54:41 +0000490 } else if (ArgTy->isAnyComplexType()) {
Chris Lattnercbfb5512008-03-01 08:45:05 +0000491 // Make a temporary alloca to pass the argument.
492 llvm::Value *DestMem = CGF.CreateTempAlloca(ConvertType(ArgTy));
493 CGF.EmitComplexExprIntoAddr(ArgExpr, DestMem, false);
494 Args.push_back(DestMem);
495 } else {
496 llvm::Value *DestMem = CGF.CreateTempAlloca(ConvertType(ArgTy));
497 CGF.EmitAggExpr(ArgExpr, DestMem, false);
498 Args.push_back(DestMem);
499 }
500 }
501
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000502 return Runtime->GenerateMessageSend(Builder, ConvertType(E->getType()),
Chris Lattner8384c142008-06-26 04:42:20 +0000503 Receiver, E->getSelector(),
Chris Lattnerc61e9f82008-03-30 23:25:33 +0000504 &Args[0], Args.size());
Chris Lattnercbfb5512008-03-01 08:45:05 +0000505}
506
Daniel Dunbara5a0cdb2008-08-12 03:55:34 +0000507Value *ScalarExprEmitter::VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
508 return Runtime->GetSelector(Builder, E->getSelector());
509}
510
Daniel Dunbarfa456242008-08-12 05:08:18 +0000511Value *ScalarExprEmitter::VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
512 // FIXME: This should pass the Decl not the name.
Daniel Dunbar84bb85f2008-08-13 00:59:25 +0000513 return Runtime->GenerateProtocolRef(Builder, E->getProtocol());
Daniel Dunbarfa456242008-08-12 05:08:18 +0000514}
515
Chris Lattner9fba49a2007-08-24 05:35:26 +0000516Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
517 // Emit subscript expressions in rvalue context's. For most cases, this just
518 // loads the lvalue formed by the subscript expr. However, we have to be
519 // careful, because the base of a vector subscript is occasionally an rvalue,
520 // so we can't get it as an lvalue.
521 if (!E->getBase()->getType()->isVectorType())
522 return EmitLoadOfLValue(E);
523
524 // Handle the vector case. The base must be a vector, the index must be an
525 // integer value.
526 Value *Base = Visit(E->getBase());
527 Value *Idx = Visit(E->getIdx());
528
529 // FIXME: Convert Idx to i32 type.
530 return Builder.CreateExtractElement(Base, Idx, "vecext");
531}
532
533/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
534/// also handle things like function to pointer-to-function decay, and array to
535/// pointer decay.
536Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
537 const Expr *Op = E->getSubExpr();
538
539 // If this is due to array->pointer conversion, emit the array expression as
540 // an l-value.
541 if (Op->getType()->isArrayType()) {
542 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
543 // will not true when we add support for VLAs.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000544 Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000545
546 assert(isa<llvm::PointerType>(V->getType()) &&
547 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
548 ->getElementType()) &&
549 "Doesn't support VLAs yet!");
Chris Lattner07307562008-03-19 05:19:41 +0000550 V = Builder.CreateStructGEP(V, 0, "arraydecay");
Chris Lattnere54443b2007-12-12 04:13:20 +0000551
552 // The resultant pointer type can be implicitly casted to other pointer
Chris Lattner3b8f5c62008-07-23 06:31:27 +0000553 // types as well (e.g. void*) and can be implicitly converted to integer.
554 const llvm::Type *DestTy = ConvertType(E->getType());
555 if (V->getType() != DestTy) {
556 if (isa<llvm::PointerType>(DestTy))
557 V = Builder.CreateBitCast(V, DestTy, "ptrconv");
558 else {
559 assert(isa<llvm::IntegerType>(DestTy) && "Unknown array decay");
560 V = Builder.CreatePtrToInt(V, DestTy, "ptrconv");
561 }
562 }
Chris Lattnere54443b2007-12-12 04:13:20 +0000563 return V;
564
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000565 } else if (E->getType()->isReferenceType()) {
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000566 return EmitLValue(Op).getAddress();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000567 }
568
569 return EmitCastExpr(Op, E->getType());
570}
571
572
573// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
574// have to handle a more broad range of conversions than explicit casts, as they
575// handle things like function to ptr-to-function decay etc.
576Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
Chris Lattner82e10392007-08-26 07:26:12 +0000577 // Handle cases where the source is an non-complex type.
Chris Lattner77288792008-02-16 23:55:16 +0000578
579 if (!CGF.hasAggregateLLVMType(E->getType())) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000580 Value *Src = Visit(const_cast<Expr*>(E));
581
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000582 // Use EmitScalarConversion to perform the conversion.
583 return EmitScalarConversion(Src, E->getType(), DestTy);
584 }
Chris Lattner77288792008-02-16 23:55:16 +0000585
Chris Lattnerde0908b2008-04-04 16:54:41 +0000586 if (E->getType()->isAnyComplexType()) {
Chris Lattner77288792008-02-16 23:55:16 +0000587 // Handle cases where the source is a complex type.
588 return EmitComplexToScalarConversion(CGF.EmitComplexExpr(E), E->getType(),
589 DestTy);
590 }
Chris Lattnerd579f7f2007-08-26 07:16:41 +0000591
Chris Lattner77288792008-02-16 23:55:16 +0000592 // Okay, this is a cast from an aggregate. It must be a cast to void. Just
593 // evaluate the result and return.
594 CGF.EmitAggExpr(E, 0, false);
595 return 0;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000596}
597
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000598Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
Chris Lattner09cee852008-07-26 20:23:23 +0000599 return CGF.EmitCompoundStmt(*E->getSubStmt(),
600 !E->getType()->isVoidType()).getScalarVal();
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000601}
602
603
Chris Lattner9fba49a2007-08-24 05:35:26 +0000604//===----------------------------------------------------------------------===//
605// Unary Operators
606//===----------------------------------------------------------------------===//
607
608Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattner855e3d72007-08-24 16:24:49 +0000609 bool isInc, bool isPre) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000610 LValue LV = EmitLValue(E->getSubExpr());
611 // FIXME: Handle volatile!
Chris Lattner0dc11f62007-08-26 05:10:16 +0000612 Value *InVal = CGF.EmitLoadOfLValue(LV, // false
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000613 E->getSubExpr()->getType()).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000614
615 int AmountVal = isInc ? 1 : -1;
616
617 Value *NextVal;
Chris Lattner0dc11f62007-08-26 05:10:16 +0000618 if (isa<llvm::PointerType>(InVal->getType())) {
619 // FIXME: This isn't right for VLAs.
620 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
Chris Lattner07307562008-03-19 05:19:41 +0000621 NextVal = Builder.CreateGEP(InVal, NextVal, "ptrincdec");
Chris Lattner0dc11f62007-08-26 05:10:16 +0000622 } else {
623 // Add the inc/dec to the real part.
624 if (isa<llvm::IntegerType>(InVal->getType()))
625 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000626 else if (InVal->getType() == llvm::Type::FloatTy)
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000627 NextVal =
Chris Lattner70c38672008-04-20 00:45:53 +0000628 llvm::ConstantFP::get(llvm::APFloat(static_cast<float>(AmountVal)));
Chris Lattnerd54d1f22008-04-20 00:50:39 +0000629 else if (InVal->getType() == llvm::Type::DoubleTy)
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000630 NextVal =
Chris Lattner70c38672008-04-20 00:45:53 +0000631 llvm::ConstantFP::get(llvm::APFloat(static_cast<double>(AmountVal)));
Chris Lattnerd54d1f22008-04-20 00:50:39 +0000632 else {
633 llvm::APFloat F(static_cast<float>(AmountVal));
Chris Lattner2a674dc2008-06-30 18:32:54 +0000634 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero);
Chris Lattnerd54d1f22008-04-20 00:50:39 +0000635 NextVal = llvm::ConstantFP::get(F);
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000636 }
Chris Lattner0dc11f62007-08-26 05:10:16 +0000637 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
638 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000639
640 // Store the updated result through the lvalue.
641 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV,
642 E->getSubExpr()->getType());
643
644 // If this is a postinc, return the value read from memory, otherwise use the
645 // updated value.
646 return isPre ? NextVal : InVal;
647}
648
649
650Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
651 Value *Op = Visit(E->getSubExpr());
652 return Builder.CreateNeg(Op, "neg");
653}
654
655Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
656 Value *Op = Visit(E->getSubExpr());
657 return Builder.CreateNot(Op, "neg");
658}
659
660Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
661 // Compare operand to zero.
662 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
663
664 // Invert value.
665 // TODO: Could dynamically modify easy computations here. For example, if
666 // the operand is an icmp ne, turn into icmp eq.
667 BoolVal = Builder.CreateNot(BoolVal, "lnot");
668
669 // ZExt result to int.
670 return Builder.CreateZExt(BoolVal, CGF.LLVMIntTy, "lnot.ext");
671}
672
673/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
674/// an integer (RetType).
675Value *ScalarExprEmitter::EmitSizeAlignOf(QualType TypeToSize,
Chris Lattner01211af2007-08-24 21:20:17 +0000676 QualType RetType,bool isSizeOf){
Chris Lattner20515462008-02-21 05:45:29 +0000677 assert(RetType->isIntegerType() && "Result type must be an integer!");
678 uint32_t ResultWidth =
Chris Lattner8cd0e932008-03-05 18:54:05 +0000679 static_cast<uint32_t>(CGF.getContext().getTypeSize(RetType));
Chris Lattner20515462008-02-21 05:45:29 +0000680
Daniel Dunbarfdb7acd2008-07-22 01:35:47 +0000681 // sizeof(void) and __alignof__(void) = 1 as a gcc extension. Also
682 // for function types.
Daniel Dunbar1c73aa22008-07-22 19:44:18 +0000683 // FIXME: what is alignof a function type in gcc?
Daniel Dunbarfdb7acd2008-07-22 01:35:47 +0000684 if (TypeToSize->isVoidType() || TypeToSize->isFunctionType())
Chris Lattner20515462008-02-21 05:45:29 +0000685 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, 1));
686
Chris Lattner9fba49a2007-08-24 05:35:26 +0000687 /// FIXME: This doesn't handle VLAs yet!
Chris Lattner8cd0e932008-03-05 18:54:05 +0000688 std::pair<uint64_t, unsigned> Info = CGF.getContext().getTypeInfo(TypeToSize);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000689
690 uint64_t Val = isSizeOf ? Info.first : Info.second;
691 Val /= 8; // Return size in bytes, not bits.
692
Chris Lattner9fba49a2007-08-24 05:35:26 +0000693 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
694}
695
Chris Lattner01211af2007-08-24 21:20:17 +0000696Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
697 Expr *Op = E->getSubExpr();
Chris Lattnerde0908b2008-04-04 16:54:41 +0000698 if (Op->getType()->isAnyComplexType())
Chris Lattner01211af2007-08-24 21:20:17 +0000699 return CGF.EmitComplexExpr(Op).first;
700 return Visit(Op);
701}
702Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
703 Expr *Op = E->getSubExpr();
Chris Lattnerde0908b2008-04-04 16:54:41 +0000704 if (Op->getType()->isAnyComplexType())
Chris Lattner01211af2007-08-24 21:20:17 +0000705 return CGF.EmitComplexExpr(Op).second;
Chris Lattnerdb8a6c92007-08-26 05:29:21 +0000706
707 // __imag on a scalar returns zero. Emit it the subexpr to ensure side
708 // effects are evaluated.
709 CGF.EmitScalarExpr(Op);
710 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner01211af2007-08-24 21:20:17 +0000711}
712
Anders Carlsson52774ad2008-01-29 15:56:48 +0000713Value *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E)
714{
715 int64_t Val = E->evaluateOffsetOf(CGF.getContext());
716
717 assert(E->getType()->isIntegerType() && "Result type must be an integer!");
718
Chris Lattner8cd0e932008-03-05 18:54:05 +0000719 uint32_t ResultWidth =
720 static_cast<uint32_t>(CGF.getContext().getTypeSize(E->getType()));
Anders Carlsson52774ad2008-01-29 15:56:48 +0000721 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
722}
Chris Lattner01211af2007-08-24 21:20:17 +0000723
Chris Lattner9fba49a2007-08-24 05:35:26 +0000724//===----------------------------------------------------------------------===//
725// Binary Operators
726//===----------------------------------------------------------------------===//
727
728BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
729 BinOpInfo Result;
730 Result.LHS = Visit(E->getLHS());
731 Result.RHS = Visit(E->getRHS());
Chris Lattner660e31d2007-08-24 21:00:35 +0000732 Result.Ty = E->getType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000733 Result.E = E;
734 return Result;
735}
736
Chris Lattner0d965302007-08-26 21:41:21 +0000737Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000738 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
739 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
740
741 BinOpInfo OpInfo;
742
743 // Load the LHS and RHS operands.
744 LValue LHSLV = EmitLValue(E->getLHS());
745 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Chris Lattner9c9f4bb2007-08-26 22:37:40 +0000746
747 // Determine the computation type. If the RHS is complex, then this is one of
748 // the add/sub/mul/div operators. All of these operators can be computed in
749 // with just their real component even though the computation domain really is
750 // complex.
Chris Lattner0d965302007-08-26 21:41:21 +0000751 QualType ComputeType = E->getComputationType();
Chris Lattner660e31d2007-08-24 21:00:35 +0000752
Chris Lattner9c9f4bb2007-08-26 22:37:40 +0000753 // If the computation type is complex, then the RHS is complex. Emit the RHS.
754 if (const ComplexType *CT = ComputeType->getAsComplexType()) {
755 ComputeType = CT->getElementType();
756
757 // Emit the RHS, only keeping the real component.
758 OpInfo.RHS = CGF.EmitComplexExpr(E->getRHS()).first;
759 RHSTy = RHSTy->getAsComplexType()->getElementType();
760 } else {
761 // Otherwise the RHS is a simple scalar value.
762 OpInfo.RHS = Visit(E->getRHS());
763 }
764
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000765 QualType LComputeTy, RComputeTy, ResultTy;
766
767 // Compound assignment does not contain enough information about all
768 // the types involved for pointer arithmetic cases. Figure it out
769 // here for now.
770 if (E->getLHS()->getType()->isPointerType()) {
771 // Pointer arithmetic cases: ptr +=,-= int and ptr -= ptr,
772 assert((E->getOpcode() == BinaryOperator::AddAssign ||
773 E->getOpcode() == BinaryOperator::SubAssign) &&
774 "Invalid compound assignment operator on pointer type.");
775 LComputeTy = E->getLHS()->getType();
776
777 if (E->getRHS()->getType()->isPointerType()) {
778 // Degenerate case of (ptr -= ptr) allowed by GCC implicit cast
779 // extension, the conversion from the pointer difference back to
780 // the LHS type is handled at the end.
781 assert(E->getOpcode() == BinaryOperator::SubAssign &&
782 "Invalid compound assignment operator on pointer type.");
783 RComputeTy = E->getLHS()->getType();
784 ResultTy = CGF.getContext().getPointerDiffType();
785 } else {
786 RComputeTy = E->getRHS()->getType();
787 ResultTy = LComputeTy;
788 }
789 } else if (E->getRHS()->getType()->isPointerType()) {
790 // Degenerate case of (int += ptr) allowed by GCC implicit cast
791 // extension.
792 assert(E->getOpcode() == BinaryOperator::AddAssign &&
793 "Invalid compound assignment operator on pointer type.");
794 LComputeTy = E->getLHS()->getType();
795 RComputeTy = E->getRHS()->getType();
796 ResultTy = RComputeTy;
797 } else {
798 LComputeTy = RComputeTy = ResultTy = ComputeType;
Chris Lattner660e31d2007-08-24 21:00:35 +0000799 }
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000800
801 // Convert the LHS/RHS values to the computation type.
802 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, LComputeTy);
803 OpInfo.RHS = EmitScalarConversion(OpInfo.RHS, RHSTy, RComputeTy);
804 OpInfo.Ty = ResultTy;
Chris Lattner660e31d2007-08-24 21:00:35 +0000805 OpInfo.E = E;
806
807 // Expand the binary operator.
808 Value *Result = (this->*Func)(OpInfo);
809
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000810 // Convert the result back to the LHS type.
811 Result = EmitScalarConversion(Result, ResultTy, LHSTy);
Chris Lattner660e31d2007-08-24 21:00:35 +0000812
813 // Store the result value into the LHS lvalue.
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000814 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy);
Chris Lattner660e31d2007-08-24 21:00:35 +0000815
Eli Friedmanf9b930c2008-05-25 14:13:57 +0000816 // For bitfields, we need the value in the bitfield
817 // FIXME: This adds an extra bitfield load
818 if (LHSLV.isBitfield())
819 Result = EmitLoadOfLValue(LHSLV, LHSTy);
820
Chris Lattner660e31d2007-08-24 21:00:35 +0000821 return Result;
822}
823
824
Chris Lattner9fba49a2007-08-24 05:35:26 +0000825Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Nate Begemanaade3bf2007-12-30 01:28:16 +0000826 if (Ops.LHS->getType()->isFPOrFPVector())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000827 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner660e31d2007-08-24 21:00:35 +0000828 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000829 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
830 else
831 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
832}
833
834Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
835 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner660e31d2007-08-24 21:00:35 +0000836 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000837 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
838 else
839 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
840}
841
842
843Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000844 if (!Ops.Ty->isPointerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000845 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Chris Lattner660e31d2007-08-24 21:00:35 +0000846
847 // FIXME: What about a pointer to a VLA?
Chris Lattner17c0cb02008-01-03 06:36:51 +0000848 Value *Ptr, *Idx;
849 Expr *IdxExp;
850 if (isa<llvm::PointerType>(Ops.LHS->getType())) { // pointer + int
851 Ptr = Ops.LHS;
852 Idx = Ops.RHS;
853 IdxExp = Ops.E->getRHS();
854 } else { // int + pointer
855 Ptr = Ops.RHS;
856 Idx = Ops.LHS;
857 IdxExp = Ops.E->getLHS();
858 }
859
860 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
861 if (Width < CGF.LLVMPointerWidth) {
862 // Zero or sign extend the pointer value based on whether the index is
863 // signed or not.
864 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
Chris Lattnerc154ac12008-07-26 22:37:01 +0000865 if (IdxExp->getType()->isSignedIntegerType())
Chris Lattner17c0cb02008-01-03 06:36:51 +0000866 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
867 else
868 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
869 }
870
871 return Builder.CreateGEP(Ptr, Idx, "add.ptr");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000872}
873
874Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
875 if (!isa<llvm::PointerType>(Ops.LHS->getType()))
876 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
Chris Lattner660e31d2007-08-24 21:00:35 +0000877
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000878 if (!isa<llvm::PointerType>(Ops.RHS->getType())) {
879 // pointer - int
880 Value *Idx = Ops.RHS;
881 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
882 if (Width < CGF.LLVMPointerWidth) {
883 // Zero or sign extend the pointer value based on whether the index is
884 // signed or not.
885 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
886 if (Ops.E->getRHS()->getType()->isSignedIntegerType())
887 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
888 else
889 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
890 }
891 Idx = Builder.CreateNeg(Idx, "sub.ptr.neg");
892
893 // FIXME: The pointer could point to a VLA.
894 // The GNU void* - int case is automatically handled here because
895 // our LLVM type for void* is i8*.
896 return Builder.CreateGEP(Ops.LHS, Idx, "sub.ptr");
Daniel Dunbar0aac9f62008-08-05 00:47:03 +0000897 } else {
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000898 // pointer - pointer
899 Value *LHS = Ops.LHS;
900 Value *RHS = Ops.RHS;
Chris Lattner660e31d2007-08-24 21:00:35 +0000901
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000902 const QualType LHSType = Ops.E->getLHS()->getType();
903 const QualType LHSElementType = LHSType->getAsPointerType()->getPointeeType();
904 uint64_t ElementSize;
Daniel Dunbar0aac9f62008-08-05 00:47:03 +0000905
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000906 // Handle GCC extension for pointer arithmetic on void* types.
907 if (LHSElementType->isVoidType()) {
908 ElementSize = 1;
909 } else {
910 ElementSize = CGF.getContext().getTypeSize(LHSElementType) / 8;
911 }
912
913 const llvm::Type *ResultType = ConvertType(Ops.Ty);
914 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
915 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
916 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
917
918 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
919 // remainder. As such, we handle common power-of-two cases here to generate
920 // better code. See PR2247.
921 if (llvm::isPowerOf2_64(ElementSize)) {
922 Value *ShAmt =
923 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
924 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
925 }
926
927 // Otherwise, do a full sdiv.
928 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
929 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000930 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000931}
932
933Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
934 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
935 // RHS to the same size as the LHS.
936 Value *RHS = Ops.RHS;
937 if (Ops.LHS->getType() != RHS->getType())
938 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
939
940 return Builder.CreateShl(Ops.LHS, RHS, "shl");
941}
942
943Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
944 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
945 // RHS to the same size as the LHS.
946 Value *RHS = Ops.RHS;
947 if (Ops.LHS->getType() != RHS->getType())
948 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
949
Chris Lattner660e31d2007-08-24 21:00:35 +0000950 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000951 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
952 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
953}
954
955Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
956 unsigned SICmpOpc, unsigned FCmpOpc) {
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000957 Value *Result;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000958 QualType LHSTy = E->getLHS()->getType();
Nate Begeman1591bc52008-07-25 20:16:05 +0000959 if (!LHSTy->isAnyComplexType() && !LHSTy->isVectorType()) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000960 Value *LHS = Visit(E->getLHS());
961 Value *RHS = Visit(E->getRHS());
962
963 if (LHS->getType()->isFloatingPoint()) {
Nate Begeman1591bc52008-07-25 20:16:05 +0000964 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +0000965 LHS, RHS, "cmp");
Eli Friedman850ea372008-05-29 15:09:15 +0000966 } else if (LHSTy->isSignedIntegerType()) {
967 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +0000968 LHS, RHS, "cmp");
969 } else {
Eli Friedman850ea372008-05-29 15:09:15 +0000970 // Unsigned integers and pointers.
971 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +0000972 LHS, RHS, "cmp");
973 }
Nate Begeman1591bc52008-07-25 20:16:05 +0000974 } else if (LHSTy->isVectorType()) {
975 Value *LHS = Visit(E->getLHS());
976 Value *RHS = Visit(E->getRHS());
977
978 if (LHS->getType()->isFPOrFPVector()) {
979 Result = Builder.CreateVFCmp((llvm::CmpInst::Predicate)FCmpOpc,
980 LHS, RHS, "cmp");
981 } else if (LHSTy->isUnsignedIntegerType()) {
982 Result = Builder.CreateVICmp((llvm::CmpInst::Predicate)UICmpOpc,
983 LHS, RHS, "cmp");
984 } else {
985 // Signed integers and pointers.
986 Result = Builder.CreateVICmp((llvm::CmpInst::Predicate)SICmpOpc,
987 LHS, RHS, "cmp");
988 }
989 return Result;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000990 } else {
991 // Complex Comparison: can only be an equality comparison.
992 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
993 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
994
Chris Lattnerc154ac12008-07-26 22:37:01 +0000995 QualType CETy = LHSTy->getAsComplexType()->getElementType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000996
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000997 Value *ResultR, *ResultI;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000998 if (CETy->isRealFloatingType()) {
999 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1000 LHS.first, RHS.first, "cmp.r");
1001 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1002 LHS.second, RHS.second, "cmp.i");
1003 } else {
1004 // Complex comparisons can only be equality comparisons. As such, signed
1005 // and unsigned opcodes are the same.
1006 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1007 LHS.first, RHS.first, "cmp.r");
1008 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1009 LHS.second, RHS.second, "cmp.i");
1010 }
1011
1012 if (E->getOpcode() == BinaryOperator::EQ) {
1013 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1014 } else {
1015 assert(E->getOpcode() == BinaryOperator::NE &&
1016 "Complex comparison other than == or != ?");
1017 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1018 }
1019 }
1020
1021 // ZExt result to int.
1022 return Builder.CreateZExt(Result, CGF.LLVMIntTy, "cmp.ext");
1023}
1024
1025Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
1026 LValue LHS = EmitLValue(E->getLHS());
1027 Value *RHS = Visit(E->getRHS());
1028
1029 // Store the value into the LHS.
1030 // FIXME: Volatility!
1031 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
Eli Friedmanf9b930c2008-05-25 14:13:57 +00001032
1033 // For bitfields, we need the value in the bitfield
1034 // FIXME: This adds an extra bitfield load
1035 if (LHS.isBitfield())
1036 return EmitLoadOfLValue(LHS, E->getLHS()->getType());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001037 // Return the RHS.
1038 return RHS;
1039}
1040
1041Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
1042 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
1043
Gabor Greif815e2c12008-04-06 20:42:52 +00001044 llvm::BasicBlock *ContBlock = llvm::BasicBlock::Create("land_cont");
1045 llvm::BasicBlock *RHSBlock = llvm::BasicBlock::Create("land_rhs");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001046
1047 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
1048 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
1049
1050 CGF.EmitBlock(RHSBlock);
1051 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1052
1053 // Reaquire the RHS block, as there may be subblocks inserted.
1054 RHSBlock = Builder.GetInsertBlock();
1055 CGF.EmitBlock(ContBlock);
1056
1057 // Create a PHI node. If we just evaluted the LHS condition, the result is
1058 // false. If we evaluated both, the result is the RHS condition.
1059 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
1060 PN->reserveOperandSpace(2);
1061 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
1062 PN->addIncoming(RHSCond, RHSBlock);
1063
1064 // ZExt result to int.
1065 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
1066}
1067
1068Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
1069 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
1070
Gabor Greif815e2c12008-04-06 20:42:52 +00001071 llvm::BasicBlock *ContBlock = llvm::BasicBlock::Create("lor_cont");
1072 llvm::BasicBlock *RHSBlock = llvm::BasicBlock::Create("lor_rhs");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001073
1074 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
1075 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
1076
1077 CGF.EmitBlock(RHSBlock);
1078 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1079
1080 // Reaquire the RHS block, as there may be subblocks inserted.
1081 RHSBlock = Builder.GetInsertBlock();
1082 CGF.EmitBlock(ContBlock);
1083
1084 // Create a PHI node. If we just evaluted the LHS condition, the result is
1085 // true. If we evaluated both, the result is the RHS condition.
1086 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
1087 PN->reserveOperandSpace(2);
1088 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
1089 PN->addIncoming(RHSCond, RHSBlock);
1090
1091 // ZExt result to int.
1092 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
1093}
1094
1095Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
1096 CGF.EmitStmt(E->getLHS());
1097 return Visit(E->getRHS());
1098}
1099
1100//===----------------------------------------------------------------------===//
1101// Other Operators
1102//===----------------------------------------------------------------------===//
1103
1104Value *ScalarExprEmitter::
1105VisitConditionalOperator(const ConditionalOperator *E) {
Gabor Greif815e2c12008-04-06 20:42:52 +00001106 llvm::BasicBlock *LHSBlock = llvm::BasicBlock::Create("cond.?");
1107 llvm::BasicBlock *RHSBlock = llvm::BasicBlock::Create("cond.:");
1108 llvm::BasicBlock *ContBlock = llvm::BasicBlock::Create("cond.cont");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001109
Chris Lattner98a425c2007-11-26 01:40:58 +00001110 // Evaluate the conditional, then convert it to bool. We do this explicitly
1111 // because we need the unconverted value if this is a GNU ?: expression with
1112 // missing middle value.
1113 Value *CondVal = CGF.EmitScalarExpr(E->getCond());
Chris Lattnerc2126682008-01-03 07:05:49 +00001114 Value *CondBoolVal =CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
1115 CGF.getContext().BoolTy);
Chris Lattner98a425c2007-11-26 01:40:58 +00001116 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001117
1118 CGF.EmitBlock(LHSBlock);
1119
1120 // Handle the GNU extension for missing LHS.
Chris Lattner98a425c2007-11-26 01:40:58 +00001121 Value *LHS;
1122 if (E->getLHS())
Eli Friedmance8d7032008-05-16 20:38:39 +00001123 LHS = Visit(E->getLHS());
Chris Lattner98a425c2007-11-26 01:40:58 +00001124 else // Perform promotions, to handle cases like "short ?: int"
1125 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
1126
Chris Lattner9fba49a2007-08-24 05:35:26 +00001127 Builder.CreateBr(ContBlock);
1128 LHSBlock = Builder.GetInsertBlock();
1129
1130 CGF.EmitBlock(RHSBlock);
1131
Eli Friedmance8d7032008-05-16 20:38:39 +00001132 Value *RHS = Visit(E->getRHS());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001133 Builder.CreateBr(ContBlock);
1134 RHSBlock = Builder.GetInsertBlock();
1135
1136 CGF.EmitBlock(ContBlock);
1137
Nuno Lopesb62ff242008-06-04 19:15:45 +00001138 if (!LHS || !RHS) {
Chris Lattner307da022007-11-30 17:56:23 +00001139 assert(E->getType()->isVoidType() && "Non-void value should have a value");
1140 return 0;
1141 }
1142
Chris Lattner9fba49a2007-08-24 05:35:26 +00001143 // Create a PHI node for the real part.
1144 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
1145 PN->reserveOperandSpace(2);
1146 PN->addIncoming(LHS, LHSBlock);
1147 PN->addIncoming(RHS, RHSBlock);
1148 return PN;
1149}
1150
1151Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Chris Lattner9fba49a2007-08-24 05:35:26 +00001152 // Emit the LHS or RHS as appropriate.
Devang Patel0f2a8fb2007-10-30 20:59:40 +00001153 return
1154 Visit(E->isConditionTrue(CGF.getContext()) ? E->getLHS() : E->getRHS());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001155}
1156
Nate Begeman9f3bfb72008-01-17 17:46:27 +00001157Value *ScalarExprEmitter::VisitOverloadExpr(OverloadExpr *E) {
Nate Begemanbd881ef2008-01-30 20:50:20 +00001158 return CGF.EmitCallExpr(E->getFn(), E->arg_begin(),
Ted Kremenek2719e982008-06-17 02:43:46 +00001159 E->arg_end(CGF.getContext())).getScalarVal();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00001160}
1161
Chris Lattner307da022007-11-30 17:56:23 +00001162Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Anders Carlsson36760332007-10-15 20:28:48 +00001163 llvm::Value *ArgValue = EmitLValue(VE->getSubExpr()).getAddress();
1164
1165 llvm::Value *V = Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
1166 return V;
1167}
1168
Chris Lattner307da022007-11-30 17:56:23 +00001169Value *ScalarExprEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Anders Carlsson36f07d82007-10-29 05:01:08 +00001170 std::string str;
Fariborz Jahanian248db262008-01-22 22:44:46 +00001171 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
1172 CGF.getContext().getObjCEncodingForType(E->getEncodedType(), str,
1173 EncodingRecordTypes);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001174
1175 llvm::Constant *C = llvm::ConstantArray::get(str);
1176 C = new llvm::GlobalVariable(C->getType(), true,
1177 llvm::GlobalValue::InternalLinkage,
1178 C, ".str", &CGF.CGM.getModule());
1179 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
1180 llvm::Constant *Zeros[] = { Zero, Zero };
1181 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
1182
1183 return C;
1184}
1185
Chris Lattner9fba49a2007-08-24 05:35:26 +00001186//===----------------------------------------------------------------------===//
1187// Entry Point into this File
1188//===----------------------------------------------------------------------===//
1189
1190/// EmitComplexExpr - Emit the computation of the specified expression of
1191/// complex type, ignoring the result.
1192Value *CodeGenFunction::EmitScalarExpr(const Expr *E) {
1193 assert(E && !hasAggregateLLVMType(E->getType()) &&
1194 "Invalid scalar expression to emit");
1195
1196 return ScalarExprEmitter(*this).Visit(const_cast<Expr*>(E));
1197}
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001198
1199/// EmitScalarConversion - Emit a conversion from the specified type to the
1200/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001201Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
1202 QualType DstTy) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001203 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
1204 "Invalid scalar expression to emit");
1205 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
1206}
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001207
1208/// EmitComplexToScalarConversion - Emit a conversion from the specified
1209/// complex type to the specified destination type, where the destination
1210/// type is an LLVM scalar type.
1211Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
1212 QualType SrcTy,
1213 QualType DstTy) {
Chris Lattnerde0908b2008-04-04 16:54:41 +00001214 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001215 "Invalid complex -> scalar conversion");
1216 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
1217 DstTy);
1218}
Anders Carlssona9234fe2007-12-10 19:35:18 +00001219
1220Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) {
1221 assert(V1->getType() == V2->getType() &&
1222 "Vector operands must be of the same type");
Anders Carlssona9234fe2007-12-10 19:35:18 +00001223 unsigned NumElements =
1224 cast<llvm::VectorType>(V1->getType())->getNumElements();
1225
1226 va_list va;
1227 va_start(va, V2);
1228
1229 llvm::SmallVector<llvm::Constant*, 16> Args;
Anders Carlssona9234fe2007-12-10 19:35:18 +00001230 for (unsigned i = 0; i < NumElements; i++) {
1231 int n = va_arg(va, int);
Anders Carlssona9234fe2007-12-10 19:35:18 +00001232 assert(n >= 0 && n < (int)NumElements * 2 &&
1233 "Vector shuffle index out of bounds!");
Anders Carlssona9234fe2007-12-10 19:35:18 +00001234 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, n));
1235 }
1236
1237 const char *Name = va_arg(va, const char *);
1238 va_end(va);
1239
1240 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
1241
1242 return Builder.CreateShuffleVector(V1, V2, Mask, Name);
1243}
1244
Anders Carlsson68b8be92007-12-15 21:23:30 +00001245llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals,
Chris Lattnera23eb7b2008-07-26 20:15:14 +00001246 unsigned NumVals, bool isSplat) {
Anders Carlsson68b8be92007-12-15 21:23:30 +00001247 llvm::Value *Vec
Chris Lattnera23eb7b2008-07-26 20:15:14 +00001248 = llvm::UndefValue::get(llvm::VectorType::get(Vals[0]->getType(), NumVals));
Anders Carlsson68b8be92007-12-15 21:23:30 +00001249
Chris Lattnera23eb7b2008-07-26 20:15:14 +00001250 for (unsigned i = 0, e = NumVals; i != e; ++i) {
Nate Begemanec2d1062007-12-30 02:59:45 +00001251 llvm::Value *Val = isSplat ? Vals[0] : Vals[i];
Anders Carlsson68b8be92007-12-15 21:23:30 +00001252 llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
Nate Begemanec2d1062007-12-30 02:59:45 +00001253 Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp");
Anders Carlsson68b8be92007-12-15 21:23:30 +00001254 }
1255
1256 return Vec;
1257}