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