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