CGExprScalar.cpp revision 3f70456b8adb0405ef2a47d51f9fc2d5937ae8ae
1//===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
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/ASTContext.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/AST/StmtVisitor.h"
19#include "clang/Basic/TargetInfo.h"
20#include "llvm/Constants.h"
21#include "llvm/Function.h"
22#include "llvm/GlobalVariable.h"
23#include "llvm/Intrinsics.h"
24#include "llvm/Support/Compiler.h"
25#include "llvm/Support/CFG.h"
26#include <cstdarg>
27
28using namespace clang;
29using namespace CodeGen;
30using llvm::Value;
31
32//===----------------------------------------------------------------------===//
33//                         Scalar Expression Emitter
34//===----------------------------------------------------------------------===//
35
36struct BinOpInfo {
37  Value *LHS;
38  Value *RHS;
39  QualType Ty;  // Computation Type.
40  const BinaryOperator *E;
41};
42
43namespace {
44class VISIBILITY_HIDDEN ScalarExprEmitter
45  : public StmtVisitor<ScalarExprEmitter, Value*> {
46  CodeGenFunction &CGF;
47  CGBuilderTy &Builder;
48
49public:
50
51  ScalarExprEmitter(CodeGenFunction &cgf) : CGF(cgf),
52    Builder(CGF.Builder) {
53  }
54
55  //===--------------------------------------------------------------------===//
56  //                               Utilities
57  //===--------------------------------------------------------------------===//
58
59  const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
60  LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
61
62  Value *EmitLoadOfLValue(LValue LV, QualType T) {
63    return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
64  }
65
66  /// EmitLoadOfLValue - Given an expression with complex type that represents a
67  /// value l-value, this method emits the address of the l-value, then loads
68  /// and returns the result.
69  Value *EmitLoadOfLValue(const Expr *E) {
70    // FIXME: Volatile
71    return EmitLoadOfLValue(EmitLValue(E), E->getType());
72  }
73
74  /// EmitConversionToBool - Convert the specified expression value to a
75  /// boolean (i1) truth value.  This is equivalent to "Val != 0".
76  Value *EmitConversionToBool(Value *Src, QualType DstTy);
77
78  /// EmitScalarConversion - Emit a conversion from the specified type to the
79  /// specified destination type, both of which are LLVM scalar types.
80  Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
81
82  /// EmitComplexToScalarConversion - Emit a conversion from the specified
83  /// complex type to the specified destination type, where the destination
84  /// type is an LLVM scalar type.
85  Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
86                                       QualType SrcTy, QualType DstTy);
87
88  //===--------------------------------------------------------------------===//
89  //                            Visitor Methods
90  //===--------------------------------------------------------------------===//
91
92  Value *VisitStmt(Stmt *S) {
93    S->dump(CGF.getContext().getSourceManager());
94    assert(0 && "Stmt can't have complex result type!");
95    return 0;
96  }
97  Value *VisitExpr(Expr *S);
98  Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
99
100  // Leaves.
101  Value *VisitIntegerLiteral(const IntegerLiteral *E) {
102    return llvm::ConstantInt::get(E->getValue());
103  }
104  Value *VisitFloatingLiteral(const FloatingLiteral *E) {
105    return llvm::ConstantFP::get(E->getValue());
106  }
107  Value *VisitCharacterLiteral(const CharacterLiteral *E) {
108    return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
109  }
110  Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
111    return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
112  }
113  Value *VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
114    return llvm::Constant::getNullValue(ConvertType(E->getType()));
115  }
116  Value *VisitGNUNullExpr(const GNUNullExpr *E) {
117    return llvm::Constant::getNullValue(ConvertType(E->getType()));
118  }
119  Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
120    return llvm::ConstantInt::get(ConvertType(E->getType()),
121                                  CGF.getContext().typesAreCompatible(
122                                    E->getArgType1(), E->getArgType2()));
123  }
124  Value *VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
125  Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
126    llvm::Value *V =
127      llvm::ConstantInt::get(llvm::Type::Int32Ty,
128                             CGF.GetIDForAddrOfLabel(E->getLabel()));
129
130    return Builder.CreateIntToPtr(V, ConvertType(E->getType()));
131  }
132
133  // l-values.
134  Value *VisitDeclRefExpr(DeclRefExpr *E) {
135    if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(E->getDecl()))
136      return llvm::ConstantInt::get(EC->getInitVal());
137    return EmitLoadOfLValue(E);
138  }
139  Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
140    return CGF.EmitObjCSelectorExpr(E);
141  }
142  Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
143    return CGF.EmitObjCProtocolExpr(E);
144  }
145  Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
146    return EmitLoadOfLValue(E);
147  }
148  Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
149    return EmitLoadOfLValue(E);
150  }
151  Value *VisitObjCKVCRefExpr(ObjCKVCRefExpr *E) {
152    return EmitLoadOfLValue(E);
153  }
154  Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
155    return CGF.EmitObjCMessageExpr(E).getScalarVal();
156  }
157
158  Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
159  Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
160  Value *VisitMemberExpr(Expr *E)           { return EmitLoadOfLValue(E); }
161  Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
162  Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
163    return EmitLoadOfLValue(E);
164  }
165  Value *VisitStringLiteral(Expr *E)  { return EmitLValue(E).getAddress(); }
166  Value *VisitPredefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); }
167
168  Value *VisitInitListExpr(InitListExpr *E) {
169    unsigned NumInitElements = E->getNumInits();
170
171    const llvm::VectorType *VType =
172      dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
173
174    // We have a scalar in braces. Just use the first element.
175    if (!VType)
176      return Visit(E->getInit(0));
177
178    if (E->hadDesignators()) {
179      CGF.ErrorUnsupported(E, "initializer list with designators");
180      return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
181    }
182
183    unsigned NumVectorElements = VType->getNumElements();
184    const llvm::Type *ElementType = VType->getElementType();
185
186    // Emit individual vector element stores.
187    llvm::Value *V = llvm::UndefValue::get(VType);
188
189    // Emit initializers
190    unsigned i;
191    for (i = 0; i < NumInitElements; ++i) {
192      Value *NewV = Visit(E->getInit(i));
193      Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
194      V = Builder.CreateInsertElement(V, NewV, Idx);
195    }
196
197    // Emit remaining default initializers
198    for (/* Do not initialize i*/; i < NumVectorElements; ++i) {
199      Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
200      llvm::Value *NewV = llvm::Constant::getNullValue(ElementType);
201      V = Builder.CreateInsertElement(V, NewV, Idx);
202    }
203
204    return V;
205  }
206
207  Value *VisitImplicitCastExpr(const ImplicitCastExpr *E);
208  Value *VisitCastExpr(const CastExpr *E) {
209    return EmitCastExpr(E->getSubExpr(), E->getType());
210  }
211  Value *EmitCastExpr(const Expr *E, QualType T);
212
213  Value *VisitCallExpr(const CallExpr *E) {
214    return CGF.EmitCallExpr(E).getScalarVal();
215  }
216
217  Value *VisitStmtExpr(const StmtExpr *E);
218
219  // Unary Operators.
220  Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre);
221  Value *VisitUnaryPostDec(const UnaryOperator *E) {
222    return VisitPrePostIncDec(E, false, false);
223  }
224  Value *VisitUnaryPostInc(const UnaryOperator *E) {
225    return VisitPrePostIncDec(E, true, false);
226  }
227  Value *VisitUnaryPreDec(const UnaryOperator *E) {
228    return VisitPrePostIncDec(E, false, true);
229  }
230  Value *VisitUnaryPreInc(const UnaryOperator *E) {
231    return VisitPrePostIncDec(E, true, true);
232  }
233  Value *VisitUnaryAddrOf(const UnaryOperator *E) {
234    return EmitLValue(E->getSubExpr()).getAddress();
235  }
236  Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
237  Value *VisitUnaryPlus(const UnaryOperator *E) {
238    return Visit(E->getSubExpr());
239  }
240  Value *VisitUnaryMinus    (const UnaryOperator *E);
241  Value *VisitUnaryNot      (const UnaryOperator *E);
242  Value *VisitUnaryLNot     (const UnaryOperator *E);
243  Value *VisitUnaryReal     (const UnaryOperator *E);
244  Value *VisitUnaryImag     (const UnaryOperator *E);
245  Value *VisitUnaryExtension(const UnaryOperator *E) {
246    return Visit(E->getSubExpr());
247  }
248  Value *VisitUnaryOffsetOf(const UnaryOperator *E);
249  Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
250    return Visit(DAE->getExpr());
251  }
252
253  // Binary Operators.
254  Value *EmitMul(const BinOpInfo &Ops) {
255    return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
256  }
257  Value *EmitDiv(const BinOpInfo &Ops);
258  Value *EmitRem(const BinOpInfo &Ops);
259  Value *EmitAdd(const BinOpInfo &Ops);
260  Value *EmitSub(const BinOpInfo &Ops);
261  Value *EmitShl(const BinOpInfo &Ops);
262  Value *EmitShr(const BinOpInfo &Ops);
263  Value *EmitAnd(const BinOpInfo &Ops) {
264    return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
265  }
266  Value *EmitXor(const BinOpInfo &Ops) {
267    return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
268  }
269  Value *EmitOr (const BinOpInfo &Ops) {
270    return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
271  }
272
273  BinOpInfo EmitBinOps(const BinaryOperator *E);
274  Value *EmitCompoundAssign(const CompoundAssignOperator *E,
275                            Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
276
277  // Binary operators and binary compound assignment operators.
278#define HANDLEBINOP(OP) \
279  Value *VisitBin ## OP(const BinaryOperator *E) {                         \
280    return Emit ## OP(EmitBinOps(E));                                      \
281  }                                                                        \
282  Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) {       \
283    return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP);          \
284  }
285  HANDLEBINOP(Mul);
286  HANDLEBINOP(Div);
287  HANDLEBINOP(Rem);
288  HANDLEBINOP(Add);
289  HANDLEBINOP(Sub);
290  HANDLEBINOP(Shl);
291  HANDLEBINOP(Shr);
292  HANDLEBINOP(And);
293  HANDLEBINOP(Xor);
294  HANDLEBINOP(Or);
295#undef HANDLEBINOP
296
297  // Comparisons.
298  Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
299                     unsigned SICmpOpc, unsigned FCmpOpc);
300#define VISITCOMP(CODE, UI, SI, FP) \
301    Value *VisitBin##CODE(const BinaryOperator *E) { \
302      return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
303                         llvm::FCmpInst::FP); }
304  VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
305  VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
306  VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
307  VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
308  VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
309  VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
310#undef VISITCOMP
311
312  Value *VisitBinAssign     (const BinaryOperator *E);
313
314  Value *VisitBinLAnd       (const BinaryOperator *E);
315  Value *VisitBinLOr        (const BinaryOperator *E);
316  Value *VisitBinComma      (const BinaryOperator *E);
317
318  // Other Operators.
319  Value *VisitConditionalOperator(const ConditionalOperator *CO);
320  Value *VisitChooseExpr(ChooseExpr *CE);
321  Value *VisitOverloadExpr(OverloadExpr *OE);
322  Value *VisitVAArgExpr(VAArgExpr *VE);
323  Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
324    return CGF.EmitObjCStringLiteral(E);
325  }
326  Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
327};
328}  // end anonymous namespace.
329
330//===----------------------------------------------------------------------===//
331//                                Utilities
332//===----------------------------------------------------------------------===//
333
334/// EmitConversionToBool - Convert the specified expression value to a
335/// boolean (i1) truth value.  This is equivalent to "Val != 0".
336Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
337  assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs");
338
339  if (SrcType->isRealFloatingType()) {
340    // Compare against 0.0 for fp scalars.
341    llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
342    return Builder.CreateFCmpUNE(Src, Zero, "tobool");
343  }
344
345  assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
346         "Unknown scalar type to convert");
347
348  // Because of the type rules of C, we often end up computing a logical value,
349  // then zero extending it to int, then wanting it as a logical value again.
350  // Optimize this common case.
351  if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
352    if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
353      Value *Result = ZI->getOperand(0);
354      // If there aren't any more uses, zap the instruction to save space.
355      // Note that there can be more uses, for example if this
356      // is the result of an assignment.
357      if (ZI->use_empty())
358        ZI->eraseFromParent();
359      return Result;
360    }
361  }
362
363  // Compare against an integer or pointer null.
364  llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
365  return Builder.CreateICmpNE(Src, Zero, "tobool");
366}
367
368/// EmitScalarConversion - Emit a conversion from the specified type to the
369/// specified destination type, both of which are LLVM scalar types.
370Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
371                                               QualType DstType) {
372  SrcType = CGF.getContext().getCanonicalType(SrcType);
373  DstType = CGF.getContext().getCanonicalType(DstType);
374  if (SrcType == DstType) return Src;
375
376  if (DstType->isVoidType()) return 0;
377
378  // Handle conversions to bool first, they are special: comparisons against 0.
379  if (DstType->isBooleanType())
380    return EmitConversionToBool(Src, SrcType);
381
382  const llvm::Type *DstTy = ConvertType(DstType);
383
384  // Ignore conversions like int -> uint.
385  if (Src->getType() == DstTy)
386    return Src;
387
388  // Handle pointer conversions next: pointers can only be converted
389  // to/from other pointers and integers. Check for pointer types in
390  // terms of LLVM, as some native types (like Obj-C id) may map to a
391  // pointer type.
392  if (isa<llvm::PointerType>(DstTy)) {
393    // The source value may be an integer, or a pointer.
394    if (isa<llvm::PointerType>(Src->getType()))
395      return Builder.CreateBitCast(Src, DstTy, "conv");
396    assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
397    return Builder.CreateIntToPtr(Src, DstTy, "conv");
398  }
399
400  if (isa<llvm::PointerType>(Src->getType())) {
401    // Must be an ptr to int cast.
402    assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
403    return Builder.CreatePtrToInt(Src, DstTy, "conv");
404  }
405
406  // A scalar can be splatted to an extended vector of the same element type
407  if (DstType->isExtVectorType() && !isa<VectorType>(SrcType) &&
408      cast<llvm::VectorType>(DstTy)->getElementType() == Src->getType())
409    return CGF.EmitVector(&Src, DstType->getAsVectorType()->getNumElements(),
410                          true);
411
412  // Allow bitcast from vector to integer/fp of the same size.
413  if (isa<llvm::VectorType>(Src->getType()) ||
414      isa<llvm::VectorType>(DstTy))
415    return Builder.CreateBitCast(Src, DstTy, "conv");
416
417  // Finally, we have the arithmetic types: real int/float.
418  if (isa<llvm::IntegerType>(Src->getType())) {
419    bool InputSigned = SrcType->isSignedIntegerType();
420    if (isa<llvm::IntegerType>(DstTy))
421      return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
422    else if (InputSigned)
423      return Builder.CreateSIToFP(Src, DstTy, "conv");
424    else
425      return Builder.CreateUIToFP(Src, DstTy, "conv");
426  }
427
428  assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
429  if (isa<llvm::IntegerType>(DstTy)) {
430    if (DstType->isSignedIntegerType())
431      return Builder.CreateFPToSI(Src, DstTy, "conv");
432    else
433      return Builder.CreateFPToUI(Src, DstTy, "conv");
434  }
435
436  assert(DstTy->isFloatingPoint() && "Unknown real conversion");
437  if (DstTy->getTypeID() < Src->getType()->getTypeID())
438    return Builder.CreateFPTrunc(Src, DstTy, "conv");
439  else
440    return Builder.CreateFPExt(Src, DstTy, "conv");
441}
442
443/// EmitComplexToScalarConversion - Emit a conversion from the specified
444/// complex type to the specified destination type, where the destination
445/// type is an LLVM scalar type.
446Value *ScalarExprEmitter::
447EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
448                              QualType SrcTy, QualType DstTy) {
449  // Get the source element type.
450  SrcTy = SrcTy->getAsComplexType()->getElementType();
451
452  // Handle conversions to bool first, they are special: comparisons against 0.
453  if (DstTy->isBooleanType()) {
454    //  Complex != 0  -> (Real != 0) | (Imag != 0)
455    Src.first  = EmitScalarConversion(Src.first, SrcTy, DstTy);
456    Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
457    return Builder.CreateOr(Src.first, Src.second, "tobool");
458  }
459
460  // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
461  // the imaginary part of the complex value is discarded and the value of the
462  // real part is converted according to the conversion rules for the
463  // corresponding real type.
464  return EmitScalarConversion(Src.first, SrcTy, DstTy);
465}
466
467
468//===----------------------------------------------------------------------===//
469//                            Visitor Methods
470//===----------------------------------------------------------------------===//
471
472Value *ScalarExprEmitter::VisitExpr(Expr *E) {
473  CGF.ErrorUnsupported(E, "scalar expression");
474  if (E->getType()->isVoidType())
475    return 0;
476  return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
477}
478
479Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
480  llvm::SmallVector<llvm::Constant*, 32> indices;
481  for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
482    indices.push_back(cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i))));
483  }
484  Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
485  Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
486  Value* SV = llvm::ConstantVector::get(indices.begin(), indices.size());
487  return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
488}
489
490Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
491  // Emit subscript expressions in rvalue context's.  For most cases, this just
492  // loads the lvalue formed by the subscript expr.  However, we have to be
493  // careful, because the base of a vector subscript is occasionally an rvalue,
494  // so we can't get it as an lvalue.
495  if (!E->getBase()->getType()->isVectorType())
496    return EmitLoadOfLValue(E);
497
498  // Handle the vector case.  The base must be a vector, the index must be an
499  // integer value.
500  Value *Base = Visit(E->getBase());
501  Value *Idx  = Visit(E->getIdx());
502
503  // FIXME: Convert Idx to i32 type.
504  return Builder.CreateExtractElement(Base, Idx, "vecext");
505}
506
507/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
508/// also handle things like function to pointer-to-function decay, and array to
509/// pointer decay.
510Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
511  const Expr *Op = E->getSubExpr();
512
513  // If this is due to array->pointer conversion, emit the array expression as
514  // an l-value.
515  if (Op->getType()->isArrayType()) {
516    // FIXME: For now we assume that all source arrays map to LLVM arrays.  This
517    // will not true when we add support for VLAs.
518    Value *V = EmitLValue(Op).getAddress();  // Bitfields can't be arrays.
519
520    if (!Op->getType()->isVariableArrayType()) {
521      assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
522      assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
523                                 ->getElementType()) &&
524             "Expected pointer to array");
525      V = Builder.CreateStructGEP(V, 0, "arraydecay");
526    }
527
528    // The resultant pointer type can be implicitly casted to other pointer
529    // types as well (e.g. void*) and can be implicitly converted to integer.
530    const llvm::Type *DestTy = ConvertType(E->getType());
531    if (V->getType() != DestTy) {
532      if (isa<llvm::PointerType>(DestTy))
533        V = Builder.CreateBitCast(V, DestTy, "ptrconv");
534      else {
535        assert(isa<llvm::IntegerType>(DestTy) && "Unknown array decay");
536        V = Builder.CreatePtrToInt(V, DestTy, "ptrconv");
537      }
538    }
539    return V;
540
541  } else if (E->getType()->isReferenceType()) {
542    return EmitLValue(Op).getAddress();
543  }
544
545  return EmitCastExpr(Op, E->getType());
546}
547
548
549// VisitCastExpr - Emit code for an explicit or implicit cast.  Implicit casts
550// have to handle a more broad range of conversions than explicit casts, as they
551// handle things like function to ptr-to-function decay etc.
552Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
553  // Handle cases where the source is an non-complex type.
554
555  if (!CGF.hasAggregateLLVMType(E->getType())) {
556    Value *Src = Visit(const_cast<Expr*>(E));
557
558    // Use EmitScalarConversion to perform the conversion.
559    return EmitScalarConversion(Src, E->getType(), DestTy);
560  }
561
562  if (E->getType()->isAnyComplexType()) {
563    // Handle cases where the source is a complex type.
564    return EmitComplexToScalarConversion(CGF.EmitComplexExpr(E), E->getType(),
565                                         DestTy);
566  }
567
568  // Okay, this is a cast from an aggregate.  It must be a cast to void.  Just
569  // evaluate the result and return.
570  CGF.EmitAggExpr(E, 0, false);
571  return 0;
572}
573
574Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
575  return CGF.EmitCompoundStmt(*E->getSubStmt(),
576                              !E->getType()->isVoidType()).getScalarVal();
577}
578
579
580//===----------------------------------------------------------------------===//
581//                             Unary Operators
582//===----------------------------------------------------------------------===//
583
584Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
585                                             bool isInc, bool isPre) {
586  LValue LV = EmitLValue(E->getSubExpr());
587  // FIXME: Handle volatile!
588  Value *InVal = CGF.EmitLoadOfLValue(LV, // false
589                                     E->getSubExpr()->getType()).getScalarVal();
590
591  int AmountVal = isInc ? 1 : -1;
592
593  Value *NextVal;
594  if (isa<llvm::PointerType>(InVal->getType())) {
595    // FIXME: This isn't right for VLAs.
596    NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
597    NextVal = Builder.CreateGEP(InVal, NextVal, "ptrincdec");
598  } else {
599    // Add the inc/dec to the real part.
600    if (isa<llvm::IntegerType>(InVal->getType()))
601      NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
602    else if (InVal->getType() == llvm::Type::FloatTy)
603      NextVal =
604        llvm::ConstantFP::get(llvm::APFloat(static_cast<float>(AmountVal)));
605    else if (InVal->getType() == llvm::Type::DoubleTy)
606      NextVal =
607        llvm::ConstantFP::get(llvm::APFloat(static_cast<double>(AmountVal)));
608    else {
609      llvm::APFloat F(static_cast<float>(AmountVal));
610      bool ignored;
611      F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
612                &ignored);
613      NextVal = llvm::ConstantFP::get(F);
614    }
615    NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
616  }
617
618  // Store the updated result through the lvalue.
619  CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV,
620                             E->getSubExpr()->getType());
621
622  // If this is a postinc, return the value read from memory, otherwise use the
623  // updated value.
624  return isPre ? NextVal : InVal;
625}
626
627
628Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
629  Value *Op = Visit(E->getSubExpr());
630  return Builder.CreateNeg(Op, "neg");
631}
632
633Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
634  Value *Op = Visit(E->getSubExpr());
635  return Builder.CreateNot(Op, "neg");
636}
637
638Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
639  // Compare operand to zero.
640  Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
641
642  // Invert value.
643  // TODO: Could dynamically modify easy computations here.  For example, if
644  // the operand is an icmp ne, turn into icmp eq.
645  BoolVal = Builder.CreateNot(BoolVal, "lnot");
646
647  // ZExt result to int.
648  return Builder.CreateZExt(BoolVal, CGF.LLVMIntTy, "lnot.ext");
649}
650
651/// VisitSizeOfAlignOfExpr - Return the size or alignment of the type of
652/// argument of the sizeof expression as an integer.
653Value *
654ScalarExprEmitter::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
655  QualType RetType = E->getType();
656  assert(RetType->isIntegerType() && "Result type must be an integer!");
657  uint32_t ResultWidth =
658    static_cast<uint32_t>(CGF.getContext().getTypeSize(RetType));
659
660  QualType TypeToSize = E->getTypeOfArgument();
661  // sizeof(void) and __alignof__(void) = 1 as a gcc extension. Also
662  // for function types.
663  // FIXME: what is alignof a function type in gcc?
664  if (TypeToSize->isVoidType() || TypeToSize->isFunctionType())
665    return llvm::ConstantInt::get(llvm::APInt(ResultWidth, 1));
666
667  if (const VariableArrayType *VAT =
668        CGF.getContext().getAsVariableArrayType(TypeToSize)) {
669    if (E->isSizeOf()) {
670      if (E->isArgumentType()) {
671        // sizeof(type) - make sure to emit the VLA size.
672        CGF.EmitVLASize(TypeToSize);
673      }
674      return CGF.GetVLASize(VAT);
675    }
676
677    // alignof
678    QualType BaseType = CGF.getContext().getBaseElementType(VAT);
679    uint64_t Align = CGF.getContext().getTypeAlign(BaseType);
680
681    Align /= 8;  // Return alignment in bytes, not bits.
682    return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Align));
683  }
684
685  std::pair<uint64_t, unsigned> Info = CGF.getContext().getTypeInfo(TypeToSize);
686
687  uint64_t Val = E->isSizeOf() ? Info.first : Info.second;
688  Val /= 8;  // Return size in bytes, not bits.
689
690  return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
691}
692
693Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
694  Expr *Op = E->getSubExpr();
695  if (Op->getType()->isAnyComplexType())
696    return CGF.EmitComplexExpr(Op).first;
697  return Visit(Op);
698}
699Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
700  Expr *Op = E->getSubExpr();
701  if (Op->getType()->isAnyComplexType())
702    return CGF.EmitComplexExpr(Op).second;
703
704  // __imag on a scalar returns zero.  Emit it the subexpr to ensure side
705  // effects are evaluated.
706  CGF.EmitScalarExpr(Op);
707  return llvm::Constant::getNullValue(ConvertType(E->getType()));
708}
709
710Value *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E)
711{
712  int64_t Val = E->evaluateOffsetOf(CGF.getContext());
713
714  assert(E->getType()->isIntegerType() && "Result type must be an integer!");
715
716  uint32_t ResultWidth =
717    static_cast<uint32_t>(CGF.getContext().getTypeSize(E->getType()));
718  return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
719}
720
721//===----------------------------------------------------------------------===//
722//                           Binary Operators
723//===----------------------------------------------------------------------===//
724
725BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
726  BinOpInfo Result;
727  Result.LHS = Visit(E->getLHS());
728  Result.RHS = Visit(E->getRHS());
729  Result.Ty  = E->getType();
730  Result.E = E;
731  return Result;
732}
733
734Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
735                      Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
736  QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
737
738  BinOpInfo OpInfo;
739
740  // Load the LHS and RHS operands.
741  LValue LHSLV = EmitLValue(E->getLHS());
742  OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
743
744  // Determine the computation type.  If the RHS is complex, then this is one of
745  // the add/sub/mul/div operators.  All of these operators can be computed in
746  // with just their real component even though the computation domain really is
747  // complex.
748  QualType ComputeType = E->getComputationType();
749
750  // If the computation type is complex, then the RHS is complex.  Emit the RHS.
751  if (const ComplexType *CT = ComputeType->getAsComplexType()) {
752    ComputeType = CT->getElementType();
753
754    // Emit the RHS, only keeping the real component.
755    OpInfo.RHS = CGF.EmitComplexExpr(E->getRHS()).first;
756    RHSTy = RHSTy->getAsComplexType()->getElementType();
757  } else {
758    // Otherwise the RHS is a simple scalar value.
759    OpInfo.RHS = Visit(E->getRHS());
760  }
761
762  QualType LComputeTy, RComputeTy, ResultTy;
763
764  // Compound assignment does not contain enough information about all
765  // the types involved for pointer arithmetic cases. Figure it out
766  // here for now.
767  if (E->getLHS()->getType()->isPointerType()) {
768    // Pointer arithmetic cases: ptr +=,-= int and ptr -= ptr,
769    assert((E->getOpcode() == BinaryOperator::AddAssign ||
770            E->getOpcode() == BinaryOperator::SubAssign) &&
771           "Invalid compound assignment operator on pointer type.");
772    LComputeTy = E->getLHS()->getType();
773
774    if (E->getRHS()->getType()->isPointerType()) {
775      // Degenerate case of (ptr -= ptr) allowed by GCC implicit cast
776      // extension, the conversion from the pointer difference back to
777      // the LHS type is handled at the end.
778      assert(E->getOpcode() == BinaryOperator::SubAssign &&
779             "Invalid compound assignment operator on pointer type.");
780      RComputeTy = E->getLHS()->getType();
781      ResultTy = CGF.getContext().getPointerDiffType();
782    } else {
783      RComputeTy = E->getRHS()->getType();
784      ResultTy = LComputeTy;
785    }
786  } else if (E->getRHS()->getType()->isPointerType()) {
787    // Degenerate case of (int += ptr) allowed by GCC implicit cast
788    // extension.
789    assert(E->getOpcode() == BinaryOperator::AddAssign &&
790           "Invalid compound assignment operator on pointer type.");
791    LComputeTy = E->getLHS()->getType();
792    RComputeTy = E->getRHS()->getType();
793    ResultTy = RComputeTy;
794  } else {
795    LComputeTy = RComputeTy = ResultTy = ComputeType;
796  }
797
798  // Convert the LHS/RHS values to the computation type.
799  OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, LComputeTy);
800  OpInfo.RHS = EmitScalarConversion(OpInfo.RHS, RHSTy, RComputeTy);
801  OpInfo.Ty = ResultTy;
802  OpInfo.E = E;
803
804  // Expand the binary operator.
805  Value *Result = (this->*Func)(OpInfo);
806
807  // Convert the result back to the LHS type.
808  Result = EmitScalarConversion(Result, ResultTy, LHSTy);
809
810  // Store the result value into the LHS lvalue. Bit-fields are
811  // handled specially because the result is altered by the store,
812  // i.e., [C99 6.5.16p1] 'An assignment expression has the value of
813  // the left operand after the assignment...'.
814  if (LHSLV.isBitfield())
815    CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy,
816                                       &Result);
817  else
818    CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy);
819
820  return Result;
821}
822
823
824Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
825  if (Ops.LHS->getType()->isFPOrFPVector())
826    return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
827  else if (Ops.Ty->isUnsignedIntegerType())
828    return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
829  else
830    return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
831}
832
833Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
834  // Rem in C can't be a floating point type: C99 6.5.5p2.
835  if (Ops.Ty->isUnsignedIntegerType())
836    return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
837  else
838    return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
839}
840
841
842Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
843  if (!Ops.Ty->isPointerType())
844    return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
845
846  // FIXME: What about a pointer to a VLA?
847  Value *Ptr, *Idx;
848  Expr *IdxExp;
849  if (isa<llvm::PointerType>(Ops.LHS->getType())) {  // pointer + int
850    Ptr = Ops.LHS;
851    Idx = Ops.RHS;
852    IdxExp = Ops.E->getRHS();
853  } else {                                           // int + pointer
854    Ptr = Ops.RHS;
855    Idx = Ops.LHS;
856    IdxExp = Ops.E->getLHS();
857  }
858
859  unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
860  if (Width < CGF.LLVMPointerWidth) {
861    // Zero or sign extend the pointer value based on whether the index is
862    // signed or not.
863    const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
864    if (IdxExp->getType()->isSignedIntegerType())
865      Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
866    else
867      Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
868  }
869
870  return Builder.CreateGEP(Ptr, Idx, "add.ptr");
871}
872
873Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
874  if (!isa<llvm::PointerType>(Ops.LHS->getType()))
875    return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
876
877  if (!isa<llvm::PointerType>(Ops.RHS->getType())) {
878    // pointer - int
879    Value *Idx = Ops.RHS;
880    unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
881    if (Width < CGF.LLVMPointerWidth) {
882      // Zero or sign extend the pointer value based on whether the index is
883      // signed or not.
884      const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
885      if (Ops.E->getRHS()->getType()->isSignedIntegerType())
886        Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
887      else
888        Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
889    }
890    Idx = Builder.CreateNeg(Idx, "sub.ptr.neg");
891
892    // FIXME: The pointer could point to a VLA.
893    // The GNU void* - int case is automatically handled here because
894    // our LLVM type for void* is i8*.
895    return Builder.CreateGEP(Ops.LHS, Idx, "sub.ptr");
896  } else {
897    // pointer - pointer
898    Value *LHS = Ops.LHS;
899    Value *RHS = Ops.RHS;
900
901    const QualType LHSType = Ops.E->getLHS()->getType();
902    const QualType LHSElementType = LHSType->getAsPointerType()->getPointeeType();
903    uint64_t ElementSize;
904
905    // Handle GCC extension for pointer arithmetic on void* types.
906    if (LHSElementType->isVoidType()) {
907      ElementSize = 1;
908    } else {
909      ElementSize = CGF.getContext().getTypeSize(LHSElementType) / 8;
910    }
911
912    const llvm::Type *ResultType = ConvertType(Ops.Ty);
913    LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
914    RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
915    Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
916
917    // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
918    // remainder.  As such, we handle common power-of-two cases here to generate
919    // better code. See PR2247.
920    if (llvm::isPowerOf2_64(ElementSize)) {
921      Value *ShAmt =
922        llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
923      return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
924    }
925
926    // Otherwise, do a full sdiv.
927    Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
928    return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
929  }
930}
931
932Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
933  // LLVM requires the LHS and RHS to be the same type: promote or truncate the
934  // RHS to the same size as the LHS.
935  Value *RHS = Ops.RHS;
936  if (Ops.LHS->getType() != RHS->getType())
937    RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
938
939  return Builder.CreateShl(Ops.LHS, RHS, "shl");
940}
941
942Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
943  // LLVM requires the LHS and RHS to be the same type: promote or truncate the
944  // RHS to the same size as the LHS.
945  Value *RHS = Ops.RHS;
946  if (Ops.LHS->getType() != RHS->getType())
947    RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
948
949  if (Ops.Ty->isUnsignedIntegerType())
950    return Builder.CreateLShr(Ops.LHS, RHS, "shr");
951  return Builder.CreateAShr(Ops.LHS, RHS, "shr");
952}
953
954Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
955                                      unsigned SICmpOpc, unsigned FCmpOpc) {
956  Value *Result;
957  QualType LHSTy = E->getLHS()->getType();
958  if (!LHSTy->isAnyComplexType() && !LHSTy->isVectorType()) {
959    Value *LHS = Visit(E->getLHS());
960    Value *RHS = Visit(E->getRHS());
961
962    if (LHS->getType()->isFloatingPoint()) {
963      Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
964                                  LHS, RHS, "cmp");
965    } else if (LHSTy->isSignedIntegerType()) {
966      Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
967                                  LHS, RHS, "cmp");
968    } else {
969      // Unsigned integers and pointers.
970      Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
971                                  LHS, RHS, "cmp");
972    }
973  } else if (LHSTy->isVectorType()) {
974    Value *LHS = Visit(E->getLHS());
975    Value *RHS = Visit(E->getRHS());
976
977    if (LHS->getType()->isFPOrFPVector()) {
978      Result = Builder.CreateVFCmp((llvm::CmpInst::Predicate)FCmpOpc,
979                                  LHS, RHS, "cmp");
980    } else if (LHSTy->isUnsignedIntegerType()) {
981      Result = Builder.CreateVICmp((llvm::CmpInst::Predicate)UICmpOpc,
982                                  LHS, RHS, "cmp");
983    } else {
984      // Signed integers and pointers.
985      Result = Builder.CreateVICmp((llvm::CmpInst::Predicate)SICmpOpc,
986                                  LHS, RHS, "cmp");
987    }
988    return Result;
989  } else {
990    // Complex Comparison: can only be an equality comparison.
991    CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
992    CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
993
994    QualType CETy = LHSTy->getAsComplexType()->getElementType();
995
996    Value *ResultR, *ResultI;
997    if (CETy->isRealFloatingType()) {
998      ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
999                                   LHS.first, RHS.first, "cmp.r");
1000      ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1001                                   LHS.second, RHS.second, "cmp.i");
1002    } else {
1003      // Complex comparisons can only be equality comparisons.  As such, signed
1004      // and unsigned opcodes are the same.
1005      ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1006                                   LHS.first, RHS.first, "cmp.r");
1007      ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1008                                   LHS.second, RHS.second, "cmp.i");
1009    }
1010
1011    if (E->getOpcode() == BinaryOperator::EQ) {
1012      Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1013    } else {
1014      assert(E->getOpcode() == BinaryOperator::NE &&
1015             "Complex comparison other than == or != ?");
1016      Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1017    }
1018  }
1019
1020  // ZExt result to int.
1021  return Builder.CreateZExt(Result, CGF.LLVMIntTy, "cmp.ext");
1022}
1023
1024Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
1025  LValue LHS = EmitLValue(E->getLHS());
1026  Value *RHS = Visit(E->getRHS());
1027
1028  // Store the value into the LHS.  Bit-fields are handled specially
1029  // because the result is altered by the store, i.e., [C99 6.5.16p1]
1030  // 'An assignment expression has the value of the left operand after
1031  // the assignment...'.
1032  // FIXME: Volatility!
1033  if (LHS.isBitfield())
1034    CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType(),
1035                                       &RHS);
1036  else
1037    CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
1038
1039  // Return the RHS.
1040  return RHS;
1041}
1042
1043Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
1044  // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
1045  // If we have 1 && X, just emit X without inserting the control flow.
1046  if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1047    if (Cond == 1) { // If we have 1 && X, just emit X.
1048      Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1049      // ZExt result to int.
1050      return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "land.ext");
1051    }
1052
1053    // 0 && RHS: If it is safe, just elide the RHS, and return 0.
1054    if (!CGF.ContainsLabel(E->getRHS()))
1055      return llvm::Constant::getNullValue(CGF.LLVMIntTy);
1056  }
1057
1058  llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
1059  llvm::BasicBlock *RHSBlock  = CGF.createBasicBlock("land.rhs");
1060
1061  // Branch on the LHS first.  If it is false, go to the failure (cont) block.
1062  CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
1063
1064  // Any edges into the ContBlock are now from an (indeterminate number of)
1065  // edges from this first condition.  All of these values will be false.  Start
1066  // setting up the PHI node in the Cont Block for this.
1067  llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::Int1Ty, "", ContBlock);
1068  PN->reserveOperandSpace(2);  // Normal case, two inputs.
1069  for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1070       PI != PE; ++PI)
1071    PN->addIncoming(llvm::ConstantInt::getFalse(), *PI);
1072
1073  CGF.EmitBlock(RHSBlock);
1074  Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1075
1076  // Reaquire the RHS block, as there may be subblocks inserted.
1077  RHSBlock = Builder.GetInsertBlock();
1078
1079  // Emit an unconditional branch from this block to ContBlock.  Insert an entry
1080  // into the phi node for the edge with the value of RHSCond.
1081  CGF.EmitBlock(ContBlock);
1082  PN->addIncoming(RHSCond, RHSBlock);
1083
1084  // ZExt result to int.
1085  return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
1086}
1087
1088Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
1089  // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
1090  // If we have 0 || X, just emit X without inserting the control flow.
1091  if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1092    if (Cond == -1) { // If we have 0 || X, just emit X.
1093      Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1094      // ZExt result to int.
1095      return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "lor.ext");
1096    }
1097
1098    // 1 || RHS: If it is safe, just elide the RHS, and return 1.
1099    if (!CGF.ContainsLabel(E->getRHS()))
1100      return llvm::ConstantInt::get(CGF.LLVMIntTy, 1);
1101  }
1102
1103  llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
1104  llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
1105
1106  // Branch on the LHS first.  If it is true, go to the success (cont) block.
1107  CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
1108
1109  // Any edges into the ContBlock are now from an (indeterminate number of)
1110  // edges from this first condition.  All of these values will be true.  Start
1111  // setting up the PHI node in the Cont Block for this.
1112  llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::Int1Ty, "", ContBlock);
1113  PN->reserveOperandSpace(2);  // Normal case, two inputs.
1114  for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1115       PI != PE; ++PI)
1116    PN->addIncoming(llvm::ConstantInt::getTrue(), *PI);
1117
1118  // Emit the RHS condition as a bool value.
1119  CGF.EmitBlock(RHSBlock);
1120  Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1121
1122  // Reaquire the RHS block, as there may be subblocks inserted.
1123  RHSBlock = Builder.GetInsertBlock();
1124
1125  // Emit an unconditional branch from this block to ContBlock.  Insert an entry
1126  // into the phi node for the edge with the value of RHSCond.
1127  CGF.EmitBlock(ContBlock);
1128  PN->addIncoming(RHSCond, RHSBlock);
1129
1130  // ZExt result to int.
1131  return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
1132}
1133
1134Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
1135  CGF.EmitStmt(E->getLHS());
1136  CGF.EnsureInsertPoint();
1137  return Visit(E->getRHS());
1138}
1139
1140//===----------------------------------------------------------------------===//
1141//                             Other Operators
1142//===----------------------------------------------------------------------===//
1143
1144/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
1145/// expression is cheap enough and side-effect-free enough to evaluate
1146/// unconditionally instead of conditionally.  This is used to convert control
1147/// flow into selects in some cases.
1148static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E) {
1149  if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
1150    return isCheapEnoughToEvaluateUnconditionally(PE->getSubExpr());
1151
1152  // TODO: Allow anything we can constant fold to an integer or fp constant.
1153  if (isa<IntegerLiteral>(E) || isa<CharacterLiteral>(E) ||
1154      isa<FloatingLiteral>(E))
1155    return true;
1156
1157  // Non-volatile automatic variables too, to get "cond ? X : Y" where
1158  // X and Y are local variables.
1159  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1160    if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1161      if (VD->hasLocalStorage() && !VD->getType().isVolatileQualified())
1162        return true;
1163
1164  return false;
1165}
1166
1167
1168Value *ScalarExprEmitter::
1169VisitConditionalOperator(const ConditionalOperator *E) {
1170  // If the condition constant folds and can be elided, try to avoid emitting
1171  // the condition and the dead arm.
1172  if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getCond())){
1173    Expr *Live = E->getLHS(), *Dead = E->getRHS();
1174    if (Cond == -1)
1175      std::swap(Live, Dead);
1176
1177    // If the dead side doesn't have labels we need, and if the Live side isn't
1178    // the gnu missing ?: extension (which we could handle, but don't bother
1179    // to), just emit the Live part.
1180    if ((!Dead || !CGF.ContainsLabel(Dead)) &&  // No labels in dead part
1181        Live)                                   // Live part isn't missing.
1182      return Visit(Live);
1183  }
1184
1185
1186  // If this is a really simple expression (like x ? 4 : 5), emit this as a
1187  // select instead of as control flow.  We can only do this if it is cheap and
1188  // safe to evaluate the LHS and RHS unconditionally.
1189  if (E->getLHS() && isCheapEnoughToEvaluateUnconditionally(E->getLHS()) &&
1190      isCheapEnoughToEvaluateUnconditionally(E->getRHS())) {
1191    llvm::Value *CondV = CGF.EvaluateExprAsBool(E->getCond());
1192    llvm::Value *LHS = Visit(E->getLHS());
1193    llvm::Value *RHS = Visit(E->getRHS());
1194    return Builder.CreateSelect(CondV, LHS, RHS, "cond");
1195  }
1196
1197
1198  llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
1199  llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
1200  llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
1201  Value *CondVal = 0;
1202
1203  // If we have the GNU missing condition extension, evaluate the conditional
1204  // and then convert it to bool the hard way.  We do this explicitly
1205  // because we need the unconverted value for the missing middle value of
1206  // the ?:.
1207  if (E->getLHS() == 0) {
1208    CondVal = CGF.EmitScalarExpr(E->getCond());
1209    Value *CondBoolVal =
1210      CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
1211                               CGF.getContext().BoolTy);
1212    Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
1213  } else {
1214    // Otherwise, just use EmitBranchOnBoolExpr to get small and simple code for
1215    // the branch on bool.
1216    CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
1217  }
1218
1219  CGF.EmitBlock(LHSBlock);
1220
1221  // Handle the GNU extension for missing LHS.
1222  Value *LHS;
1223  if (E->getLHS())
1224    LHS = Visit(E->getLHS());
1225  else    // Perform promotions, to handle cases like "short ?: int"
1226    LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
1227
1228  LHSBlock = Builder.GetInsertBlock();
1229  CGF.EmitBranch(ContBlock);
1230
1231  CGF.EmitBlock(RHSBlock);
1232
1233  Value *RHS = Visit(E->getRHS());
1234  RHSBlock = Builder.GetInsertBlock();
1235  CGF.EmitBranch(ContBlock);
1236
1237  CGF.EmitBlock(ContBlock);
1238
1239  if (!LHS || !RHS) {
1240    assert(E->getType()->isVoidType() && "Non-void value should have a value");
1241    return 0;
1242  }
1243
1244  // Create a PHI node for the real part.
1245  llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
1246  PN->reserveOperandSpace(2);
1247  PN->addIncoming(LHS, LHSBlock);
1248  PN->addIncoming(RHS, RHSBlock);
1249  return PN;
1250}
1251
1252Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
1253  // Emit the LHS or RHS as appropriate.
1254  return
1255    Visit(E->isConditionTrue(CGF.getContext()) ? E->getLHS() : E->getRHS());
1256}
1257
1258Value *ScalarExprEmitter::VisitOverloadExpr(OverloadExpr *E) {
1259  return CGF.EmitCallExpr(E->getFn(), E->arg_begin(),
1260                          E->arg_end(CGF.getContext())).getScalarVal();
1261}
1262
1263Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
1264  llvm::Value *ArgValue = EmitLValue(VE->getSubExpr()).getAddress();
1265
1266  llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
1267
1268  // If EmitVAArg fails, we fall back to the LLVM instruction.
1269  if (!ArgPtr)
1270    return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
1271
1272  // FIXME: volatile?
1273  return Builder.CreateLoad(ArgPtr);
1274}
1275
1276Value *ScalarExprEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
1277  std::string str;
1278  CGF.getContext().getObjCEncodingForType(E->getEncodedType(), str);
1279
1280  llvm::Constant *C = llvm::ConstantArray::get(str);
1281  C = new llvm::GlobalVariable(C->getType(), true,
1282                               llvm::GlobalValue::InternalLinkage,
1283                               C, ".str", &CGF.CGM.getModule());
1284  llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
1285  llvm::Constant *Zeros[] = { Zero, Zero };
1286  C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
1287
1288  return C;
1289}
1290
1291//===----------------------------------------------------------------------===//
1292//                         Entry Point into this File
1293//===----------------------------------------------------------------------===//
1294
1295/// EmitComplexExpr - Emit the computation of the specified expression of
1296/// complex type, ignoring the result.
1297Value *CodeGenFunction::EmitScalarExpr(const Expr *E) {
1298  assert(E && !hasAggregateLLVMType(E->getType()) &&
1299         "Invalid scalar expression to emit");
1300
1301  return ScalarExprEmitter(*this).Visit(const_cast<Expr*>(E));
1302}
1303
1304/// EmitScalarConversion - Emit a conversion from the specified type to the
1305/// specified destination type, both of which are LLVM scalar types.
1306Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
1307                                             QualType DstTy) {
1308  assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
1309         "Invalid scalar expression to emit");
1310  return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
1311}
1312
1313/// EmitComplexToScalarConversion - Emit a conversion from the specified
1314/// complex type to the specified destination type, where the destination
1315/// type is an LLVM scalar type.
1316Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
1317                                                      QualType SrcTy,
1318                                                      QualType DstTy) {
1319  assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
1320         "Invalid complex -> scalar conversion");
1321  return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
1322                                                                DstTy);
1323}
1324
1325Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) {
1326  assert(V1->getType() == V2->getType() &&
1327         "Vector operands must be of the same type");
1328  unsigned NumElements =
1329    cast<llvm::VectorType>(V1->getType())->getNumElements();
1330
1331  va_list va;
1332  va_start(va, V2);
1333
1334  llvm::SmallVector<llvm::Constant*, 16> Args;
1335  for (unsigned i = 0; i < NumElements; i++) {
1336    int n = va_arg(va, int);
1337    assert(n >= 0 && n < (int)NumElements * 2 &&
1338           "Vector shuffle index out of bounds!");
1339    Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, n));
1340  }
1341
1342  const char *Name = va_arg(va, const char *);
1343  va_end(va);
1344
1345  llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
1346
1347  return Builder.CreateShuffleVector(V1, V2, Mask, Name);
1348}
1349
1350llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals,
1351                                         unsigned NumVals, bool isSplat) {
1352  llvm::Value *Vec
1353    = llvm::UndefValue::get(llvm::VectorType::get(Vals[0]->getType(), NumVals));
1354
1355  for (unsigned i = 0, e = NumVals; i != e; ++i) {
1356    llvm::Value *Val = isSplat ? Vals[0] : Vals[i];
1357    llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
1358    Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp");
1359  }
1360
1361  return Vec;
1362}
1363