blob: 85831d5dd3616aa060b088d66abb1a081663ff50 [file] [log] [blame]
Chris Lattner7f02f722007-08-24 05:35:26 +00001//===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner7f02f722007-08-24 05:35:26 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Expr nodes with scalar LLVM types as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
15#include "CodeGenModule.h"
16#include "clang/AST/AST.h"
17#include "llvm/Constants.h"
18#include "llvm/Function.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000019#include "llvm/GlobalVariable.h"
Anders Carlsson7c50aca2007-10-15 20:28:48 +000020#include "llvm/Intrinsics.h"
Chris Lattner7f02f722007-08-24 05:35:26 +000021#include "llvm/Support/Compiler.h"
Chris Lattnerc89bf692008-01-03 07:05:49 +000022#include <cstdarg>
Ted Kremenek6aad91a2007-12-10 23:44:32 +000023
Chris Lattner7f02f722007-08-24 05:35:26 +000024using namespace clang;
25using namespace CodeGen;
26using llvm::Value;
27
28//===----------------------------------------------------------------------===//
29// Scalar Expression Emitter
30//===----------------------------------------------------------------------===//
31
32struct BinOpInfo {
33 Value *LHS;
34 Value *RHS;
Chris Lattner1f1ded92007-08-24 21:00:35 +000035 QualType Ty; // Computation Type.
Chris Lattner7f02f722007-08-24 05:35:26 +000036 const BinaryOperator *E;
37};
38
39namespace {
40class VISIBILITY_HIDDEN ScalarExprEmitter
41 : public StmtVisitor<ScalarExprEmitter, Value*> {
42 CodeGenFunction &CGF;
Devang Patel50c90342007-10-09 19:49:58 +000043 llvm::LLVMFoldingBuilder &Builder;
Chris Lattner7f02f722007-08-24 05:35:26 +000044public:
45
46 ScalarExprEmitter(CodeGenFunction &cgf) : CGF(cgf), Builder(CGF.Builder) {
47 }
48
49
50 //===--------------------------------------------------------------------===//
51 // Utilities
52 //===--------------------------------------------------------------------===//
53
54 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
55 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
56
57 Value *EmitLoadOfLValue(LValue LV, QualType T) {
Chris Lattner9b655512007-08-31 22:49:20 +000058 return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +000059 }
60
61 /// EmitLoadOfLValue - Given an expression with complex type that represents a
62 /// value l-value, this method emits the address of the l-value, then loads
63 /// and returns the result.
64 Value *EmitLoadOfLValue(const Expr *E) {
65 // FIXME: Volatile
66 return EmitLoadOfLValue(EmitLValue(E), E->getType());
67 }
68
Chris Lattner9abc84e2007-08-26 16:42:57 +000069 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +000070 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +000071 Value *EmitConversionToBool(Value *Src, QualType DstTy);
72
Chris Lattner3707b252007-08-26 06:48:56 +000073 /// EmitScalarConversion - Emit a conversion from the specified type to the
74 /// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +000075 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
76
77 /// EmitComplexToScalarConversion - Emit a conversion from the specified
78 /// complex type to the specified destination type, where the destination
79 /// type is an LLVM scalar type.
80 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
81 QualType SrcTy, QualType DstTy);
Chris Lattner3707b252007-08-26 06:48:56 +000082
Chris Lattner7f02f722007-08-24 05:35:26 +000083 //===--------------------------------------------------------------------===//
84 // Visitor Methods
85 //===--------------------------------------------------------------------===//
86
87 Value *VisitStmt(Stmt *S) {
Ted Kremenek7a9d49f2007-12-11 21:27:55 +000088 S->dump(CGF.getContext().getSourceManager());
Chris Lattner7f02f722007-08-24 05:35:26 +000089 assert(0 && "Stmt can't have complex result type!");
90 return 0;
91 }
92 Value *VisitExpr(Expr *S);
93 Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
94
95 // Leaves.
96 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
97 return llvm::ConstantInt::get(E->getValue());
98 }
99 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Chris Lattnerc9bec4b2007-09-22 18:47:25 +0000100 return llvm::ConstantFP::get(ConvertType(E->getType()), E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000101 }
102 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
103 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
104 }
Nate Begemane7579b52007-11-15 05:40:03 +0000105 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
106 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
107 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000108 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
109 return llvm::ConstantInt::get(ConvertType(E->getType()),
Steve Naroffec0550f2007-10-15 20:41:53 +0000110 CGF.getContext().typesAreCompatible(
111 E->getArgType1(), E->getArgType2()));
Chris Lattner7f02f722007-08-24 05:35:26 +0000112 }
113 Value *VisitSizeOfAlignOfTypeExpr(const SizeOfAlignOfTypeExpr *E) {
114 return EmitSizeAlignOf(E->getArgumentType(), E->getType(), E->isSizeOf());
115 }
116
117 // l-values.
118 Value *VisitDeclRefExpr(DeclRefExpr *E) {
119 if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(E->getDecl()))
120 return llvm::ConstantInt::get(EC->getInitVal());
121 return EmitLoadOfLValue(E);
122 }
123 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
124 Value *VisitMemberExpr(Expr *E) { return EmitLoadOfLValue(E); }
125 Value *VisitOCUVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
126 Value *VisitStringLiteral(Expr *E) { return EmitLValue(E).getAddress(); }
127 Value *VisitPreDefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); }
Devang Patel35634f52007-10-24 17:18:43 +0000128
129 Value *VisitInitListExpr(InitListExpr *E) {
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000130 unsigned NumInitElements = E->getNumInits();
131
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000132 const llvm::VectorType *VType =
Anders Carlssonf6884ac2008-01-29 01:15:48 +0000133 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
134
135 // We have a scalar in braces. Just use the first element.
136 if (!VType)
137 return Visit(E->getInit(0));
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000138
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000139 unsigned NumVectorElements = VType->getNumElements();
140 const llvm::Type *ElementType = VType->getElementType();
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000141
142 // Emit individual vector element stores.
143 llvm::Value *V = llvm::UndefValue::get(VType);
144
Anders Carlsson222d2c82007-12-18 02:45:33 +0000145 // Emit initializers
146 unsigned i;
147 for (i = 0; i < NumInitElements; ++i) {
Devang Patela83cc332007-10-24 18:05:48 +0000148 Value *NewV = Visit(E->getInit(i));
149 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
150 V = Builder.CreateInsertElement(V, NewV, Idx);
Devang Patel35634f52007-10-24 17:18:43 +0000151 }
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000152
153 // Emit remaining default initializers
154 for (/* Do not initialize i*/; i < NumVectorElements; ++i) {
155 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
156 llvm::Value *NewV = llvm::Constant::getNullValue(ElementType);
157 V = Builder.CreateInsertElement(V, NewV, Idx);
158 }
159
Devang Patela83cc332007-10-24 18:05:48 +0000160 return V;
Devang Patel35634f52007-10-24 17:18:43 +0000161 }
162
163 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
164 return Visit(E->getInitializer());
165 }
166
Chris Lattner7f02f722007-08-24 05:35:26 +0000167 Value *VisitImplicitCastExpr(const ImplicitCastExpr *E);
168 Value *VisitCastExpr(const CastExpr *E) {
169 return EmitCastExpr(E->getSubExpr(), E->getType());
170 }
171 Value *EmitCastExpr(const Expr *E, QualType T);
172
173 Value *VisitCallExpr(const CallExpr *E) {
Chris Lattner9b655512007-08-31 22:49:20 +0000174 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +0000175 }
176
Chris Lattner33793202007-08-31 22:09:40 +0000177 Value *VisitStmtExpr(const StmtExpr *E);
178
Chris Lattner7f02f722007-08-24 05:35:26 +0000179 // Unary Operators.
180 Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre);
181 Value *VisitUnaryPostDec(const UnaryOperator *E) {
182 return VisitPrePostIncDec(E, false, false);
183 }
184 Value *VisitUnaryPostInc(const UnaryOperator *E) {
185 return VisitPrePostIncDec(E, true, false);
186 }
187 Value *VisitUnaryPreDec(const UnaryOperator *E) {
188 return VisitPrePostIncDec(E, false, true);
189 }
190 Value *VisitUnaryPreInc(const UnaryOperator *E) {
191 return VisitPrePostIncDec(E, true, true);
192 }
193 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
194 return EmitLValue(E->getSubExpr()).getAddress();
195 }
196 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
197 Value *VisitUnaryPlus(const UnaryOperator *E) {
198 return Visit(E->getSubExpr());
199 }
200 Value *VisitUnaryMinus (const UnaryOperator *E);
201 Value *VisitUnaryNot (const UnaryOperator *E);
202 Value *VisitUnaryLNot (const UnaryOperator *E);
203 Value *VisitUnarySizeOf (const UnaryOperator *E) {
204 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), true);
205 }
206 Value *VisitUnaryAlignOf (const UnaryOperator *E) {
207 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), false);
208 }
209 Value *EmitSizeAlignOf(QualType TypeToSize, QualType RetType,
210 bool isSizeOf);
Chris Lattner46f93d02007-08-24 21:20:17 +0000211 Value *VisitUnaryReal (const UnaryOperator *E);
212 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000213 Value *VisitUnaryExtension(const UnaryOperator *E) {
214 return Visit(E->getSubExpr());
215 }
Anders Carlsson5a1deb82008-01-29 15:56:48 +0000216 Value *VisitUnaryOffsetOf(const UnaryOperator *E);
217
Chris Lattner7f02f722007-08-24 05:35:26 +0000218 // Binary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000219 Value *EmitMul(const BinOpInfo &Ops) {
220 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
221 }
222 Value *EmitDiv(const BinOpInfo &Ops);
223 Value *EmitRem(const BinOpInfo &Ops);
224 Value *EmitAdd(const BinOpInfo &Ops);
225 Value *EmitSub(const BinOpInfo &Ops);
226 Value *EmitShl(const BinOpInfo &Ops);
227 Value *EmitShr(const BinOpInfo &Ops);
228 Value *EmitAnd(const BinOpInfo &Ops) {
229 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
230 }
231 Value *EmitXor(const BinOpInfo &Ops) {
232 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
233 }
234 Value *EmitOr (const BinOpInfo &Ops) {
235 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
236 }
237
Chris Lattner1f1ded92007-08-24 21:00:35 +0000238 BinOpInfo EmitBinOps(const BinaryOperator *E);
Chris Lattner3ccf7742007-08-26 21:41:21 +0000239 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner1f1ded92007-08-24 21:00:35 +0000240 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
241
242 // Binary operators and binary compound assignment operators.
243#define HANDLEBINOP(OP) \
Chris Lattner3ccf7742007-08-26 21:41:21 +0000244 Value *VisitBin ## OP(const BinaryOperator *E) { \
245 return Emit ## OP(EmitBinOps(E)); \
246 } \
247 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
248 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner1f1ded92007-08-24 21:00:35 +0000249 }
250 HANDLEBINOP(Mul);
251 HANDLEBINOP(Div);
252 HANDLEBINOP(Rem);
253 HANDLEBINOP(Add);
254 // (Sub) - Sub is handled specially below for ptr-ptr subtract.
255 HANDLEBINOP(Shl);
256 HANDLEBINOP(Shr);
257 HANDLEBINOP(And);
258 HANDLEBINOP(Xor);
259 HANDLEBINOP(Or);
260#undef HANDLEBINOP
261 Value *VisitBinSub(const BinaryOperator *E);
Chris Lattner3ccf7742007-08-26 21:41:21 +0000262 Value *VisitBinSubAssign(const CompoundAssignOperator *E) {
Chris Lattner1f1ded92007-08-24 21:00:35 +0000263 return EmitCompoundAssign(E, &ScalarExprEmitter::EmitSub);
264 }
265
Chris Lattner7f02f722007-08-24 05:35:26 +0000266 // Comparisons.
267 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
268 unsigned SICmpOpc, unsigned FCmpOpc);
269#define VISITCOMP(CODE, UI, SI, FP) \
270 Value *VisitBin##CODE(const BinaryOperator *E) { \
271 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
272 llvm::FCmpInst::FP); }
273 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
274 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
275 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
276 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
277 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
278 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
279#undef VISITCOMP
280
281 Value *VisitBinAssign (const BinaryOperator *E);
282
283 Value *VisitBinLAnd (const BinaryOperator *E);
284 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000285 Value *VisitBinComma (const BinaryOperator *E);
286
287 // Other Operators.
288 Value *VisitConditionalOperator(const ConditionalOperator *CO);
289 Value *VisitChooseExpr(ChooseExpr *CE);
Nate Begemane2ce1d92008-01-17 17:46:27 +0000290 Value *VisitOverloadExpr(OverloadExpr *OE);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000291 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000292 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
293 return CGF.EmitObjCStringLiteral(E);
294 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +0000295 Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000296};
297} // end anonymous namespace.
298
299//===----------------------------------------------------------------------===//
300// Utilities
301//===----------------------------------------------------------------------===//
302
Chris Lattner9abc84e2007-08-26 16:42:57 +0000303/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +0000304/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +0000305Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
306 assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs");
307
308 if (SrcType->isRealFloatingType()) {
309 // Compare against 0.0 for fp scalars.
310 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattner9abc84e2007-08-26 16:42:57 +0000311 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
312 }
313
314 assert((SrcType->isIntegerType() || SrcType->isPointerType()) &&
315 "Unknown scalar type to convert");
316
317 // Because of the type rules of C, we often end up computing a logical value,
318 // then zero extending it to int, then wanting it as a logical value again.
319 // Optimize this common case.
320 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
321 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
322 Value *Result = ZI->getOperand(0);
Eli Friedman356916e2008-01-29 18:13:51 +0000323 // If there aren't any more uses, zap the instruction to save space.
324 // Note that there can be more uses, for example if this
325 // is the result of an assignment.
326 if (ZI->use_empty())
327 ZI->eraseFromParent();
Chris Lattner9abc84e2007-08-26 16:42:57 +0000328 return Result;
329 }
330 }
331
332 // Compare against an integer or pointer null.
333 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
334 return Builder.CreateICmpNE(Src, Zero, "tobool");
335}
336
Chris Lattner3707b252007-08-26 06:48:56 +0000337/// EmitScalarConversion - Emit a conversion from the specified type to the
338/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000339Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
340 QualType DstType) {
Chris Lattner3707b252007-08-26 06:48:56 +0000341 SrcType = SrcType.getCanonicalType();
342 DstType = DstType.getCanonicalType();
343 if (SrcType == DstType) return Src;
Chris Lattnercf289082007-08-26 07:21:11 +0000344
345 if (DstType->isVoidType()) return 0;
Chris Lattner3707b252007-08-26 06:48:56 +0000346
347 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnered70f0a2007-08-26 16:52:28 +0000348 if (DstType->isBooleanType())
349 return EmitConversionToBool(Src, SrcType);
Chris Lattner3707b252007-08-26 06:48:56 +0000350
351 const llvm::Type *DstTy = ConvertType(DstType);
352
353 // Ignore conversions like int -> uint.
354 if (Src->getType() == DstTy)
355 return Src;
356
357 // Handle pointer conversions next: pointers can only be converted to/from
358 // other pointers and integers.
359 if (isa<PointerType>(DstType)) {
360 // The source value may be an integer, or a pointer.
361 if (isa<llvm::PointerType>(Src->getType()))
362 return Builder.CreateBitCast(Src, DstTy, "conv");
363 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
364 return Builder.CreateIntToPtr(Src, DstTy, "conv");
365 }
366
367 if (isa<PointerType>(SrcType)) {
368 // Must be an ptr to int cast.
369 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson50b5a302007-10-31 23:18:02 +0000370 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000371 }
372
Anders Carlsson79b67f32008-02-01 23:17:55 +0000373 // A scalar source can be splatted to an OCU vector of the same element type
Chris Lattner3b1ae002008-02-02 04:51:41 +0000374 if (DstType->isOCUVectorType() && !isa<VectorType>(SrcType) &&
375 cast<llvm::VectorType>(DstTy)->getElementType() == Src->getType())
Nate Begeman4119d1a2007-12-30 02:59:45 +0000376 return CGF.EmitVector(&Src, DstType->getAsVectorType()->getNumElements(),
377 true);
Nate Begeman4119d1a2007-12-30 02:59:45 +0000378
Chris Lattner3b1ae002008-02-02 04:51:41 +0000379 // Allow bitcast from vector to integer/fp of the same size.
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000380 if (isa<llvm::VectorType>(Src->getType()) ||
Chris Lattner3b1ae002008-02-02 04:51:41 +0000381 isa<llvm::VectorType>(DstTy))
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000382 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000383
Chris Lattner3707b252007-08-26 06:48:56 +0000384 // Finally, we have the arithmetic types: real int/float.
385 if (isa<llvm::IntegerType>(Src->getType())) {
386 bool InputSigned = SrcType->isSignedIntegerType();
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000387 if (isa<llvm::IntegerType>(DstTy))
388 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
389 else if (InputSigned)
390 return Builder.CreateSIToFP(Src, DstTy, "conv");
391 else
392 return Builder.CreateUIToFP(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000393 }
394
395 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
396 if (isa<llvm::IntegerType>(DstTy)) {
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000397 if (DstType->isSignedIntegerType())
398 return Builder.CreateFPToSI(Src, DstTy, "conv");
399 else
400 return Builder.CreateFPToUI(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000401 }
402
403 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000404 if (DstTy->getTypeID() < Src->getType()->getTypeID())
405 return Builder.CreateFPTrunc(Src, DstTy, "conv");
406 else
407 return Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000408}
409
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000410/// EmitComplexToScalarConversion - Emit a conversion from the specified
411/// complex type to the specified destination type, where the destination
412/// type is an LLVM scalar type.
413Value *ScalarExprEmitter::
414EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
415 QualType SrcTy, QualType DstTy) {
Chris Lattnered70f0a2007-08-26 16:52:28 +0000416 // Get the source element type.
417 SrcTy = cast<ComplexType>(SrcTy.getCanonicalType())->getElementType();
418
419 // Handle conversions to bool first, they are special: comparisons against 0.
420 if (DstTy->isBooleanType()) {
421 // Complex != 0 -> (Real != 0) | (Imag != 0)
422 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
423 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
424 return Builder.CreateOr(Src.first, Src.second, "tobool");
425 }
426
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000427 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
428 // the imaginary part of the complex value is discarded and the value of the
429 // real part is converted according to the conversion rules for the
430 // corresponding real type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000431 return EmitScalarConversion(Src.first, SrcTy, DstTy);
432}
433
434
Chris Lattner7f02f722007-08-24 05:35:26 +0000435//===----------------------------------------------------------------------===//
436// Visitor Methods
437//===----------------------------------------------------------------------===//
438
439Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Chris Lattnerdc4d2802007-12-02 01:49:16 +0000440 CGF.WarnUnsupported(E, "scalar expression");
Chris Lattner7f02f722007-08-24 05:35:26 +0000441 if (E->getType()->isVoidType())
442 return 0;
443 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
444}
445
446Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
447 // Emit subscript expressions in rvalue context's. For most cases, this just
448 // loads the lvalue formed by the subscript expr. However, we have to be
449 // careful, because the base of a vector subscript is occasionally an rvalue,
450 // so we can't get it as an lvalue.
451 if (!E->getBase()->getType()->isVectorType())
452 return EmitLoadOfLValue(E);
453
454 // Handle the vector case. The base must be a vector, the index must be an
455 // integer value.
456 Value *Base = Visit(E->getBase());
457 Value *Idx = Visit(E->getIdx());
458
459 // FIXME: Convert Idx to i32 type.
460 return Builder.CreateExtractElement(Base, Idx, "vecext");
461}
462
463/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
464/// also handle things like function to pointer-to-function decay, and array to
465/// pointer decay.
466Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
467 const Expr *Op = E->getSubExpr();
468
469 // If this is due to array->pointer conversion, emit the array expression as
470 // an l-value.
471 if (Op->getType()->isArrayType()) {
472 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
473 // will not true when we add support for VLAs.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000474 Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
Chris Lattner7f02f722007-08-24 05:35:26 +0000475
476 assert(isa<llvm::PointerType>(V->getType()) &&
477 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
478 ->getElementType()) &&
479 "Doesn't support VLAs yet!");
480 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
Ted Kremenekd6278892007-09-04 17:20:08 +0000481
482 llvm::Value *Ops[] = {Idx0, Idx0};
Chris Lattnera9e63722007-12-12 04:13:20 +0000483 V = Builder.CreateGEP(V, Ops, Ops+2, "arraydecay");
484
485 // The resultant pointer type can be implicitly casted to other pointer
486 // types as well, for example void*.
487 const llvm::Type *DestPTy = ConvertType(E->getType());
488 assert(isa<llvm::PointerType>(DestPTy) &&
489 "Only expect implicit cast to pointer");
490 if (V->getType() != DestPTy)
491 V = Builder.CreateBitCast(V, DestPTy, "ptrconv");
492 return V;
493
Anders Carlsson793680e2007-10-12 23:56:29 +0000494 } else if (E->getType()->isReferenceType()) {
Anders Carlsson23af9f22007-10-13 05:52:34 +0000495 assert(cast<ReferenceType>(E->getType().getCanonicalType())->
496 getReferenceeType() ==
497 Op->getType().getCanonicalType() && "Incompatible types!");
Anders Carlsson793680e2007-10-12 23:56:29 +0000498
499 return EmitLValue(Op).getAddress();
Chris Lattner7f02f722007-08-24 05:35:26 +0000500 }
501
502 return EmitCastExpr(Op, E->getType());
503}
504
505
506// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
507// have to handle a more broad range of conversions than explicit casts, as they
508// handle things like function to ptr-to-function decay etc.
509Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
Chris Lattner58a2e942007-08-26 07:26:12 +0000510 // Handle cases where the source is an non-complex type.
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000511
512 if (!CGF.hasAggregateLLVMType(E->getType())) {
Chris Lattner3707b252007-08-26 06:48:56 +0000513 Value *Src = Visit(const_cast<Expr*>(E));
514
Chris Lattner3707b252007-08-26 06:48:56 +0000515 // Use EmitScalarConversion to perform the conversion.
516 return EmitScalarConversion(Src, E->getType(), DestTy);
517 }
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000518
519 if (E->getType()->isComplexType()) {
520 // Handle cases where the source is a complex type.
521 return EmitComplexToScalarConversion(CGF.EmitComplexExpr(E), E->getType(),
522 DestTy);
523 }
Chris Lattner10b00cf2007-08-26 07:16:41 +0000524
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000525 // Okay, this is a cast from an aggregate. It must be a cast to void. Just
526 // evaluate the result and return.
527 CGF.EmitAggExpr(E, 0, false);
528 return 0;
Chris Lattner7f02f722007-08-24 05:35:26 +0000529}
530
Chris Lattner33793202007-08-31 22:09:40 +0000531Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
Chris Lattner9b655512007-08-31 22:49:20 +0000532 return CGF.EmitCompoundStmt(*E->getSubStmt(), true).getScalarVal();
Chris Lattner33793202007-08-31 22:09:40 +0000533}
534
535
Chris Lattner7f02f722007-08-24 05:35:26 +0000536//===----------------------------------------------------------------------===//
537// Unary Operators
538//===----------------------------------------------------------------------===//
539
540Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattnerdfce2a52007-08-24 16:24:49 +0000541 bool isInc, bool isPre) {
Chris Lattner7f02f722007-08-24 05:35:26 +0000542 LValue LV = EmitLValue(E->getSubExpr());
543 // FIXME: Handle volatile!
Chris Lattnere936cc82007-08-26 05:10:16 +0000544 Value *InVal = CGF.EmitLoadOfLValue(LV, // false
Chris Lattner9b655512007-08-31 22:49:20 +0000545 E->getSubExpr()->getType()).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +0000546
547 int AmountVal = isInc ? 1 : -1;
548
549 Value *NextVal;
Chris Lattnere936cc82007-08-26 05:10:16 +0000550 if (isa<llvm::PointerType>(InVal->getType())) {
551 // FIXME: This isn't right for VLAs.
552 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
553 NextVal = Builder.CreateGEP(InVal, NextVal);
554 } else {
555 // Add the inc/dec to the real part.
556 if (isa<llvm::IntegerType>(InVal->getType()))
557 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
Chris Lattnerca2617c2007-09-13 06:19:18 +0000558 else if (InVal->getType() == llvm::Type::FloatTy)
559 // FIXME: Handle long double.
Devang Patele9b8c0a2007-10-30 20:59:40 +0000560 NextVal =
561 llvm::ConstantFP::get(InVal->getType(),
562 llvm::APFloat(static_cast<float>(AmountVal)));
Chris Lattnerca2617c2007-09-13 06:19:18 +0000563 else {
564 // FIXME: Handle long double.
565 assert(InVal->getType() == llvm::Type::DoubleTy);
Devang Patele9b8c0a2007-10-30 20:59:40 +0000566 NextVal =
567 llvm::ConstantFP::get(InVal->getType(),
568 llvm::APFloat(static_cast<double>(AmountVal)));
Chris Lattnerca2617c2007-09-13 06:19:18 +0000569 }
Chris Lattnere936cc82007-08-26 05:10:16 +0000570 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
571 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000572
573 // Store the updated result through the lvalue.
574 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV,
575 E->getSubExpr()->getType());
576
577 // If this is a postinc, return the value read from memory, otherwise use the
578 // updated value.
579 return isPre ? NextVal : InVal;
580}
581
582
583Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
584 Value *Op = Visit(E->getSubExpr());
585 return Builder.CreateNeg(Op, "neg");
586}
587
588Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
589 Value *Op = Visit(E->getSubExpr());
590 return Builder.CreateNot(Op, "neg");
591}
592
593Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
594 // Compare operand to zero.
595 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
596
597 // Invert value.
598 // TODO: Could dynamically modify easy computations here. For example, if
599 // the operand is an icmp ne, turn into icmp eq.
600 BoolVal = Builder.CreateNot(BoolVal, "lnot");
601
602 // ZExt result to int.
603 return Builder.CreateZExt(BoolVal, CGF.LLVMIntTy, "lnot.ext");
604}
605
606/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
607/// an integer (RetType).
608Value *ScalarExprEmitter::EmitSizeAlignOf(QualType TypeToSize,
Chris Lattner46f93d02007-08-24 21:20:17 +0000609 QualType RetType,bool isSizeOf){
Chris Lattnera269ebf2008-02-21 05:45:29 +0000610 assert(RetType->isIntegerType() && "Result type must be an integer!");
611 uint32_t ResultWidth =
612 static_cast<uint32_t>(CGF.getContext().getTypeSize(RetType,
613 SourceLocation()));
614
615 // sizeof(void) and __alignof__(void) = 1 as a gcc extension.
616 if (TypeToSize->isVoidType())
617 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, 1));
618
Chris Lattner7f02f722007-08-24 05:35:26 +0000619 /// FIXME: This doesn't handle VLAs yet!
620 std::pair<uint64_t, unsigned> Info =
621 CGF.getContext().getTypeInfo(TypeToSize, SourceLocation());
622
623 uint64_t Val = isSizeOf ? Info.first : Info.second;
624 Val /= 8; // Return size in bytes, not bits.
625
Chris Lattner7f02f722007-08-24 05:35:26 +0000626 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
627}
628
Chris Lattner46f93d02007-08-24 21:20:17 +0000629Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
630 Expr *Op = E->getSubExpr();
631 if (Op->getType()->isComplexType())
632 return CGF.EmitComplexExpr(Op).first;
633 return Visit(Op);
634}
635Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
636 Expr *Op = E->getSubExpr();
637 if (Op->getType()->isComplexType())
638 return CGF.EmitComplexExpr(Op).second;
Chris Lattner36f84062007-08-26 05:29:21 +0000639
640 // __imag on a scalar returns zero. Emit it the subexpr to ensure side
641 // effects are evaluated.
642 CGF.EmitScalarExpr(Op);
643 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner46f93d02007-08-24 21:20:17 +0000644}
645
Anders Carlsson5a1deb82008-01-29 15:56:48 +0000646Value *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E)
647{
648 int64_t Val = E->evaluateOffsetOf(CGF.getContext());
649
650 assert(E->getType()->isIntegerType() && "Result type must be an integer!");
651
652 uint32_t ResultWidth = static_cast<uint32_t>(
653 CGF.getContext().getTypeSize(E->getType(), SourceLocation()));
654 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
655}
Chris Lattner46f93d02007-08-24 21:20:17 +0000656
Chris Lattner7f02f722007-08-24 05:35:26 +0000657//===----------------------------------------------------------------------===//
658// Binary Operators
659//===----------------------------------------------------------------------===//
660
661BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
662 BinOpInfo Result;
663 Result.LHS = Visit(E->getLHS());
664 Result.RHS = Visit(E->getRHS());
Chris Lattner1f1ded92007-08-24 21:00:35 +0000665 Result.Ty = E->getType();
Chris Lattner7f02f722007-08-24 05:35:26 +0000666 Result.E = E;
667 return Result;
668}
669
Chris Lattner3ccf7742007-08-26 21:41:21 +0000670Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner1f1ded92007-08-24 21:00:35 +0000671 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
672 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
673
674 BinOpInfo OpInfo;
675
676 // Load the LHS and RHS operands.
677 LValue LHSLV = EmitLValue(E->getLHS());
678 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Chris Lattner04dc7642007-08-26 22:37:40 +0000679
680 // Determine the computation type. If the RHS is complex, then this is one of
681 // the add/sub/mul/div operators. All of these operators can be computed in
682 // with just their real component even though the computation domain really is
683 // complex.
Chris Lattner3ccf7742007-08-26 21:41:21 +0000684 QualType ComputeType = E->getComputationType();
Chris Lattner1f1ded92007-08-24 21:00:35 +0000685
Chris Lattner04dc7642007-08-26 22:37:40 +0000686 // If the computation type is complex, then the RHS is complex. Emit the RHS.
687 if (const ComplexType *CT = ComputeType->getAsComplexType()) {
688 ComputeType = CT->getElementType();
689
690 // Emit the RHS, only keeping the real component.
691 OpInfo.RHS = CGF.EmitComplexExpr(E->getRHS()).first;
692 RHSTy = RHSTy->getAsComplexType()->getElementType();
693 } else {
694 // Otherwise the RHS is a simple scalar value.
695 OpInfo.RHS = Visit(E->getRHS());
696 }
697
698 // Convert the LHS/RHS values to the computation type.
Chris Lattnere9377122007-08-26 07:08:39 +0000699 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, ComputeType);
Chris Lattner1f1ded92007-08-24 21:00:35 +0000700
Devang Patelf86206f2007-10-25 22:19:13 +0000701 // Do not merge types for -= or += where the LHS is a pointer.
702 if (!(E->getOpcode() == BinaryOperator::SubAssign ||
Devang Patel03f7c032007-10-30 18:31:12 +0000703 E->getOpcode() == BinaryOperator::AddAssign) ||
Chris Lattner3b44b572007-08-25 21:56:20 +0000704 !E->getLHS()->getType()->isPointerType()) {
Chris Lattnere9377122007-08-26 07:08:39 +0000705 OpInfo.RHS = EmitScalarConversion(OpInfo.RHS, RHSTy, ComputeType);
Chris Lattner1f1ded92007-08-24 21:00:35 +0000706 }
707 OpInfo.Ty = ComputeType;
708 OpInfo.E = E;
709
710 // Expand the binary operator.
711 Value *Result = (this->*Func)(OpInfo);
712
713 // Truncate the result back to the LHS type.
Chris Lattnere9377122007-08-26 07:08:39 +0000714 Result = EmitScalarConversion(Result, ComputeType, LHSTy);
Chris Lattner1f1ded92007-08-24 21:00:35 +0000715
716 // Store the result value into the LHS lvalue.
717 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, E->getType());
718
719 return Result;
720}
721
722
Chris Lattner7f02f722007-08-24 05:35:26 +0000723Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Nate Begemanb3ab8dc2007-12-30 01:28:16 +0000724 if (Ops.LHS->getType()->isFPOrFPVector())
Chris Lattner7f02f722007-08-24 05:35:26 +0000725 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner1f1ded92007-08-24 21:00:35 +0000726 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner7f02f722007-08-24 05:35:26 +0000727 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
728 else
729 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
730}
731
732Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
733 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner1f1ded92007-08-24 21:00:35 +0000734 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner7f02f722007-08-24 05:35:26 +0000735 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
736 else
737 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
738}
739
740
741Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Chris Lattner1f1ded92007-08-24 21:00:35 +0000742 if (!Ops.Ty->isPointerType())
Chris Lattner7f02f722007-08-24 05:35:26 +0000743 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Chris Lattner1f1ded92007-08-24 21:00:35 +0000744
745 // FIXME: What about a pointer to a VLA?
Chris Lattner8f925282008-01-03 06:36:51 +0000746 Value *Ptr, *Idx;
747 Expr *IdxExp;
748 if (isa<llvm::PointerType>(Ops.LHS->getType())) { // pointer + int
749 Ptr = Ops.LHS;
750 Idx = Ops.RHS;
751 IdxExp = Ops.E->getRHS();
752 } else { // int + pointer
753 Ptr = Ops.RHS;
754 Idx = Ops.LHS;
755 IdxExp = Ops.E->getLHS();
756 }
757
758 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
759 if (Width < CGF.LLVMPointerWidth) {
760 // Zero or sign extend the pointer value based on whether the index is
761 // signed or not.
762 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
763 if (IdxExp->getType().getCanonicalType()->isSignedIntegerType())
764 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
765 else
766 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
767 }
768
769 return Builder.CreateGEP(Ptr, Idx, "add.ptr");
Chris Lattner7f02f722007-08-24 05:35:26 +0000770}
771
772Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
773 if (!isa<llvm::PointerType>(Ops.LHS->getType()))
774 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
775
Chris Lattner1f1ded92007-08-24 21:00:35 +0000776 // pointer - int
777 assert(!isa<llvm::PointerType>(Ops.RHS->getType()) &&
778 "ptr-ptr shouldn't get here");
779 // FIXME: The pointer could point to a VLA.
Chris Lattner6860f3c2008-01-31 04:12:50 +0000780 Value *Idx = Builder.CreateNeg(Ops.RHS, "sub.ptr.neg");
781
782 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
783 if (Width < CGF.LLVMPointerWidth) {
784 // Zero or sign extend the pointer value based on whether the index is
785 // signed or not.
786 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
787 if (Ops.E->getRHS()->getType().getCanonicalType()->isSignedIntegerType())
788 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
789 else
790 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
791 }
792
793 return Builder.CreateGEP(Ops.LHS, Idx, "sub.ptr");
Chris Lattner1f1ded92007-08-24 21:00:35 +0000794}
795
796Value *ScalarExprEmitter::VisitBinSub(const BinaryOperator *E) {
797 // "X - Y" is different from "X -= Y" in one case: when Y is a pointer. In
798 // the compound assignment case it is invalid, so just handle it here.
799 if (!E->getRHS()->getType()->isPointerType())
800 return EmitSub(EmitBinOps(E));
Chris Lattner7f02f722007-08-24 05:35:26 +0000801
802 // pointer - pointer
Chris Lattner1f1ded92007-08-24 21:00:35 +0000803 Value *LHS = Visit(E->getLHS());
804 Value *RHS = Visit(E->getRHS());
805
Seo Sanghyeonec86b972007-12-03 06:23:43 +0000806 const QualType LHSType = E->getLHS()->getType().getCanonicalType();
Seo Sanghyeon9bb947a2007-12-26 05:21:37 +0000807 const QualType LHSElementType = cast<PointerType>(LHSType)->getPointeeType();
Chris Lattner7f02f722007-08-24 05:35:26 +0000808 uint64_t ElementSize = CGF.getContext().getTypeSize(LHSElementType,
809 SourceLocation()) / 8;
Chris Lattner1f1ded92007-08-24 21:00:35 +0000810
811 const llvm::Type *ResultType = ConvertType(E->getType());
812 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
813 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
814 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Chris Lattner7f02f722007-08-24 05:35:26 +0000815
816 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
817 // remainder. As such, we handle common power-of-two cases here to generate
818 // better code.
819 if (llvm::isPowerOf2_64(ElementSize)) {
820 Value *ShAmt =
821 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
822 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
823 }
Chris Lattner1f1ded92007-08-24 21:00:35 +0000824
Chris Lattner7f02f722007-08-24 05:35:26 +0000825 // Otherwise, do a full sdiv.
826 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
827 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
828}
829
Chris Lattner1f1ded92007-08-24 21:00:35 +0000830
Chris Lattner7f02f722007-08-24 05:35:26 +0000831Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
832 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
833 // RHS to the same size as the LHS.
834 Value *RHS = Ops.RHS;
835 if (Ops.LHS->getType() != RHS->getType())
836 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
837
838 return Builder.CreateShl(Ops.LHS, RHS, "shl");
839}
840
841Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
842 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
843 // RHS to the same size as the LHS.
844 Value *RHS = Ops.RHS;
845 if (Ops.LHS->getType() != RHS->getType())
846 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
847
Chris Lattner1f1ded92007-08-24 21:00:35 +0000848 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner7f02f722007-08-24 05:35:26 +0000849 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
850 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
851}
852
853Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
854 unsigned SICmpOpc, unsigned FCmpOpc) {
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000855 Value *Result;
Chris Lattner7f02f722007-08-24 05:35:26 +0000856 QualType LHSTy = E->getLHS()->getType();
857 if (!LHSTy->isComplexType()) {
858 Value *LHS = Visit(E->getLHS());
859 Value *RHS = Visit(E->getRHS());
860
861 if (LHS->getType()->isFloatingPoint()) {
862 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
863 LHS, RHS, "cmp");
864 } else if (LHSTy->isUnsignedIntegerType()) {
865 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
866 LHS, RHS, "cmp");
867 } else {
868 // Signed integers and pointers.
869 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
870 LHS, RHS, "cmp");
871 }
872 } else {
873 // Complex Comparison: can only be an equality comparison.
874 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
875 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
876
877 QualType CETy =
878 cast<ComplexType>(LHSTy.getCanonicalType())->getElementType();
879
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000880 Value *ResultR, *ResultI;
Chris Lattner7f02f722007-08-24 05:35:26 +0000881 if (CETy->isRealFloatingType()) {
882 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
883 LHS.first, RHS.first, "cmp.r");
884 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
885 LHS.second, RHS.second, "cmp.i");
886 } else {
887 // Complex comparisons can only be equality comparisons. As such, signed
888 // and unsigned opcodes are the same.
889 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
890 LHS.first, RHS.first, "cmp.r");
891 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
892 LHS.second, RHS.second, "cmp.i");
893 }
894
895 if (E->getOpcode() == BinaryOperator::EQ) {
896 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
897 } else {
898 assert(E->getOpcode() == BinaryOperator::NE &&
899 "Complex comparison other than == or != ?");
900 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
901 }
902 }
903
904 // ZExt result to int.
905 return Builder.CreateZExt(Result, CGF.LLVMIntTy, "cmp.ext");
906}
907
908Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
909 LValue LHS = EmitLValue(E->getLHS());
910 Value *RHS = Visit(E->getRHS());
911
912 // Store the value into the LHS.
913 // FIXME: Volatility!
914 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
915
916 // Return the RHS.
917 return RHS;
918}
919
920Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
921 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
922
923 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
924 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
925
926 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
927 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
928
929 CGF.EmitBlock(RHSBlock);
930 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
931
932 // Reaquire the RHS block, as there may be subblocks inserted.
933 RHSBlock = Builder.GetInsertBlock();
934 CGF.EmitBlock(ContBlock);
935
936 // Create a PHI node. If we just evaluted the LHS condition, the result is
937 // false. If we evaluated both, the result is the RHS condition.
938 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
939 PN->reserveOperandSpace(2);
940 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
941 PN->addIncoming(RHSCond, RHSBlock);
942
943 // ZExt result to int.
944 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
945}
946
947Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
948 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
949
950 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
951 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
952
953 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
954 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
955
956 CGF.EmitBlock(RHSBlock);
957 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
958
959 // Reaquire the RHS block, as there may be subblocks inserted.
960 RHSBlock = Builder.GetInsertBlock();
961 CGF.EmitBlock(ContBlock);
962
963 // Create a PHI node. If we just evaluted the LHS condition, the result is
964 // true. If we evaluated both, the result is the RHS condition.
965 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
966 PN->reserveOperandSpace(2);
967 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
968 PN->addIncoming(RHSCond, RHSBlock);
969
970 // ZExt result to int.
971 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
972}
973
974Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
975 CGF.EmitStmt(E->getLHS());
976 return Visit(E->getRHS());
977}
978
979//===----------------------------------------------------------------------===//
980// Other Operators
981//===----------------------------------------------------------------------===//
982
983Value *ScalarExprEmitter::
984VisitConditionalOperator(const ConditionalOperator *E) {
985 llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
986 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
987 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
988
Chris Lattnera21ddb32007-11-26 01:40:58 +0000989 // Evaluate the conditional, then convert it to bool. We do this explicitly
990 // because we need the unconverted value if this is a GNU ?: expression with
991 // missing middle value.
992 Value *CondVal = CGF.EmitScalarExpr(E->getCond());
Chris Lattnerc89bf692008-01-03 07:05:49 +0000993 Value *CondBoolVal =CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
994 CGF.getContext().BoolTy);
Chris Lattnera21ddb32007-11-26 01:40:58 +0000995 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +0000996
997 CGF.EmitBlock(LHSBlock);
998
999 // Handle the GNU extension for missing LHS.
Chris Lattnera21ddb32007-11-26 01:40:58 +00001000 Value *LHS;
1001 if (E->getLHS())
1002 LHS = Visit(E->getLHS());
1003 else // Perform promotions, to handle cases like "short ?: int"
1004 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
1005
Chris Lattner7f02f722007-08-24 05:35:26 +00001006 Builder.CreateBr(ContBlock);
1007 LHSBlock = Builder.GetInsertBlock();
1008
1009 CGF.EmitBlock(RHSBlock);
1010
1011 Value *RHS = Visit(E->getRHS());
1012 Builder.CreateBr(ContBlock);
1013 RHSBlock = Builder.GetInsertBlock();
1014
1015 CGF.EmitBlock(ContBlock);
1016
Chris Lattner2202bce2007-11-30 17:56:23 +00001017 if (!LHS) {
1018 assert(E->getType()->isVoidType() && "Non-void value should have a value");
1019 return 0;
1020 }
1021
Chris Lattner7f02f722007-08-24 05:35:26 +00001022 // Create a PHI node for the real part.
1023 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
1024 PN->reserveOperandSpace(2);
1025 PN->addIncoming(LHS, LHSBlock);
1026 PN->addIncoming(RHS, RHSBlock);
1027 return PN;
1028}
1029
1030Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Chris Lattner7f02f722007-08-24 05:35:26 +00001031 // Emit the LHS or RHS as appropriate.
Devang Patele9b8c0a2007-10-30 20:59:40 +00001032 return
1033 Visit(E->isConditionTrue(CGF.getContext()) ? E->getLHS() : E->getRHS());
Chris Lattner7f02f722007-08-24 05:35:26 +00001034}
1035
Nate Begemane2ce1d92008-01-17 17:46:27 +00001036Value *ScalarExprEmitter::VisitOverloadExpr(OverloadExpr *E) {
Nate Begeman67295d02008-01-30 20:50:20 +00001037 return CGF.EmitCallExpr(E->getFn(), E->arg_begin(),
1038 E->getNumArgs(CGF.getContext())).getScalarVal();
Nate Begemane2ce1d92008-01-17 17:46:27 +00001039}
1040
Chris Lattner2202bce2007-11-30 17:56:23 +00001041Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Anders Carlsson7c50aca2007-10-15 20:28:48 +00001042 llvm::Value *ArgValue = EmitLValue(VE->getSubExpr()).getAddress();
1043
1044 llvm::Value *V = Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
1045 return V;
1046}
1047
Chris Lattner2202bce2007-11-30 17:56:23 +00001048Value *ScalarExprEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001049 std::string str;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00001050 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
1051 CGF.getContext().getObjCEncodingForType(E->getEncodedType(), str,
1052 EncodingRecordTypes);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001053
1054 llvm::Constant *C = llvm::ConstantArray::get(str);
1055 C = new llvm::GlobalVariable(C->getType(), true,
1056 llvm::GlobalValue::InternalLinkage,
1057 C, ".str", &CGF.CGM.getModule());
1058 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
1059 llvm::Constant *Zeros[] = { Zero, Zero };
1060 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
1061
1062 return C;
1063}
1064
Chris Lattner7f02f722007-08-24 05:35:26 +00001065//===----------------------------------------------------------------------===//
1066// Entry Point into this File
1067//===----------------------------------------------------------------------===//
1068
1069/// EmitComplexExpr - Emit the computation of the specified expression of
1070/// complex type, ignoring the result.
1071Value *CodeGenFunction::EmitScalarExpr(const Expr *E) {
1072 assert(E && !hasAggregateLLVMType(E->getType()) &&
1073 "Invalid scalar expression to emit");
1074
1075 return ScalarExprEmitter(*this).Visit(const_cast<Expr*>(E));
1076}
Chris Lattner3707b252007-08-26 06:48:56 +00001077
1078/// EmitScalarConversion - Emit a conversion from the specified type to the
1079/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001080Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
1081 QualType DstTy) {
Chris Lattner3707b252007-08-26 06:48:56 +00001082 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
1083 "Invalid scalar expression to emit");
1084 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
1085}
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001086
1087/// EmitComplexToScalarConversion - Emit a conversion from the specified
1088/// complex type to the specified destination type, where the destination
1089/// type is an LLVM scalar type.
1090Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
1091 QualType SrcTy,
1092 QualType DstTy) {
1093 assert(SrcTy->isComplexType() && !hasAggregateLLVMType(DstTy) &&
1094 "Invalid complex -> scalar conversion");
1095 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
1096 DstTy);
1097}
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001098
1099Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) {
1100 assert(V1->getType() == V2->getType() &&
1101 "Vector operands must be of the same type");
1102
1103 unsigned NumElements =
1104 cast<llvm::VectorType>(V1->getType())->getNumElements();
1105
1106 va_list va;
1107 va_start(va, V2);
1108
1109 llvm::SmallVector<llvm::Constant*, 16> Args;
1110
1111 for (unsigned i = 0; i < NumElements; i++) {
1112 int n = va_arg(va, int);
1113
1114 assert(n >= 0 && n < (int)NumElements * 2 &&
1115 "Vector shuffle index out of bounds!");
1116
1117 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, n));
1118 }
1119
1120 const char *Name = va_arg(va, const char *);
1121 va_end(va);
1122
1123 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
1124
1125 return Builder.CreateShuffleVector(V1, V2, Mask, Name);
1126}
1127
Anders Carlsson6086bbd2007-12-15 21:23:30 +00001128llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals,
Nate Begeman4119d1a2007-12-30 02:59:45 +00001129 unsigned NumVals, bool isSplat)
Anders Carlsson6086bbd2007-12-15 21:23:30 +00001130{
Anders Carlsson6086bbd2007-12-15 21:23:30 +00001131 llvm::Value *Vec
1132 = llvm::UndefValue::get(llvm::VectorType::get(Vals[0]->getType(), NumVals));
1133
1134 for (unsigned i = 0, e = NumVals ; i != e; ++i) {
Nate Begeman4119d1a2007-12-30 02:59:45 +00001135 llvm::Value *Val = isSplat ? Vals[0] : Vals[i];
Anders Carlsson6086bbd2007-12-15 21:23:30 +00001136 llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
Nate Begeman4119d1a2007-12-30 02:59:45 +00001137 Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp");
Anders Carlsson6086bbd2007-12-15 21:23:30 +00001138 }
1139
1140 return Vec;
1141}