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