CGExprScalar.cpp revision 193326
1193326Sed//===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
2193326Sed//
3193326Sed//                     The LLVM Compiler Infrastructure
4193326Sed//
5193326Sed// This file is distributed under the University of Illinois Open Source
6193326Sed// License. See LICENSE.TXT for details.
7193326Sed//
8193326Sed//===----------------------------------------------------------------------===//
9193326Sed//
10193326Sed// This contains code to emit Expr nodes with scalar LLVM types as LLVM code.
11193326Sed//
12193326Sed//===----------------------------------------------------------------------===//
13193326Sed
14193326Sed#include "CodeGenFunction.h"
15193326Sed#include "CodeGenModule.h"
16193326Sed#include "clang/AST/ASTContext.h"
17193326Sed#include "clang/AST/DeclObjC.h"
18193326Sed#include "clang/AST/RecordLayout.h"
19193326Sed#include "clang/AST/StmtVisitor.h"
20193326Sed#include "clang/Basic/TargetInfo.h"
21193326Sed#include "llvm/Constants.h"
22193326Sed#include "llvm/Function.h"
23193326Sed#include "llvm/GlobalVariable.h"
24193326Sed#include "llvm/Intrinsics.h"
25193326Sed#include "llvm/Module.h"
26193326Sed#include "llvm/Support/Compiler.h"
27193326Sed#include "llvm/Support/CFG.h"
28193326Sed#include "llvm/Target/TargetData.h"
29193326Sed#include <cstdarg>
30193326Sed
31193326Sedusing namespace clang;
32193326Sedusing namespace CodeGen;
33193326Sedusing llvm::Value;
34193326Sed
35193326Sed//===----------------------------------------------------------------------===//
36193326Sed//                         Scalar Expression Emitter
37193326Sed//===----------------------------------------------------------------------===//
38193326Sed
39193326Sedstruct BinOpInfo {
40193326Sed  Value *LHS;
41193326Sed  Value *RHS;
42193326Sed  QualType Ty;  // Computation Type.
43193326Sed  const BinaryOperator *E;
44193326Sed};
45193326Sed
46193326Sednamespace {
47193326Sedclass VISIBILITY_HIDDEN ScalarExprEmitter
48193326Sed  : public StmtVisitor<ScalarExprEmitter, Value*> {
49193326Sed  CodeGenFunction &CGF;
50193326Sed  CGBuilderTy &Builder;
51193326Sed  bool IgnoreResultAssign;
52193326Sed
53193326Sedpublic:
54193326Sed
55193326Sed  ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
56193326Sed    : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira) {
57193326Sed  }
58193326Sed
59193326Sed  //===--------------------------------------------------------------------===//
60193326Sed  //                               Utilities
61193326Sed  //===--------------------------------------------------------------------===//
62193326Sed
63193326Sed  bool TestAndClearIgnoreResultAssign() {
64193326Sed    bool I = IgnoreResultAssign; IgnoreResultAssign = false;
65193326Sed    return I; }
66193326Sed
67193326Sed  const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
68193326Sed  LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
69193326Sed
70193326Sed  Value *EmitLoadOfLValue(LValue LV, QualType T) {
71193326Sed    return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
72193326Sed  }
73193326Sed
74193326Sed  /// EmitLoadOfLValue - Given an expression with complex type that represents a
75193326Sed  /// value l-value, this method emits the address of the l-value, then loads
76193326Sed  /// and returns the result.
77193326Sed  Value *EmitLoadOfLValue(const Expr *E) {
78193326Sed    return EmitLoadOfLValue(EmitLValue(E), E->getType());
79193326Sed  }
80193326Sed
81193326Sed  /// EmitConversionToBool - Convert the specified expression value to a
82193326Sed  /// boolean (i1) truth value.  This is equivalent to "Val != 0".
83193326Sed  Value *EmitConversionToBool(Value *Src, QualType DstTy);
84193326Sed
85193326Sed  /// EmitScalarConversion - Emit a conversion from the specified type to the
86193326Sed  /// specified destination type, both of which are LLVM scalar types.
87193326Sed  Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
88193326Sed
89193326Sed  /// EmitComplexToScalarConversion - Emit a conversion from the specified
90193326Sed  /// complex type to the specified destination type, where the destination
91193326Sed  /// type is an LLVM scalar type.
92193326Sed  Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
93193326Sed                                       QualType SrcTy, QualType DstTy);
94193326Sed
95193326Sed  //===--------------------------------------------------------------------===//
96193326Sed  //                            Visitor Methods
97193326Sed  //===--------------------------------------------------------------------===//
98193326Sed
99193326Sed  Value *VisitStmt(Stmt *S) {
100193326Sed    S->dump(CGF.getContext().getSourceManager());
101193326Sed    assert(0 && "Stmt can't have complex result type!");
102193326Sed    return 0;
103193326Sed  }
104193326Sed  Value *VisitExpr(Expr *S);
105193326Sed  Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
106193326Sed
107193326Sed  // Leaves.
108193326Sed  Value *VisitIntegerLiteral(const IntegerLiteral *E) {
109193326Sed    return llvm::ConstantInt::get(E->getValue());
110193326Sed  }
111193326Sed  Value *VisitFloatingLiteral(const FloatingLiteral *E) {
112193326Sed    return llvm::ConstantFP::get(E->getValue());
113193326Sed  }
114193326Sed  Value *VisitCharacterLiteral(const CharacterLiteral *E) {
115193326Sed    return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
116193326Sed  }
117193326Sed  Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
118193326Sed    return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
119193326Sed  }
120193326Sed  Value *VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
121193326Sed    return llvm::Constant::getNullValue(ConvertType(E->getType()));
122193326Sed  }
123193326Sed  Value *VisitGNUNullExpr(const GNUNullExpr *E) {
124193326Sed    return llvm::Constant::getNullValue(ConvertType(E->getType()));
125193326Sed  }
126193326Sed  Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
127193326Sed    return llvm::ConstantInt::get(ConvertType(E->getType()),
128193326Sed                                  CGF.getContext().typesAreCompatible(
129193326Sed                                    E->getArgType1(), E->getArgType2()));
130193326Sed  }
131193326Sed  Value *VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
132193326Sed  Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
133193326Sed    llvm::Value *V =
134193326Sed      llvm::ConstantInt::get(llvm::Type::Int32Ty,
135193326Sed                             CGF.GetIDForAddrOfLabel(E->getLabel()));
136193326Sed
137193326Sed    return Builder.CreateIntToPtr(V, ConvertType(E->getType()));
138193326Sed  }
139193326Sed
140193326Sed  // l-values.
141193326Sed  Value *VisitDeclRefExpr(DeclRefExpr *E) {
142193326Sed    if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(E->getDecl()))
143193326Sed      return llvm::ConstantInt::get(EC->getInitVal());
144193326Sed    return EmitLoadOfLValue(E);
145193326Sed  }
146193326Sed  Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
147193326Sed    return CGF.EmitObjCSelectorExpr(E);
148193326Sed  }
149193326Sed  Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
150193326Sed    return CGF.EmitObjCProtocolExpr(E);
151193326Sed  }
152193326Sed  Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
153193326Sed    return EmitLoadOfLValue(E);
154193326Sed  }
155193326Sed  Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
156193326Sed    return EmitLoadOfLValue(E);
157193326Sed  }
158193326Sed  Value *VisitObjCKVCRefExpr(ObjCKVCRefExpr *E) {
159193326Sed    return EmitLoadOfLValue(E);
160193326Sed  }
161193326Sed  Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
162193326Sed    return CGF.EmitObjCMessageExpr(E).getScalarVal();
163193326Sed  }
164193326Sed
165193326Sed  Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
166193326Sed  Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
167193326Sed  Value *VisitMemberExpr(Expr *E)           { return EmitLoadOfLValue(E); }
168193326Sed  Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
169193326Sed  Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
170193326Sed    return EmitLoadOfLValue(E);
171193326Sed  }
172193326Sed  Value *VisitStringLiteral(Expr *E)  { return EmitLValue(E).getAddress(); }
173193326Sed  Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
174193326Sed     return EmitLValue(E).getAddress();
175193326Sed  }
176193326Sed
177193326Sed  Value *VisitPredefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); }
178193326Sed
179193326Sed  Value *VisitInitListExpr(InitListExpr *E) {
180193326Sed    bool Ignore = TestAndClearIgnoreResultAssign();
181193326Sed    (void)Ignore;
182193326Sed    assert (Ignore == false && "init list ignored");
183193326Sed    unsigned NumInitElements = E->getNumInits();
184193326Sed
185193326Sed    if (E->hadArrayRangeDesignator()) {
186193326Sed      CGF.ErrorUnsupported(E, "GNU array range designator extension");
187193326Sed    }
188193326Sed
189193326Sed    const llvm::VectorType *VType =
190193326Sed      dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
191193326Sed
192193326Sed    // We have a scalar in braces. Just use the first element.
193193326Sed    if (!VType)
194193326Sed      return Visit(E->getInit(0));
195193326Sed
196193326Sed    unsigned NumVectorElements = VType->getNumElements();
197193326Sed    const llvm::Type *ElementType = VType->getElementType();
198193326Sed
199193326Sed    // Emit individual vector element stores.
200193326Sed    llvm::Value *V = llvm::UndefValue::get(VType);
201193326Sed
202193326Sed    // Emit initializers
203193326Sed    unsigned i;
204193326Sed    for (i = 0; i < NumInitElements; ++i) {
205193326Sed      Value *NewV = Visit(E->getInit(i));
206193326Sed      Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
207193326Sed      V = Builder.CreateInsertElement(V, NewV, Idx);
208193326Sed    }
209193326Sed
210193326Sed    // Emit remaining default initializers
211193326Sed    for (/* Do not initialize i*/; i < NumVectorElements; ++i) {
212193326Sed      Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
213193326Sed      llvm::Value *NewV = llvm::Constant::getNullValue(ElementType);
214193326Sed      V = Builder.CreateInsertElement(V, NewV, Idx);
215193326Sed    }
216193326Sed
217193326Sed    return V;
218193326Sed  }
219193326Sed
220193326Sed  Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
221193326Sed    return llvm::Constant::getNullValue(ConvertType(E->getType()));
222193326Sed  }
223193326Sed  Value *VisitImplicitCastExpr(const ImplicitCastExpr *E);
224193326Sed  Value *VisitCastExpr(const CastExpr *E) {
225193326Sed    // Make sure to evaluate VLA bounds now so that we have them for later.
226193326Sed    if (E->getType()->isVariablyModifiedType())
227193326Sed      CGF.EmitVLASize(E->getType());
228193326Sed
229193326Sed    return EmitCastExpr(E->getSubExpr(), E->getType());
230193326Sed  }
231193326Sed  Value *EmitCastExpr(const Expr *E, QualType T);
232193326Sed
233193326Sed  Value *VisitCallExpr(const CallExpr *E) {
234193326Sed    if (E->getCallReturnType()->isReferenceType())
235193326Sed      return EmitLoadOfLValue(E);
236193326Sed
237193326Sed    return CGF.EmitCallExpr(E).getScalarVal();
238193326Sed  }
239193326Sed
240193326Sed  Value *VisitStmtExpr(const StmtExpr *E);
241193326Sed
242193326Sed  Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E);
243193326Sed
244193326Sed  // Unary Operators.
245193326Sed  Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre);
246193326Sed  Value *VisitUnaryPostDec(const UnaryOperator *E) {
247193326Sed    return VisitPrePostIncDec(E, false, false);
248193326Sed  }
249193326Sed  Value *VisitUnaryPostInc(const UnaryOperator *E) {
250193326Sed    return VisitPrePostIncDec(E, true, false);
251193326Sed  }
252193326Sed  Value *VisitUnaryPreDec(const UnaryOperator *E) {
253193326Sed    return VisitPrePostIncDec(E, false, true);
254193326Sed  }
255193326Sed  Value *VisitUnaryPreInc(const UnaryOperator *E) {
256193326Sed    return VisitPrePostIncDec(E, true, true);
257193326Sed  }
258193326Sed  Value *VisitUnaryAddrOf(const UnaryOperator *E) {
259193326Sed    return EmitLValue(E->getSubExpr()).getAddress();
260193326Sed  }
261193326Sed  Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
262193326Sed  Value *VisitUnaryPlus(const UnaryOperator *E) {
263193326Sed    // This differs from gcc, though, most likely due to a bug in gcc.
264193326Sed    TestAndClearIgnoreResultAssign();
265193326Sed    return Visit(E->getSubExpr());
266193326Sed  }
267193326Sed  Value *VisitUnaryMinus    (const UnaryOperator *E);
268193326Sed  Value *VisitUnaryNot      (const UnaryOperator *E);
269193326Sed  Value *VisitUnaryLNot     (const UnaryOperator *E);
270193326Sed  Value *VisitUnaryReal     (const UnaryOperator *E);
271193326Sed  Value *VisitUnaryImag     (const UnaryOperator *E);
272193326Sed  Value *VisitUnaryExtension(const UnaryOperator *E) {
273193326Sed    return Visit(E->getSubExpr());
274193326Sed  }
275193326Sed  Value *VisitUnaryOffsetOf(const UnaryOperator *E);
276193326Sed
277193326Sed  // C++
278193326Sed  Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
279193326Sed    return Visit(DAE->getExpr());
280193326Sed  }
281193326Sed  Value *VisitCXXThisExpr(CXXThisExpr *TE) {
282193326Sed    return CGF.LoadCXXThis();
283193326Sed  }
284193326Sed
285193326Sed  Value *VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) {
286193326Sed    return CGF.EmitCXXExprWithTemporaries(E).getScalarVal();
287193326Sed  }
288193326Sed  Value *VisitCXXNewExpr(const CXXNewExpr *E) {
289193326Sed    return CGF.EmitCXXNewExpr(E);
290193326Sed  }
291193326Sed
292193326Sed  // Binary Operators.
293193326Sed  Value *EmitMul(const BinOpInfo &Ops) {
294193326Sed    if (CGF.getContext().getLangOptions().OverflowChecking
295193326Sed        && Ops.Ty->isSignedIntegerType())
296193326Sed      return EmitOverflowCheckedBinOp(Ops);
297193326Sed    return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
298193326Sed  }
299193326Sed  /// Create a binary op that checks for overflow.
300193326Sed  /// Currently only supports +, - and *.
301193326Sed  Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
302193326Sed  Value *EmitDiv(const BinOpInfo &Ops);
303193326Sed  Value *EmitRem(const BinOpInfo &Ops);
304193326Sed  Value *EmitAdd(const BinOpInfo &Ops);
305193326Sed  Value *EmitSub(const BinOpInfo &Ops);
306193326Sed  Value *EmitShl(const BinOpInfo &Ops);
307193326Sed  Value *EmitShr(const BinOpInfo &Ops);
308193326Sed  Value *EmitAnd(const BinOpInfo &Ops) {
309193326Sed    return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
310193326Sed  }
311193326Sed  Value *EmitXor(const BinOpInfo &Ops) {
312193326Sed    return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
313193326Sed  }
314193326Sed  Value *EmitOr (const BinOpInfo &Ops) {
315193326Sed    return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
316193326Sed  }
317193326Sed
318193326Sed  BinOpInfo EmitBinOps(const BinaryOperator *E);
319193326Sed  Value *EmitCompoundAssign(const CompoundAssignOperator *E,
320193326Sed                            Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
321193326Sed
322193326Sed  // Binary operators and binary compound assignment operators.
323193326Sed#define HANDLEBINOP(OP) \
324193326Sed  Value *VisitBin ## OP(const BinaryOperator *E) {                         \
325193326Sed    return Emit ## OP(EmitBinOps(E));                                      \
326193326Sed  }                                                                        \
327193326Sed  Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) {       \
328193326Sed    return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP);          \
329193326Sed  }
330193326Sed  HANDLEBINOP(Mul);
331193326Sed  HANDLEBINOP(Div);
332193326Sed  HANDLEBINOP(Rem);
333193326Sed  HANDLEBINOP(Add);
334193326Sed  HANDLEBINOP(Sub);
335193326Sed  HANDLEBINOP(Shl);
336193326Sed  HANDLEBINOP(Shr);
337193326Sed  HANDLEBINOP(And);
338193326Sed  HANDLEBINOP(Xor);
339193326Sed  HANDLEBINOP(Or);
340193326Sed#undef HANDLEBINOP
341193326Sed
342193326Sed  // Comparisons.
343193326Sed  Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
344193326Sed                     unsigned SICmpOpc, unsigned FCmpOpc);
345193326Sed#define VISITCOMP(CODE, UI, SI, FP) \
346193326Sed    Value *VisitBin##CODE(const BinaryOperator *E) { \
347193326Sed      return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
348193326Sed                         llvm::FCmpInst::FP); }
349193326Sed  VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
350193326Sed  VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
351193326Sed  VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
352193326Sed  VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
353193326Sed  VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
354193326Sed  VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
355193326Sed#undef VISITCOMP
356193326Sed
357193326Sed  Value *VisitBinAssign     (const BinaryOperator *E);
358193326Sed
359193326Sed  Value *VisitBinLAnd       (const BinaryOperator *E);
360193326Sed  Value *VisitBinLOr        (const BinaryOperator *E);
361193326Sed  Value *VisitBinComma      (const BinaryOperator *E);
362193326Sed
363193326Sed  // Other Operators.
364193326Sed  Value *VisitBlockExpr(const BlockExpr *BE);
365193326Sed  Value *VisitConditionalOperator(const ConditionalOperator *CO);
366193326Sed  Value *VisitChooseExpr(ChooseExpr *CE);
367193326Sed  Value *VisitVAArgExpr(VAArgExpr *VE);
368193326Sed  Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
369193326Sed    return CGF.EmitObjCStringLiteral(E);
370193326Sed  }
371193326Sed};
372193326Sed}  // end anonymous namespace.
373193326Sed
374193326Sed//===----------------------------------------------------------------------===//
375193326Sed//                                Utilities
376193326Sed//===----------------------------------------------------------------------===//
377193326Sed
378193326Sed/// EmitConversionToBool - Convert the specified expression value to a
379193326Sed/// boolean (i1) truth value.  This is equivalent to "Val != 0".
380193326SedValue *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
381193326Sed  assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs");
382193326Sed
383193326Sed  if (SrcType->isRealFloatingType()) {
384193326Sed    // Compare against 0.0 for fp scalars.
385193326Sed    llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
386193326Sed    return Builder.CreateFCmpUNE(Src, Zero, "tobool");
387193326Sed  }
388193326Sed
389193326Sed  assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
390193326Sed         "Unknown scalar type to convert");
391193326Sed
392193326Sed  // Because of the type rules of C, we often end up computing a logical value,
393193326Sed  // then zero extending it to int, then wanting it as a logical value again.
394193326Sed  // Optimize this common case.
395193326Sed  if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
396193326Sed    if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
397193326Sed      Value *Result = ZI->getOperand(0);
398193326Sed      // If there aren't any more uses, zap the instruction to save space.
399193326Sed      // Note that there can be more uses, for example if this
400193326Sed      // is the result of an assignment.
401193326Sed      if (ZI->use_empty())
402193326Sed        ZI->eraseFromParent();
403193326Sed      return Result;
404193326Sed    }
405193326Sed  }
406193326Sed
407193326Sed  // Compare against an integer or pointer null.
408193326Sed  llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
409193326Sed  return Builder.CreateICmpNE(Src, Zero, "tobool");
410193326Sed}
411193326Sed
412193326Sed/// EmitScalarConversion - Emit a conversion from the specified type to the
413193326Sed/// specified destination type, both of which are LLVM scalar types.
414193326SedValue *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
415193326Sed                                               QualType DstType) {
416193326Sed  SrcType = CGF.getContext().getCanonicalType(SrcType);
417193326Sed  DstType = CGF.getContext().getCanonicalType(DstType);
418193326Sed  if (SrcType == DstType) return Src;
419193326Sed
420193326Sed  if (DstType->isVoidType()) return 0;
421193326Sed
422193326Sed  // Handle conversions to bool first, they are special: comparisons against 0.
423193326Sed  if (DstType->isBooleanType())
424193326Sed    return EmitConversionToBool(Src, SrcType);
425193326Sed
426193326Sed  const llvm::Type *DstTy = ConvertType(DstType);
427193326Sed
428193326Sed  // Ignore conversions like int -> uint.
429193326Sed  if (Src->getType() == DstTy)
430193326Sed    return Src;
431193326Sed
432193326Sed  // Handle pointer conversions next: pointers can only be converted
433193326Sed  // to/from other pointers and integers. Check for pointer types in
434193326Sed  // terms of LLVM, as some native types (like Obj-C id) may map to a
435193326Sed  // pointer type.
436193326Sed  if (isa<llvm::PointerType>(DstTy)) {
437193326Sed    // The source value may be an integer, or a pointer.
438193326Sed    if (isa<llvm::PointerType>(Src->getType()))
439193326Sed      return Builder.CreateBitCast(Src, DstTy, "conv");
440193326Sed    assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
441193326Sed    // First, convert to the correct width so that we control the kind of
442193326Sed    // extension.
443193326Sed    const llvm::Type *MiddleTy = llvm::IntegerType::get(CGF.LLVMPointerWidth);
444193326Sed    bool InputSigned = SrcType->isSignedIntegerType();
445193326Sed    llvm::Value* IntResult =
446193326Sed        Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
447193326Sed    // Then, cast to pointer.
448193326Sed    return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
449193326Sed  }
450193326Sed
451193326Sed  if (isa<llvm::PointerType>(Src->getType())) {
452193326Sed    // Must be an ptr to int cast.
453193326Sed    assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
454193326Sed    return Builder.CreatePtrToInt(Src, DstTy, "conv");
455193326Sed  }
456193326Sed
457193326Sed  // A scalar can be splatted to an extended vector of the same element type
458193326Sed  if (DstType->isExtVectorType() && !isa<VectorType>(SrcType)) {
459193326Sed    // Cast the scalar to element type
460193326Sed    QualType EltTy = DstType->getAsExtVectorType()->getElementType();
461193326Sed    llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
462193326Sed
463193326Sed    // Insert the element in element zero of an undef vector
464193326Sed    llvm::Value *UnV = llvm::UndefValue::get(DstTy);
465193326Sed    llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
466193326Sed    UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
467193326Sed
468193326Sed    // Splat the element across to all elements
469193326Sed    llvm::SmallVector<llvm::Constant*, 16> Args;
470193326Sed    unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
471193326Sed    for (unsigned i = 0; i < NumElements; i++)
472193326Sed      Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
473193326Sed
474193326Sed    llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
475193326Sed    llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
476193326Sed    return Yay;
477193326Sed  }
478193326Sed
479193326Sed  // Allow bitcast from vector to integer/fp of the same size.
480193326Sed  if (isa<llvm::VectorType>(Src->getType()) ||
481193326Sed      isa<llvm::VectorType>(DstTy))
482193326Sed    return Builder.CreateBitCast(Src, DstTy, "conv");
483193326Sed
484193326Sed  // Finally, we have the arithmetic types: real int/float.
485193326Sed  if (isa<llvm::IntegerType>(Src->getType())) {
486193326Sed    bool InputSigned = SrcType->isSignedIntegerType();
487193326Sed    if (isa<llvm::IntegerType>(DstTy))
488193326Sed      return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
489193326Sed    else if (InputSigned)
490193326Sed      return Builder.CreateSIToFP(Src, DstTy, "conv");
491193326Sed    else
492193326Sed      return Builder.CreateUIToFP(Src, DstTy, "conv");
493193326Sed  }
494193326Sed
495193326Sed  assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
496193326Sed  if (isa<llvm::IntegerType>(DstTy)) {
497193326Sed    if (DstType->isSignedIntegerType())
498193326Sed      return Builder.CreateFPToSI(Src, DstTy, "conv");
499193326Sed    else
500193326Sed      return Builder.CreateFPToUI(Src, DstTy, "conv");
501193326Sed  }
502193326Sed
503193326Sed  assert(DstTy->isFloatingPoint() && "Unknown real conversion");
504193326Sed  if (DstTy->getTypeID() < Src->getType()->getTypeID())
505193326Sed    return Builder.CreateFPTrunc(Src, DstTy, "conv");
506193326Sed  else
507193326Sed    return Builder.CreateFPExt(Src, DstTy, "conv");
508193326Sed}
509193326Sed
510193326Sed/// EmitComplexToScalarConversion - Emit a conversion from the specified
511193326Sed/// complex type to the specified destination type, where the destination
512193326Sed/// type is an LLVM scalar type.
513193326SedValue *ScalarExprEmitter::
514193326SedEmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
515193326Sed                              QualType SrcTy, QualType DstTy) {
516193326Sed  // Get the source element type.
517193326Sed  SrcTy = SrcTy->getAsComplexType()->getElementType();
518193326Sed
519193326Sed  // Handle conversions to bool first, they are special: comparisons against 0.
520193326Sed  if (DstTy->isBooleanType()) {
521193326Sed    //  Complex != 0  -> (Real != 0) | (Imag != 0)
522193326Sed    Src.first  = EmitScalarConversion(Src.first, SrcTy, DstTy);
523193326Sed    Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
524193326Sed    return Builder.CreateOr(Src.first, Src.second, "tobool");
525193326Sed  }
526193326Sed
527193326Sed  // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
528193326Sed  // the imaginary part of the complex value is discarded and the value of the
529193326Sed  // real part is converted according to the conversion rules for the
530193326Sed  // corresponding real type.
531193326Sed  return EmitScalarConversion(Src.first, SrcTy, DstTy);
532193326Sed}
533193326Sed
534193326Sed
535193326Sed//===----------------------------------------------------------------------===//
536193326Sed//                            Visitor Methods
537193326Sed//===----------------------------------------------------------------------===//
538193326Sed
539193326SedValue *ScalarExprEmitter::VisitExpr(Expr *E) {
540193326Sed  CGF.ErrorUnsupported(E, "scalar expression");
541193326Sed  if (E->getType()->isVoidType())
542193326Sed    return 0;
543193326Sed  return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
544193326Sed}
545193326Sed
546193326SedValue *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
547193326Sed  llvm::SmallVector<llvm::Constant*, 32> indices;
548193326Sed  for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
549193326Sed    indices.push_back(cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i))));
550193326Sed  }
551193326Sed  Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
552193326Sed  Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
553193326Sed  Value* SV = llvm::ConstantVector::get(indices.begin(), indices.size());
554193326Sed  return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
555193326Sed}
556193326Sed
557193326SedValue *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
558193326Sed  TestAndClearIgnoreResultAssign();
559193326Sed
560193326Sed  // Emit subscript expressions in rvalue context's.  For most cases, this just
561193326Sed  // loads the lvalue formed by the subscript expr.  However, we have to be
562193326Sed  // careful, because the base of a vector subscript is occasionally an rvalue,
563193326Sed  // so we can't get it as an lvalue.
564193326Sed  if (!E->getBase()->getType()->isVectorType())
565193326Sed    return EmitLoadOfLValue(E);
566193326Sed
567193326Sed  // Handle the vector case.  The base must be a vector, the index must be an
568193326Sed  // integer value.
569193326Sed  Value *Base = Visit(E->getBase());
570193326Sed  Value *Idx  = Visit(E->getIdx());
571193326Sed  bool IdxSigned = E->getIdx()->getType()->isSignedIntegerType();
572193326Sed  Idx = Builder.CreateIntCast(Idx, llvm::Type::Int32Ty, IdxSigned,
573193326Sed                              "vecidxcast");
574193326Sed  return Builder.CreateExtractElement(Base, Idx, "vecext");
575193326Sed}
576193326Sed
577193326Sed/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
578193326Sed/// also handle things like function to pointer-to-function decay, and array to
579193326Sed/// pointer decay.
580193326SedValue *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
581193326Sed  const Expr *Op = E->getSubExpr();
582193326Sed
583193326Sed  // If this is due to array->pointer conversion, emit the array expression as
584193326Sed  // an l-value.
585193326Sed  if (Op->getType()->isArrayType()) {
586193326Sed    Value *V = EmitLValue(Op).getAddress();  // Bitfields can't be arrays.
587193326Sed
588193326Sed    // Note that VLA pointers are always decayed, so we don't need to do
589193326Sed    // anything here.
590193326Sed    if (!Op->getType()->isVariableArrayType()) {
591193326Sed      assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
592193326Sed      assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
593193326Sed                                 ->getElementType()) &&
594193326Sed             "Expected pointer to array");
595193326Sed      V = Builder.CreateStructGEP(V, 0, "arraydecay");
596193326Sed    }
597193326Sed
598193326Sed    // The resultant pointer type can be implicitly casted to other pointer
599193326Sed    // types as well (e.g. void*) and can be implicitly converted to integer.
600193326Sed    const llvm::Type *DestTy = ConvertType(E->getType());
601193326Sed    if (V->getType() != DestTy) {
602193326Sed      if (isa<llvm::PointerType>(DestTy))
603193326Sed        V = Builder.CreateBitCast(V, DestTy, "ptrconv");
604193326Sed      else {
605193326Sed        assert(isa<llvm::IntegerType>(DestTy) && "Unknown array decay");
606193326Sed        V = Builder.CreatePtrToInt(V, DestTy, "ptrconv");
607193326Sed      }
608193326Sed    }
609193326Sed    return V;
610193326Sed  }
611193326Sed
612193326Sed  return EmitCastExpr(Op, E->getType());
613193326Sed}
614193326Sed
615193326Sed
616193326Sed// VisitCastExpr - Emit code for an explicit or implicit cast.  Implicit casts
617193326Sed// have to handle a more broad range of conversions than explicit casts, as they
618193326Sed// handle things like function to ptr-to-function decay etc.
619193326SedValue *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
620193326Sed  if (!DestTy->isVoidType())
621193326Sed    TestAndClearIgnoreResultAssign();
622193326Sed
623193326Sed  // Handle cases where the source is an non-complex type.
624193326Sed
625193326Sed  if (!CGF.hasAggregateLLVMType(E->getType())) {
626193326Sed    Value *Src = Visit(const_cast<Expr*>(E));
627193326Sed
628193326Sed    // Use EmitScalarConversion to perform the conversion.
629193326Sed    return EmitScalarConversion(Src, E->getType(), DestTy);
630193326Sed  }
631193326Sed
632193326Sed  if (E->getType()->isAnyComplexType()) {
633193326Sed    // Handle cases where the source is a complex type.
634193326Sed    bool IgnoreImag = true;
635193326Sed    bool IgnoreImagAssign = true;
636193326Sed    bool IgnoreReal = IgnoreResultAssign;
637193326Sed    bool IgnoreRealAssign = IgnoreResultAssign;
638193326Sed    if (DestTy->isBooleanType())
639193326Sed      IgnoreImagAssign = IgnoreImag = false;
640193326Sed    else if (DestTy->isVoidType()) {
641193326Sed      IgnoreReal = IgnoreImag = false;
642193326Sed      IgnoreRealAssign = IgnoreImagAssign = true;
643193326Sed    }
644193326Sed    CodeGenFunction::ComplexPairTy V
645193326Sed      = CGF.EmitComplexExpr(E, IgnoreReal, IgnoreImag, IgnoreRealAssign,
646193326Sed                            IgnoreImagAssign);
647193326Sed    return EmitComplexToScalarConversion(V, E->getType(), DestTy);
648193326Sed  }
649193326Sed
650193326Sed  // Okay, this is a cast from an aggregate.  It must be a cast to void.  Just
651193326Sed  // evaluate the result and return.
652193326Sed  CGF.EmitAggExpr(E, 0, false, true);
653193326Sed  return 0;
654193326Sed}
655193326Sed
656193326SedValue *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
657193326Sed  return CGF.EmitCompoundStmt(*E->getSubStmt(),
658193326Sed                              !E->getType()->isVoidType()).getScalarVal();
659193326Sed}
660193326Sed
661193326SedValue *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
662193326Sed  return Builder.CreateLoad(CGF.GetAddrOfBlockDecl(E), false, "tmp");
663193326Sed}
664193326Sed
665193326Sed//===----------------------------------------------------------------------===//
666193326Sed//                             Unary Operators
667193326Sed//===----------------------------------------------------------------------===//
668193326Sed
669193326SedValue *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
670193326Sed                                             bool isInc, bool isPre) {
671193326Sed  LValue LV = EmitLValue(E->getSubExpr());
672193326Sed  QualType ValTy = E->getSubExpr()->getType();
673193326Sed  Value *InVal = CGF.EmitLoadOfLValue(LV, ValTy).getScalarVal();
674193326Sed
675193326Sed  int AmountVal = isInc ? 1 : -1;
676193326Sed
677193326Sed  if (ValTy->isPointerType() &&
678193326Sed      ValTy->getAsPointerType()->isVariableArrayType()) {
679193326Sed    // The amount of the addition/subtraction needs to account for the VLA size
680193326Sed    CGF.ErrorUnsupported(E, "VLA pointer inc/dec");
681193326Sed  }
682193326Sed
683193326Sed  Value *NextVal;
684193326Sed  if (const llvm::PointerType *PT =
685193326Sed         dyn_cast<llvm::PointerType>(InVal->getType())) {
686193326Sed    llvm::Constant *Inc =llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
687193326Sed    if (!isa<llvm::FunctionType>(PT->getElementType())) {
688193326Sed      NextVal = Builder.CreateGEP(InVal, Inc, "ptrincdec");
689193326Sed    } else {
690193326Sed      const llvm::Type *i8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
691193326Sed      NextVal = Builder.CreateBitCast(InVal, i8Ty, "tmp");
692193326Sed      NextVal = Builder.CreateGEP(NextVal, Inc, "ptrincdec");
693193326Sed      NextVal = Builder.CreateBitCast(NextVal, InVal->getType());
694193326Sed    }
695193326Sed  } else if (InVal->getType() == llvm::Type::Int1Ty && isInc) {
696193326Sed    // Bool++ is an interesting case, due to promotion rules, we get:
697193326Sed    // Bool++ -> Bool = Bool+1 -> Bool = (int)Bool+1 ->
698193326Sed    // Bool = ((int)Bool+1) != 0
699193326Sed    // An interesting aspect of this is that increment is always true.
700193326Sed    // Decrement does not have this property.
701193326Sed    NextVal = llvm::ConstantInt::getTrue();
702193326Sed  } else {
703193326Sed    // Add the inc/dec to the real part.
704193326Sed    if (isa<llvm::IntegerType>(InVal->getType()))
705193326Sed      NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
706193326Sed    else if (InVal->getType() == llvm::Type::FloatTy)
707193326Sed      NextVal =
708193326Sed        llvm::ConstantFP::get(llvm::APFloat(static_cast<float>(AmountVal)));
709193326Sed    else if (InVal->getType() == llvm::Type::DoubleTy)
710193326Sed      NextVal =
711193326Sed        llvm::ConstantFP::get(llvm::APFloat(static_cast<double>(AmountVal)));
712193326Sed    else {
713193326Sed      llvm::APFloat F(static_cast<float>(AmountVal));
714193326Sed      bool ignored;
715193326Sed      F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
716193326Sed                &ignored);
717193326Sed      NextVal = llvm::ConstantFP::get(F);
718193326Sed    }
719193326Sed    NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
720193326Sed  }
721193326Sed
722193326Sed  // Store the updated result through the lvalue.
723193326Sed  if (LV.isBitfield())
724193326Sed    CGF.EmitStoreThroughBitfieldLValue(RValue::get(NextVal), LV, ValTy,
725193326Sed                                       &NextVal);
726193326Sed  else
727193326Sed    CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV, ValTy);
728193326Sed
729193326Sed  // If this is a postinc, return the value read from memory, otherwise use the
730193326Sed  // updated value.
731193326Sed  return isPre ? NextVal : InVal;
732193326Sed}
733193326Sed
734193326Sed
735193326SedValue *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
736193326Sed  TestAndClearIgnoreResultAssign();
737193326Sed  Value *Op = Visit(E->getSubExpr());
738193326Sed  return Builder.CreateNeg(Op, "neg");
739193326Sed}
740193326Sed
741193326SedValue *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
742193326Sed  TestAndClearIgnoreResultAssign();
743193326Sed  Value *Op = Visit(E->getSubExpr());
744193326Sed  return Builder.CreateNot(Op, "neg");
745193326Sed}
746193326Sed
747193326SedValue *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
748193326Sed  // Compare operand to zero.
749193326Sed  Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
750193326Sed
751193326Sed  // Invert value.
752193326Sed  // TODO: Could dynamically modify easy computations here.  For example, if
753193326Sed  // the operand is an icmp ne, turn into icmp eq.
754193326Sed  BoolVal = Builder.CreateNot(BoolVal, "lnot");
755193326Sed
756193326Sed  // ZExt result to the expr type.
757193326Sed  return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
758193326Sed}
759193326Sed
760193326Sed/// VisitSizeOfAlignOfExpr - Return the size or alignment of the type of
761193326Sed/// argument of the sizeof expression as an integer.
762193326SedValue *
763193326SedScalarExprEmitter::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
764193326Sed  QualType TypeToSize = E->getTypeOfArgument();
765193326Sed  if (E->isSizeOf()) {
766193326Sed    if (const VariableArrayType *VAT =
767193326Sed          CGF.getContext().getAsVariableArrayType(TypeToSize)) {
768193326Sed      if (E->isArgumentType()) {
769193326Sed        // sizeof(type) - make sure to emit the VLA size.
770193326Sed        CGF.EmitVLASize(TypeToSize);
771193326Sed      } else {
772193326Sed        // C99 6.5.3.4p2: If the argument is an expression of type
773193326Sed        // VLA, it is evaluated.
774193326Sed        CGF.EmitAnyExpr(E->getArgumentExpr());
775193326Sed      }
776193326Sed
777193326Sed      return CGF.GetVLASize(VAT);
778193326Sed    }
779193326Sed  }
780193326Sed
781193326Sed  // If this isn't sizeof(vla), the result must be constant; use the
782193326Sed  // constant folding logic so we don't have to duplicate it here.
783193326Sed  Expr::EvalResult Result;
784193326Sed  E->Evaluate(Result, CGF.getContext());
785193326Sed  return llvm::ConstantInt::get(Result.Val.getInt());
786193326Sed}
787193326Sed
788193326SedValue *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
789193326Sed  Expr *Op = E->getSubExpr();
790193326Sed  if (Op->getType()->isAnyComplexType())
791193326Sed    return CGF.EmitComplexExpr(Op, false, true, false, true).first;
792193326Sed  return Visit(Op);
793193326Sed}
794193326SedValue *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
795193326Sed  Expr *Op = E->getSubExpr();
796193326Sed  if (Op->getType()->isAnyComplexType())
797193326Sed    return CGF.EmitComplexExpr(Op, true, false, true, false).second;
798193326Sed
799193326Sed  // __imag on a scalar returns zero.  Emit the subexpr to ensure side
800193326Sed  // effects are evaluated, but not the actual value.
801193326Sed  if (E->isLvalue(CGF.getContext()) == Expr::LV_Valid)
802193326Sed    CGF.EmitLValue(Op);
803193326Sed  else
804193326Sed    CGF.EmitScalarExpr(Op, true);
805193326Sed  return llvm::Constant::getNullValue(ConvertType(E->getType()));
806193326Sed}
807193326Sed
808193326SedValue *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E)
809193326Sed{
810193326Sed  Value* ResultAsPtr = EmitLValue(E->getSubExpr()).getAddress();
811193326Sed  const llvm::Type* ResultType = ConvertType(E->getType());
812193326Sed  return Builder.CreatePtrToInt(ResultAsPtr, ResultType, "offsetof");
813193326Sed}
814193326Sed
815193326Sed//===----------------------------------------------------------------------===//
816193326Sed//                           Binary Operators
817193326Sed//===----------------------------------------------------------------------===//
818193326Sed
819193326SedBinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
820193326Sed  TestAndClearIgnoreResultAssign();
821193326Sed  BinOpInfo Result;
822193326Sed  Result.LHS = Visit(E->getLHS());
823193326Sed  Result.RHS = Visit(E->getRHS());
824193326Sed  Result.Ty  = E->getType();
825193326Sed  Result.E = E;
826193326Sed  return Result;
827193326Sed}
828193326Sed
829193326SedValue *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
830193326Sed                      Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
831193326Sed  bool Ignore = TestAndClearIgnoreResultAssign();
832193326Sed  QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
833193326Sed
834193326Sed  BinOpInfo OpInfo;
835193326Sed
836193326Sed  if (E->getComputationResultType()->isAnyComplexType()) {
837193326Sed    // This needs to go through the complex expression emitter, but
838193326Sed    // it's a tad complicated to do that... I'm leaving it out for now.
839193326Sed    // (Note that we do actually need the imaginary part of the RHS for
840193326Sed    // multiplication and division.)
841193326Sed    CGF.ErrorUnsupported(E, "complex compound assignment");
842193326Sed    return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
843193326Sed  }
844193326Sed
845193326Sed  // Emit the RHS first.  __block variables need to have the rhs evaluated
846193326Sed  // first, plus this should improve codegen a little.
847193326Sed  OpInfo.RHS = Visit(E->getRHS());
848193326Sed  OpInfo.Ty = E->getComputationResultType();
849193326Sed  OpInfo.E = E;
850193326Sed  // Load/convert the LHS.
851193326Sed  LValue LHSLV = EmitLValue(E->getLHS());
852193326Sed  OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
853193326Sed  OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
854193326Sed                                    E->getComputationLHSType());
855193326Sed
856193326Sed  // Expand the binary operator.
857193326Sed  Value *Result = (this->*Func)(OpInfo);
858193326Sed
859193326Sed  // Convert the result back to the LHS type.
860193326Sed  Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
861193326Sed
862193326Sed  // Store the result value into the LHS lvalue. Bit-fields are
863193326Sed  // handled specially because the result is altered by the store,
864193326Sed  // i.e., [C99 6.5.16p1] 'An assignment expression has the value of
865193326Sed  // the left operand after the assignment...'.
866193326Sed  if (LHSLV.isBitfield()) {
867193326Sed    if (!LHSLV.isVolatileQualified()) {
868193326Sed      CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy,
869193326Sed                                         &Result);
870193326Sed      return Result;
871193326Sed    } else
872193326Sed      CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy);
873193326Sed  } else
874193326Sed    CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy);
875193326Sed  if (Ignore)
876193326Sed    return 0;
877193326Sed  return EmitLoadOfLValue(LHSLV, E->getType());
878193326Sed}
879193326Sed
880193326Sed
881193326SedValue *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
882193326Sed  if (Ops.LHS->getType()->isFPOrFPVector())
883193326Sed    return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
884193326Sed  else if (Ops.Ty->isUnsignedIntegerType())
885193326Sed    return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
886193326Sed  else
887193326Sed    return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
888193326Sed}
889193326Sed
890193326SedValue *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
891193326Sed  // Rem in C can't be a floating point type: C99 6.5.5p2.
892193326Sed  if (Ops.Ty->isUnsignedIntegerType())
893193326Sed    return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
894193326Sed  else
895193326Sed    return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
896193326Sed}
897193326Sed
898193326SedValue *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
899193326Sed  unsigned IID;
900193326Sed  unsigned OpID = 0;
901193326Sed
902193326Sed  switch (Ops.E->getOpcode()) {
903193326Sed  case BinaryOperator::Add:
904193326Sed  case BinaryOperator::AddAssign:
905193326Sed    OpID = 1;
906193326Sed    IID = llvm::Intrinsic::sadd_with_overflow;
907193326Sed    break;
908193326Sed  case BinaryOperator::Sub:
909193326Sed  case BinaryOperator::SubAssign:
910193326Sed    OpID = 2;
911193326Sed    IID = llvm::Intrinsic::ssub_with_overflow;
912193326Sed    break;
913193326Sed  case BinaryOperator::Mul:
914193326Sed  case BinaryOperator::MulAssign:
915193326Sed    OpID = 3;
916193326Sed    IID = llvm::Intrinsic::smul_with_overflow;
917193326Sed    break;
918193326Sed  default:
919193326Sed    assert(false && "Unsupported operation for overflow detection");
920193326Sed    IID = 0;
921193326Sed  }
922193326Sed  OpID <<= 1;
923193326Sed  OpID |= 1;
924193326Sed
925193326Sed  const llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
926193326Sed
927193326Sed  llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, &opTy, 1);
928193326Sed
929193326Sed  Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
930193326Sed  Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
931193326Sed  Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
932193326Sed
933193326Sed  // Branch in case of overflow.
934193326Sed  llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
935193326Sed  llvm::BasicBlock *overflowBB =
936193326Sed    CGF.createBasicBlock("overflow", CGF.CurFn);
937193326Sed  llvm::BasicBlock *continueBB =
938193326Sed    CGF.createBasicBlock("overflow.continue", CGF.CurFn);
939193326Sed
940193326Sed  Builder.CreateCondBr(overflow, overflowBB, continueBB);
941193326Sed
942193326Sed  // Handle overflow
943193326Sed
944193326Sed  Builder.SetInsertPoint(overflowBB);
945193326Sed
946193326Sed  // Handler is:
947193326Sed  // long long *__overflow_handler)(long long a, long long b, char op,
948193326Sed  // char width)
949193326Sed  std::vector<const llvm::Type*> handerArgTypes;
950193326Sed  handerArgTypes.push_back(llvm::Type::Int64Ty);
951193326Sed  handerArgTypes.push_back(llvm::Type::Int64Ty);
952193326Sed  handerArgTypes.push_back(llvm::Type::Int8Ty);
953193326Sed  handerArgTypes.push_back(llvm::Type::Int8Ty);
954193326Sed  llvm::FunctionType *handlerTy = llvm::FunctionType::get(llvm::Type::Int64Ty,
955193326Sed      handerArgTypes, false);
956193326Sed  llvm::Value *handlerFunction =
957193326Sed    CGF.CGM.getModule().getOrInsertGlobal("__overflow_handler",
958193326Sed        llvm::PointerType::getUnqual(handlerTy));
959193326Sed  handlerFunction = Builder.CreateLoad(handlerFunction);
960193326Sed
961193326Sed  llvm::Value *handlerResult = Builder.CreateCall4(handlerFunction,
962193326Sed      Builder.CreateSExt(Ops.LHS, llvm::Type::Int64Ty),
963193326Sed      Builder.CreateSExt(Ops.RHS, llvm::Type::Int64Ty),
964193326Sed      llvm::ConstantInt::get(llvm::Type::Int8Ty, OpID),
965193326Sed      llvm::ConstantInt::get(llvm::Type::Int8Ty,
966193326Sed        cast<llvm::IntegerType>(opTy)->getBitWidth()));
967193326Sed
968193326Sed  handlerResult = Builder.CreateTrunc(handlerResult, opTy);
969193326Sed
970193326Sed  Builder.CreateBr(continueBB);
971193326Sed
972193326Sed  // Set up the continuation
973193326Sed  Builder.SetInsertPoint(continueBB);
974193326Sed  // Get the correct result
975193326Sed  llvm::PHINode *phi = Builder.CreatePHI(opTy);
976193326Sed  phi->reserveOperandSpace(2);
977193326Sed  phi->addIncoming(result, initialBB);
978193326Sed  phi->addIncoming(handlerResult, overflowBB);
979193326Sed
980193326Sed  return phi;
981193326Sed}
982193326Sed
983193326SedValue *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
984193326Sed  if (!Ops.Ty->isPointerType()) {
985193326Sed    if (CGF.getContext().getLangOptions().OverflowChecking
986193326Sed        && Ops.Ty->isSignedIntegerType())
987193326Sed      return EmitOverflowCheckedBinOp(Ops);
988193326Sed    return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
989193326Sed  }
990193326Sed
991193326Sed  if (Ops.Ty->getAsPointerType()->isVariableArrayType()) {
992193326Sed    // The amount of the addition needs to account for the VLA size
993193326Sed    CGF.ErrorUnsupported(Ops.E, "VLA pointer addition");
994193326Sed  }
995193326Sed  Value *Ptr, *Idx;
996193326Sed  Expr *IdxExp;
997193326Sed  const PointerType *PT;
998193326Sed  if ((PT = Ops.E->getLHS()->getType()->getAsPointerType())) {
999193326Sed    Ptr = Ops.LHS;
1000193326Sed    Idx = Ops.RHS;
1001193326Sed    IdxExp = Ops.E->getRHS();
1002193326Sed  } else {                                           // int + pointer
1003193326Sed    PT = Ops.E->getRHS()->getType()->getAsPointerType();
1004193326Sed    assert(PT && "Invalid add expr");
1005193326Sed    Ptr = Ops.RHS;
1006193326Sed    Idx = Ops.LHS;
1007193326Sed    IdxExp = Ops.E->getLHS();
1008193326Sed  }
1009193326Sed
1010193326Sed  unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
1011193326Sed  if (Width < CGF.LLVMPointerWidth) {
1012193326Sed    // Zero or sign extend the pointer value based on whether the index is
1013193326Sed    // signed or not.
1014193326Sed    const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
1015193326Sed    if (IdxExp->getType()->isSignedIntegerType())
1016193326Sed      Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1017193326Sed    else
1018193326Sed      Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1019193326Sed  }
1020193326Sed
1021193326Sed  const QualType ElementType = PT->getPointeeType();
1022193326Sed  // Handle interface types, which are not represented with a concrete
1023193326Sed  // type.
1024193326Sed  if (const ObjCInterfaceType *OIT = dyn_cast<ObjCInterfaceType>(ElementType)) {
1025193326Sed    llvm::Value *InterfaceSize =
1026193326Sed      llvm::ConstantInt::get(Idx->getType(),
1027193326Sed                             CGF.getContext().getTypeSize(OIT) / 8);
1028193326Sed    Idx = Builder.CreateMul(Idx, InterfaceSize);
1029193326Sed    const llvm::Type *i8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
1030193326Sed    Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
1031193326Sed    Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
1032193326Sed    return Builder.CreateBitCast(Res, Ptr->getType());
1033193326Sed  }
1034193326Sed
1035193326Sed  // Explicitly handle GNU void* and function pointer arithmetic
1036193326Sed  // extensions. The GNU void* casts amount to no-ops since our void*
1037193326Sed  // type is i8*, but this is future proof.
1038193326Sed  if (ElementType->isVoidType() || ElementType->isFunctionType()) {
1039193326Sed    const llvm::Type *i8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
1040193326Sed    Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
1041193326Sed    Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
1042193326Sed    return Builder.CreateBitCast(Res, Ptr->getType());
1043193326Sed  }
1044193326Sed
1045193326Sed  return Builder.CreateGEP(Ptr, Idx, "add.ptr");
1046193326Sed}
1047193326Sed
1048193326SedValue *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
1049193326Sed  if (!isa<llvm::PointerType>(Ops.LHS->getType())) {
1050193326Sed    if (CGF.getContext().getLangOptions().OverflowChecking
1051193326Sed        && Ops.Ty->isSignedIntegerType())
1052193326Sed      return EmitOverflowCheckedBinOp(Ops);
1053193326Sed    return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
1054193326Sed  }
1055193326Sed
1056193326Sed  if (Ops.E->getLHS()->getType()->getAsPointerType()->isVariableArrayType()) {
1057193326Sed    // The amount of the addition needs to account for the VLA size for
1058193326Sed    // ptr-int
1059193326Sed    // The amount of the division needs to account for the VLA size for
1060193326Sed    // ptr-ptr.
1061193326Sed    CGF.ErrorUnsupported(Ops.E, "VLA pointer subtraction");
1062193326Sed  }
1063193326Sed
1064193326Sed  const QualType LHSType = Ops.E->getLHS()->getType();
1065193326Sed  const QualType LHSElementType = LHSType->getAsPointerType()->getPointeeType();
1066193326Sed  if (!isa<llvm::PointerType>(Ops.RHS->getType())) {
1067193326Sed    // pointer - int
1068193326Sed    Value *Idx = Ops.RHS;
1069193326Sed    unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
1070193326Sed    if (Width < CGF.LLVMPointerWidth) {
1071193326Sed      // Zero or sign extend the pointer value based on whether the index is
1072193326Sed      // signed or not.
1073193326Sed      const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
1074193326Sed      if (Ops.E->getRHS()->getType()->isSignedIntegerType())
1075193326Sed        Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1076193326Sed      else
1077193326Sed        Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1078193326Sed    }
1079193326Sed    Idx = Builder.CreateNeg(Idx, "sub.ptr.neg");
1080193326Sed
1081193326Sed    // Handle interface types, which are not represented with a concrete
1082193326Sed    // type.
1083193326Sed    if (const ObjCInterfaceType *OIT =
1084193326Sed        dyn_cast<ObjCInterfaceType>(LHSElementType)) {
1085193326Sed      llvm::Value *InterfaceSize =
1086193326Sed        llvm::ConstantInt::get(Idx->getType(),
1087193326Sed                               CGF.getContext().getTypeSize(OIT) / 8);
1088193326Sed      Idx = Builder.CreateMul(Idx, InterfaceSize);
1089193326Sed      const llvm::Type *i8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
1090193326Sed      Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1091193326Sed      Value *Res = Builder.CreateGEP(LHSCasted, Idx, "add.ptr");
1092193326Sed      return Builder.CreateBitCast(Res, Ops.LHS->getType());
1093193326Sed    }
1094193326Sed
1095193326Sed    // Explicitly handle GNU void* and function pointer arithmetic
1096193326Sed    // extensions. The GNU void* casts amount to no-ops since our
1097193326Sed    // void* type is i8*, but this is future proof.
1098193326Sed    if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
1099193326Sed      const llvm::Type *i8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
1100193326Sed      Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1101193326Sed      Value *Res = Builder.CreateGEP(LHSCasted, Idx, "sub.ptr");
1102193326Sed      return Builder.CreateBitCast(Res, Ops.LHS->getType());
1103193326Sed    }
1104193326Sed
1105193326Sed    return Builder.CreateGEP(Ops.LHS, Idx, "sub.ptr");
1106193326Sed  } else {
1107193326Sed    // pointer - pointer
1108193326Sed    Value *LHS = Ops.LHS;
1109193326Sed    Value *RHS = Ops.RHS;
1110193326Sed
1111193326Sed    uint64_t ElementSize;
1112193326Sed
1113193326Sed    // Handle GCC extension for pointer arithmetic on void* and function pointer
1114193326Sed    // types.
1115193326Sed    if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
1116193326Sed      ElementSize = 1;
1117193326Sed    } else {
1118193326Sed      ElementSize = CGF.getContext().getTypeSize(LHSElementType) / 8;
1119193326Sed    }
1120193326Sed
1121193326Sed    const llvm::Type *ResultType = ConvertType(Ops.Ty);
1122193326Sed    LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
1123193326Sed    RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1124193326Sed    Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
1125193326Sed
1126193326Sed    // Optimize out the shift for element size of 1.
1127193326Sed    if (ElementSize == 1)
1128193326Sed      return BytesBetween;
1129193326Sed
1130193326Sed    // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
1131193326Sed    // remainder.  As such, we handle common power-of-two cases here to generate
1132193326Sed    // better code. See PR2247.
1133193326Sed    if (llvm::isPowerOf2_64(ElementSize)) {
1134193326Sed      Value *ShAmt =
1135193326Sed        llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
1136193326Sed      return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
1137193326Sed    }
1138193326Sed
1139193326Sed    // Otherwise, do a full sdiv.
1140193326Sed    Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
1141193326Sed    return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
1142193326Sed  }
1143193326Sed}
1144193326Sed
1145193326SedValue *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
1146193326Sed  // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1147193326Sed  // RHS to the same size as the LHS.
1148193326Sed  Value *RHS = Ops.RHS;
1149193326Sed  if (Ops.LHS->getType() != RHS->getType())
1150193326Sed    RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
1151193326Sed
1152193326Sed  return Builder.CreateShl(Ops.LHS, RHS, "shl");
1153193326Sed}
1154193326Sed
1155193326SedValue *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
1156193326Sed  // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1157193326Sed  // RHS to the same size as the LHS.
1158193326Sed  Value *RHS = Ops.RHS;
1159193326Sed  if (Ops.LHS->getType() != RHS->getType())
1160193326Sed    RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
1161193326Sed
1162193326Sed  if (Ops.Ty->isUnsignedIntegerType())
1163193326Sed    return Builder.CreateLShr(Ops.LHS, RHS, "shr");
1164193326Sed  return Builder.CreateAShr(Ops.LHS, RHS, "shr");
1165193326Sed}
1166193326Sed
1167193326SedValue *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
1168193326Sed                                      unsigned SICmpOpc, unsigned FCmpOpc) {
1169193326Sed  TestAndClearIgnoreResultAssign();
1170193326Sed  Value *Result;
1171193326Sed  QualType LHSTy = E->getLHS()->getType();
1172193326Sed  if (!LHSTy->isAnyComplexType() && !LHSTy->isVectorType()) {
1173193326Sed    Value *LHS = Visit(E->getLHS());
1174193326Sed    Value *RHS = Visit(E->getRHS());
1175193326Sed
1176193326Sed    if (LHS->getType()->isFloatingPoint()) {
1177193326Sed      Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
1178193326Sed                                  LHS, RHS, "cmp");
1179193326Sed    } else if (LHSTy->isSignedIntegerType()) {
1180193326Sed      Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
1181193326Sed                                  LHS, RHS, "cmp");
1182193326Sed    } else {
1183193326Sed      // Unsigned integers and pointers.
1184193326Sed      Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1185193326Sed                                  LHS, RHS, "cmp");
1186193326Sed    }
1187193326Sed  } else if (LHSTy->isVectorType()) {
1188193326Sed    Value *LHS = Visit(E->getLHS());
1189193326Sed    Value *RHS = Visit(E->getRHS());
1190193326Sed
1191193326Sed    if (LHS->getType()->isFPOrFPVector()) {
1192193326Sed      Result = Builder.CreateVFCmp((llvm::CmpInst::Predicate)FCmpOpc,
1193193326Sed                                  LHS, RHS, "cmp");
1194193326Sed    } else if (LHSTy->isUnsignedIntegerType()) {
1195193326Sed      Result = Builder.CreateVICmp((llvm::CmpInst::Predicate)UICmpOpc,
1196193326Sed                                  LHS, RHS, "cmp");
1197193326Sed    } else {
1198193326Sed      // Signed integers and pointers.
1199193326Sed      Result = Builder.CreateVICmp((llvm::CmpInst::Predicate)SICmpOpc,
1200193326Sed                                  LHS, RHS, "cmp");
1201193326Sed    }
1202193326Sed    return Result;
1203193326Sed  } else {
1204193326Sed    // Complex Comparison: can only be an equality comparison.
1205193326Sed    CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
1206193326Sed    CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
1207193326Sed
1208193326Sed    QualType CETy = LHSTy->getAsComplexType()->getElementType();
1209193326Sed
1210193326Sed    Value *ResultR, *ResultI;
1211193326Sed    if (CETy->isRealFloatingType()) {
1212193326Sed      ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1213193326Sed                                   LHS.first, RHS.first, "cmp.r");
1214193326Sed      ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1215193326Sed                                   LHS.second, RHS.second, "cmp.i");
1216193326Sed    } else {
1217193326Sed      // Complex comparisons can only be equality comparisons.  As such, signed
1218193326Sed      // and unsigned opcodes are the same.
1219193326Sed      ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1220193326Sed                                   LHS.first, RHS.first, "cmp.r");
1221193326Sed      ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1222193326Sed                                   LHS.second, RHS.second, "cmp.i");
1223193326Sed    }
1224193326Sed
1225193326Sed    if (E->getOpcode() == BinaryOperator::EQ) {
1226193326Sed      Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1227193326Sed    } else {
1228193326Sed      assert(E->getOpcode() == BinaryOperator::NE &&
1229193326Sed             "Complex comparison other than == or != ?");
1230193326Sed      Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1231193326Sed    }
1232193326Sed  }
1233193326Sed
1234193326Sed  return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
1235193326Sed}
1236193326Sed
1237193326SedValue *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
1238193326Sed  bool Ignore = TestAndClearIgnoreResultAssign();
1239193326Sed
1240193326Sed  // __block variables need to have the rhs evaluated first, plus this should
1241193326Sed  // improve codegen just a little.
1242193326Sed  Value *RHS = Visit(E->getRHS());
1243193326Sed  LValue LHS = EmitLValue(E->getLHS());
1244193326Sed
1245193326Sed  // Store the value into the LHS.  Bit-fields are handled specially
1246193326Sed  // because the result is altered by the store, i.e., [C99 6.5.16p1]
1247193326Sed  // 'An assignment expression has the value of the left operand after
1248193326Sed  // the assignment...'.
1249193326Sed  if (LHS.isBitfield()) {
1250193326Sed    if (!LHS.isVolatileQualified()) {
1251193326Sed      CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType(),
1252193326Sed                                         &RHS);
1253193326Sed      return RHS;
1254193326Sed    } else
1255193326Sed      CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType());
1256193326Sed  } else
1257193326Sed    CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
1258193326Sed  if (Ignore)
1259193326Sed    return 0;
1260193326Sed  return EmitLoadOfLValue(LHS, E->getType());
1261193326Sed}
1262193326Sed
1263193326SedValue *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
1264193326Sed  // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
1265193326Sed  // If we have 1 && X, just emit X without inserting the control flow.
1266193326Sed  if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1267193326Sed    if (Cond == 1) { // If we have 1 && X, just emit X.
1268193326Sed      Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1269193326Sed      // ZExt result to int.
1270193326Sed      return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "land.ext");
1271193326Sed    }
1272193326Sed
1273193326Sed    // 0 && RHS: If it is safe, just elide the RHS, and return 0.
1274193326Sed    if (!CGF.ContainsLabel(E->getRHS()))
1275193326Sed      return llvm::Constant::getNullValue(CGF.LLVMIntTy);
1276193326Sed  }
1277193326Sed
1278193326Sed  llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
1279193326Sed  llvm::BasicBlock *RHSBlock  = CGF.createBasicBlock("land.rhs");
1280193326Sed
1281193326Sed  // Branch on the LHS first.  If it is false, go to the failure (cont) block.
1282193326Sed  CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
1283193326Sed
1284193326Sed  // Any edges into the ContBlock are now from an (indeterminate number of)
1285193326Sed  // edges from this first condition.  All of these values will be false.  Start
1286193326Sed  // setting up the PHI node in the Cont Block for this.
1287193326Sed  llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::Int1Ty, "", ContBlock);
1288193326Sed  PN->reserveOperandSpace(2);  // Normal case, two inputs.
1289193326Sed  for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1290193326Sed       PI != PE; ++PI)
1291193326Sed    PN->addIncoming(llvm::ConstantInt::getFalse(), *PI);
1292193326Sed
1293193326Sed  CGF.EmitBlock(RHSBlock);
1294193326Sed  Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1295193326Sed
1296193326Sed  // Reaquire the RHS block, as there may be subblocks inserted.
1297193326Sed  RHSBlock = Builder.GetInsertBlock();
1298193326Sed
1299193326Sed  // Emit an unconditional branch from this block to ContBlock.  Insert an entry
1300193326Sed  // into the phi node for the edge with the value of RHSCond.
1301193326Sed  CGF.EmitBlock(ContBlock);
1302193326Sed  PN->addIncoming(RHSCond, RHSBlock);
1303193326Sed
1304193326Sed  // ZExt result to int.
1305193326Sed  return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
1306193326Sed}
1307193326Sed
1308193326SedValue *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
1309193326Sed  // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
1310193326Sed  // If we have 0 || X, just emit X without inserting the control flow.
1311193326Sed  if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1312193326Sed    if (Cond == -1) { // If we have 0 || X, just emit X.
1313193326Sed      Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1314193326Sed      // ZExt result to int.
1315193326Sed      return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "lor.ext");
1316193326Sed    }
1317193326Sed
1318193326Sed    // 1 || RHS: If it is safe, just elide the RHS, and return 1.
1319193326Sed    if (!CGF.ContainsLabel(E->getRHS()))
1320193326Sed      return llvm::ConstantInt::get(CGF.LLVMIntTy, 1);
1321193326Sed  }
1322193326Sed
1323193326Sed  llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
1324193326Sed  llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
1325193326Sed
1326193326Sed  // Branch on the LHS first.  If it is true, go to the success (cont) block.
1327193326Sed  CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
1328193326Sed
1329193326Sed  // Any edges into the ContBlock are now from an (indeterminate number of)
1330193326Sed  // edges from this first condition.  All of these values will be true.  Start
1331193326Sed  // setting up the PHI node in the Cont Block for this.
1332193326Sed  llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::Int1Ty, "", ContBlock);
1333193326Sed  PN->reserveOperandSpace(2);  // Normal case, two inputs.
1334193326Sed  for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1335193326Sed       PI != PE; ++PI)
1336193326Sed    PN->addIncoming(llvm::ConstantInt::getTrue(), *PI);
1337193326Sed
1338193326Sed  // Emit the RHS condition as a bool value.
1339193326Sed  CGF.EmitBlock(RHSBlock);
1340193326Sed  Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1341193326Sed
1342193326Sed  // Reaquire the RHS block, as there may be subblocks inserted.
1343193326Sed  RHSBlock = Builder.GetInsertBlock();
1344193326Sed
1345193326Sed  // Emit an unconditional branch from this block to ContBlock.  Insert an entry
1346193326Sed  // into the phi node for the edge with the value of RHSCond.
1347193326Sed  CGF.EmitBlock(ContBlock);
1348193326Sed  PN->addIncoming(RHSCond, RHSBlock);
1349193326Sed
1350193326Sed  // ZExt result to int.
1351193326Sed  return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
1352193326Sed}
1353193326Sed
1354193326SedValue *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
1355193326Sed  CGF.EmitStmt(E->getLHS());
1356193326Sed  CGF.EnsureInsertPoint();
1357193326Sed  return Visit(E->getRHS());
1358193326Sed}
1359193326Sed
1360193326Sed//===----------------------------------------------------------------------===//
1361193326Sed//                             Other Operators
1362193326Sed//===----------------------------------------------------------------------===//
1363193326Sed
1364193326Sed/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
1365193326Sed/// expression is cheap enough and side-effect-free enough to evaluate
1366193326Sed/// unconditionally instead of conditionally.  This is used to convert control
1367193326Sed/// flow into selects in some cases.
1368193326Sedstatic bool isCheapEnoughToEvaluateUnconditionally(const Expr *E) {
1369193326Sed  if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
1370193326Sed    return isCheapEnoughToEvaluateUnconditionally(PE->getSubExpr());
1371193326Sed
1372193326Sed  // TODO: Allow anything we can constant fold to an integer or fp constant.
1373193326Sed  if (isa<IntegerLiteral>(E) || isa<CharacterLiteral>(E) ||
1374193326Sed      isa<FloatingLiteral>(E))
1375193326Sed    return true;
1376193326Sed
1377193326Sed  // Non-volatile automatic variables too, to get "cond ? X : Y" where
1378193326Sed  // X and Y are local variables.
1379193326Sed  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1380193326Sed    if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1381193326Sed      if (VD->hasLocalStorage() && !VD->getType().isVolatileQualified())
1382193326Sed        return true;
1383193326Sed
1384193326Sed  return false;
1385193326Sed}
1386193326Sed
1387193326Sed
1388193326SedValue *ScalarExprEmitter::
1389193326SedVisitConditionalOperator(const ConditionalOperator *E) {
1390193326Sed  TestAndClearIgnoreResultAssign();
1391193326Sed  // If the condition constant folds and can be elided, try to avoid emitting
1392193326Sed  // the condition and the dead arm.
1393193326Sed  if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getCond())){
1394193326Sed    Expr *Live = E->getLHS(), *Dead = E->getRHS();
1395193326Sed    if (Cond == -1)
1396193326Sed      std::swap(Live, Dead);
1397193326Sed
1398193326Sed    // If the dead side doesn't have labels we need, and if the Live side isn't
1399193326Sed    // the gnu missing ?: extension (which we could handle, but don't bother
1400193326Sed    // to), just emit the Live part.
1401193326Sed    if ((!Dead || !CGF.ContainsLabel(Dead)) &&  // No labels in dead part
1402193326Sed        Live)                                   // Live part isn't missing.
1403193326Sed      return Visit(Live);
1404193326Sed  }
1405193326Sed
1406193326Sed
1407193326Sed  // If this is a really simple expression (like x ? 4 : 5), emit this as a
1408193326Sed  // select instead of as control flow.  We can only do this if it is cheap and
1409193326Sed  // safe to evaluate the LHS and RHS unconditionally.
1410193326Sed  if (E->getLHS() && isCheapEnoughToEvaluateUnconditionally(E->getLHS()) &&
1411193326Sed      isCheapEnoughToEvaluateUnconditionally(E->getRHS())) {
1412193326Sed    llvm::Value *CondV = CGF.EvaluateExprAsBool(E->getCond());
1413193326Sed    llvm::Value *LHS = Visit(E->getLHS());
1414193326Sed    llvm::Value *RHS = Visit(E->getRHS());
1415193326Sed    return Builder.CreateSelect(CondV, LHS, RHS, "cond");
1416193326Sed  }
1417193326Sed
1418193326Sed
1419193326Sed  llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
1420193326Sed  llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
1421193326Sed  llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
1422193326Sed  Value *CondVal = 0;
1423193326Sed
1424193326Sed  // If we don't have the GNU missing condition extension, emit a branch on
1425193326Sed  // bool the normal way.
1426193326Sed  if (E->getLHS()) {
1427193326Sed    // Otherwise, just use EmitBranchOnBoolExpr to get small and simple code for
1428193326Sed    // the branch on bool.
1429193326Sed    CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
1430193326Sed  } else {
1431193326Sed    // Otherwise, for the ?: extension, evaluate the conditional and then
1432193326Sed    // convert it to bool the hard way.  We do this explicitly because we need
1433193326Sed    // the unconverted value for the missing middle value of the ?:.
1434193326Sed    CondVal = CGF.EmitScalarExpr(E->getCond());
1435193326Sed
1436193326Sed    // In some cases, EmitScalarConversion will delete the "CondVal" expression
1437193326Sed    // if there are no extra uses (an optimization).  Inhibit this by making an
1438193326Sed    // extra dead use, because we're going to add a use of CondVal later.  We
1439193326Sed    // don't use the builder for this, because we don't want it to get optimized
1440193326Sed    // away.  This leaves dead code, but the ?: extension isn't common.
1441193326Sed    new llvm::BitCastInst(CondVal, CondVal->getType(), "dummy?:holder",
1442193326Sed                          Builder.GetInsertBlock());
1443193326Sed
1444193326Sed    Value *CondBoolVal =
1445193326Sed      CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
1446193326Sed                               CGF.getContext().BoolTy);
1447193326Sed    Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
1448193326Sed  }
1449193326Sed
1450193326Sed  CGF.EmitBlock(LHSBlock);
1451193326Sed
1452193326Sed  // Handle the GNU extension for missing LHS.
1453193326Sed  Value *LHS;
1454193326Sed  if (E->getLHS())
1455193326Sed    LHS = Visit(E->getLHS());
1456193326Sed  else    // Perform promotions, to handle cases like "short ?: int"
1457193326Sed    LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
1458193326Sed
1459193326Sed  LHSBlock = Builder.GetInsertBlock();
1460193326Sed  CGF.EmitBranch(ContBlock);
1461193326Sed
1462193326Sed  CGF.EmitBlock(RHSBlock);
1463193326Sed
1464193326Sed  Value *RHS = Visit(E->getRHS());
1465193326Sed  RHSBlock = Builder.GetInsertBlock();
1466193326Sed  CGF.EmitBranch(ContBlock);
1467193326Sed
1468193326Sed  CGF.EmitBlock(ContBlock);
1469193326Sed
1470193326Sed  if (!LHS || !RHS) {
1471193326Sed    assert(E->getType()->isVoidType() && "Non-void value should have a value");
1472193326Sed    return 0;
1473193326Sed  }
1474193326Sed
1475193326Sed  // Create a PHI node for the real part.
1476193326Sed  llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
1477193326Sed  PN->reserveOperandSpace(2);
1478193326Sed  PN->addIncoming(LHS, LHSBlock);
1479193326Sed  PN->addIncoming(RHS, RHSBlock);
1480193326Sed  return PN;
1481193326Sed}
1482193326Sed
1483193326SedValue *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
1484193326Sed  return Visit(E->getChosenSubExpr(CGF.getContext()));
1485193326Sed}
1486193326Sed
1487193326SedValue *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
1488193326Sed  llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
1489193326Sed  llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
1490193326Sed
1491193326Sed  // If EmitVAArg fails, we fall back to the LLVM instruction.
1492193326Sed  if (!ArgPtr)
1493193326Sed    return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
1494193326Sed
1495193326Sed  // FIXME Volatility.
1496193326Sed  return Builder.CreateLoad(ArgPtr);
1497193326Sed}
1498193326Sed
1499193326SedValue *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *BE) {
1500193326Sed  return CGF.BuildBlockLiteralTmp(BE);
1501193326Sed}
1502193326Sed
1503193326Sed//===----------------------------------------------------------------------===//
1504193326Sed//                         Entry Point into this File
1505193326Sed//===----------------------------------------------------------------------===//
1506193326Sed
1507193326Sed/// EmitScalarExpr - Emit the computation of the specified expression of
1508193326Sed/// scalar type, ignoring the result.
1509193326SedValue *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
1510193326Sed  assert(E && !hasAggregateLLVMType(E->getType()) &&
1511193326Sed         "Invalid scalar expression to emit");
1512193326Sed
1513193326Sed  return ScalarExprEmitter(*this, IgnoreResultAssign)
1514193326Sed    .Visit(const_cast<Expr*>(E));
1515193326Sed}
1516193326Sed
1517193326Sed/// EmitScalarConversion - Emit a conversion from the specified type to the
1518193326Sed/// specified destination type, both of which are LLVM scalar types.
1519193326SedValue *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
1520193326Sed                                             QualType DstTy) {
1521193326Sed  assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
1522193326Sed         "Invalid scalar expression to emit");
1523193326Sed  return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
1524193326Sed}
1525193326Sed
1526193326Sed/// EmitComplexToScalarConversion - Emit a conversion from the specified
1527193326Sed/// complex type to the specified destination type, where the destination
1528193326Sed/// type is an LLVM scalar type.
1529193326SedValue *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
1530193326Sed                                                      QualType SrcTy,
1531193326Sed                                                      QualType DstTy) {
1532193326Sed  assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
1533193326Sed         "Invalid complex -> scalar conversion");
1534193326Sed  return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
1535193326Sed                                                                DstTy);
1536193326Sed}
1537193326Sed
1538193326SedValue *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) {
1539193326Sed  assert(V1->getType() == V2->getType() &&
1540193326Sed         "Vector operands must be of the same type");
1541193326Sed  unsigned NumElements =
1542193326Sed    cast<llvm::VectorType>(V1->getType())->getNumElements();
1543193326Sed
1544193326Sed  va_list va;
1545193326Sed  va_start(va, V2);
1546193326Sed
1547193326Sed  llvm::SmallVector<llvm::Constant*, 16> Args;
1548193326Sed  for (unsigned i = 0; i < NumElements; i++) {
1549193326Sed    int n = va_arg(va, int);
1550193326Sed    assert(n >= 0 && n < (int)NumElements * 2 &&
1551193326Sed           "Vector shuffle index out of bounds!");
1552193326Sed    Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, n));
1553193326Sed  }
1554193326Sed
1555193326Sed  const char *Name = va_arg(va, const char *);
1556193326Sed  va_end(va);
1557193326Sed
1558193326Sed  llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
1559193326Sed
1560193326Sed  return Builder.CreateShuffleVector(V1, V2, Mask, Name);
1561193326Sed}
1562193326Sed
1563193326Sedllvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals,
1564193326Sed                                         unsigned NumVals, bool isSplat) {
1565193326Sed  llvm::Value *Vec
1566193326Sed    = llvm::UndefValue::get(llvm::VectorType::get(Vals[0]->getType(), NumVals));
1567193326Sed
1568193326Sed  for (unsigned i = 0, e = NumVals; i != e; ++i) {
1569193326Sed    llvm::Value *Val = isSplat ? Vals[0] : Vals[i];
1570193326Sed    llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
1571193326Sed    Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp");
1572193326Sed  }
1573193326Sed
1574193326Sed  return Vec;
1575193326Sed}
1576