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