]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - contrib/llvm/tools/clang/lib/CodeGen/CGExprScalar.cpp
MFC r234353:
[FreeBSD/stable/9.git] / contrib / llvm / tools / clang / 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 "clang/Frontend/CodeGenOptions.h"
15 #include "CodeGenFunction.h"
16 #include "CGCXXABI.h"
17 #include "CGObjCRuntime.h"
18 #include "CodeGenModule.h"
19 #include "CGDebugInfo.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/RecordLayout.h"
23 #include "clang/AST/StmtVisitor.h"
24 #include "clang/Basic/TargetInfo.h"
25 #include "llvm/Constants.h"
26 #include "llvm/Function.h"
27 #include "llvm/GlobalVariable.h"
28 #include "llvm/Intrinsics.h"
29 #include "llvm/Module.h"
30 #include "llvm/Support/CFG.h"
31 #include "llvm/Target/TargetData.h"
32 #include <cstdarg>
33
34 using namespace clang;
35 using namespace CodeGen;
36 using llvm::Value;
37
38 //===----------------------------------------------------------------------===//
39 //                         Scalar Expression Emitter
40 //===----------------------------------------------------------------------===//
41
42 namespace {
43 struct BinOpInfo {
44   Value *LHS;
45   Value *RHS;
46   QualType Ty;  // Computation Type.
47   BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform
48   const Expr *E;      // Entire expr, for error unsupported.  May not be binop.
49 };
50
51 static bool MustVisitNullValue(const Expr *E) {
52   // If a null pointer expression's type is the C++0x nullptr_t, then
53   // it's not necessarily a simple constant and it must be evaluated
54   // for its potential side effects.
55   return E->getType()->isNullPtrType();
56 }
57
58 class ScalarExprEmitter
59   : public StmtVisitor<ScalarExprEmitter, Value*> {
60   CodeGenFunction &CGF;
61   CGBuilderTy &Builder;
62   bool IgnoreResultAssign;
63   llvm::LLVMContext &VMContext;
64 public:
65
66   ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
67     : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
68       VMContext(cgf.getLLVMContext()) {
69   }
70
71   //===--------------------------------------------------------------------===//
72   //                               Utilities
73   //===--------------------------------------------------------------------===//
74
75   bool TestAndClearIgnoreResultAssign() {
76     bool I = IgnoreResultAssign;
77     IgnoreResultAssign = false;
78     return I;
79   }
80
81   llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
82   LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
83   LValue EmitCheckedLValue(const Expr *E) { return CGF.EmitCheckedLValue(E); }
84
85   Value *EmitLoadOfLValue(LValue LV) {
86     return CGF.EmitLoadOfLValue(LV).getScalarVal();
87   }
88
89   /// EmitLoadOfLValue - Given an expression with complex type that represents a
90   /// value l-value, this method emits the address of the l-value, then loads
91   /// and returns the result.
92   Value *EmitLoadOfLValue(const Expr *E) {
93     return EmitLoadOfLValue(EmitCheckedLValue(E));
94   }
95
96   /// EmitConversionToBool - Convert the specified expression value to a
97   /// boolean (i1) truth value.  This is equivalent to "Val != 0".
98   Value *EmitConversionToBool(Value *Src, QualType DstTy);
99
100   /// EmitScalarConversion - Emit a conversion from the specified type to the
101   /// specified destination type, both of which are LLVM scalar types.
102   Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
103
104   /// EmitComplexToScalarConversion - Emit a conversion from the specified
105   /// complex type to the specified destination type, where the destination type
106   /// is an LLVM scalar type.
107   Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
108                                        QualType SrcTy, QualType DstTy);
109
110   /// EmitNullValue - Emit a value that corresponds to null for the given type.
111   Value *EmitNullValue(QualType Ty);
112
113   /// EmitFloatToBoolConversion - Perform an FP to boolean conversion.
114   Value *EmitFloatToBoolConversion(Value *V) {
115     // Compare against 0.0 for fp scalars.
116     llvm::Value *Zero = llvm::Constant::getNullValue(V->getType());
117     return Builder.CreateFCmpUNE(V, Zero, "tobool");
118   }
119
120   /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion.
121   Value *EmitPointerToBoolConversion(Value *V) {
122     Value *Zero = llvm::ConstantPointerNull::get(
123                                       cast<llvm::PointerType>(V->getType()));
124     return Builder.CreateICmpNE(V, Zero, "tobool");
125   }
126
127   Value *EmitIntToBoolConversion(Value *V) {
128     // Because of the type rules of C, we often end up computing a
129     // logical value, then zero extending it to int, then wanting it
130     // as a logical value again.  Optimize this common case.
131     if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) {
132       if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) {
133         Value *Result = ZI->getOperand(0);
134         // If there aren't any more uses, zap the instruction to save space.
135         // Note that there can be more uses, for example if this
136         // is the result of an assignment.
137         if (ZI->use_empty())
138           ZI->eraseFromParent();
139         return Result;
140       }
141     }
142
143     return Builder.CreateIsNotNull(V, "tobool");
144   }
145
146   //===--------------------------------------------------------------------===//
147   //                            Visitor Methods
148   //===--------------------------------------------------------------------===//
149
150   Value *Visit(Expr *E) {
151     return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
152   }
153     
154   Value *VisitStmt(Stmt *S) {
155     S->dump(CGF.getContext().getSourceManager());
156     llvm_unreachable("Stmt can't have complex result type!");
157   }
158   Value *VisitExpr(Expr *S);
159   
160   Value *VisitParenExpr(ParenExpr *PE) {
161     return Visit(PE->getSubExpr()); 
162   }
163   Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
164     return Visit(E->getReplacement()); 
165   }
166   Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
167     return Visit(GE->getResultExpr());
168   }
169
170   // Leaves.
171   Value *VisitIntegerLiteral(const IntegerLiteral *E) {
172     return Builder.getInt(E->getValue());
173   }
174   Value *VisitFloatingLiteral(const FloatingLiteral *E) {
175     return llvm::ConstantFP::get(VMContext, E->getValue());
176   }
177   Value *VisitCharacterLiteral(const CharacterLiteral *E) {
178     return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
179   }
180   Value *VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
181     return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
182   }
183   Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
184     return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
185   }
186   Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
187     return EmitNullValue(E->getType());
188   }
189   Value *VisitGNUNullExpr(const GNUNullExpr *E) {
190     return EmitNullValue(E->getType());
191   }
192   Value *VisitOffsetOfExpr(OffsetOfExpr *E);
193   Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
194   Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
195     llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
196     return Builder.CreateBitCast(V, ConvertType(E->getType()));
197   }
198
199   Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
200     return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength());
201   }
202
203   Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) {
204     return CGF.EmitPseudoObjectRValue(E).getScalarVal();
205   }
206
207   Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
208     if (E->isGLValue())
209       return EmitLoadOfLValue(CGF.getOpaqueLValueMapping(E));
210
211     // Otherwise, assume the mapping is the scalar directly.
212     return CGF.getOpaqueRValueMapping(E).getScalarVal();
213   }
214
215   // l-values.
216   Value *VisitDeclRefExpr(DeclRefExpr *E) {
217     if (CodeGenFunction::ConstantEmission result = CGF.tryEmitAsConstant(E)) {
218       if (result.isReference())
219         return EmitLoadOfLValue(result.getReferenceLValue(CGF, E));
220       return result.getValue();
221     }
222     return EmitLoadOfLValue(E);
223   }
224
225   Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
226     return CGF.EmitObjCSelectorExpr(E);
227   }
228   Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
229     return CGF.EmitObjCProtocolExpr(E);
230   }
231   Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
232     return EmitLoadOfLValue(E);
233   }
234   Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
235     if (E->getMethodDecl() && 
236         E->getMethodDecl()->getResultType()->isReferenceType())
237       return EmitLoadOfLValue(E);
238     return CGF.EmitObjCMessageExpr(E).getScalarVal();
239   }
240
241   Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
242     LValue LV = CGF.EmitObjCIsaExpr(E);
243     Value *V = CGF.EmitLoadOfLValue(LV).getScalarVal();
244     return V;
245   }
246
247   Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
248   Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
249   Value *VisitMemberExpr(MemberExpr *E);
250   Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
251   Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
252     return EmitLoadOfLValue(E);
253   }
254
255   Value *VisitInitListExpr(InitListExpr *E);
256
257   Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
258     return CGF.CGM.EmitNullConstant(E->getType());
259   }
260   Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
261     if (E->getType()->isVariablyModifiedType())
262       CGF.EmitVariablyModifiedType(E->getType());
263     return VisitCastExpr(E);
264   }
265   Value *VisitCastExpr(CastExpr *E);
266
267   Value *VisitCallExpr(const CallExpr *E) {
268     if (E->getCallReturnType()->isReferenceType())
269       return EmitLoadOfLValue(E);
270
271     return CGF.EmitCallExpr(E).getScalarVal();
272   }
273
274   Value *VisitStmtExpr(const StmtExpr *E);
275
276   // Unary Operators.
277   Value *VisitUnaryPostDec(const UnaryOperator *E) {
278     LValue LV = EmitLValue(E->getSubExpr());
279     return EmitScalarPrePostIncDec(E, LV, false, false);
280   }
281   Value *VisitUnaryPostInc(const UnaryOperator *E) {
282     LValue LV = EmitLValue(E->getSubExpr());
283     return EmitScalarPrePostIncDec(E, LV, true, false);
284   }
285   Value *VisitUnaryPreDec(const UnaryOperator *E) {
286     LValue LV = EmitLValue(E->getSubExpr());
287     return EmitScalarPrePostIncDec(E, LV, false, true);
288   }
289   Value *VisitUnaryPreInc(const UnaryOperator *E) {
290     LValue LV = EmitLValue(E->getSubExpr());
291     return EmitScalarPrePostIncDec(E, LV, true, true);
292   }
293
294   llvm::Value *EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
295                                                llvm::Value *InVal,
296                                                llvm::Value *NextVal,
297                                                bool IsInc);
298
299   llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
300                                        bool isInc, bool isPre);
301
302     
303   Value *VisitUnaryAddrOf(const UnaryOperator *E) {
304     if (isa<MemberPointerType>(E->getType())) // never sugared
305       return CGF.CGM.getMemberPointerConstant(E);
306
307     return EmitLValue(E->getSubExpr()).getAddress();
308   }
309   Value *VisitUnaryDeref(const UnaryOperator *E) {
310     if (E->getType()->isVoidType())
311       return Visit(E->getSubExpr()); // the actual value should be unused
312     return EmitLoadOfLValue(E);
313   }
314   Value *VisitUnaryPlus(const UnaryOperator *E) {
315     // This differs from gcc, though, most likely due to a bug in gcc.
316     TestAndClearIgnoreResultAssign();
317     return Visit(E->getSubExpr());
318   }
319   Value *VisitUnaryMinus    (const UnaryOperator *E);
320   Value *VisitUnaryNot      (const UnaryOperator *E);
321   Value *VisitUnaryLNot     (const UnaryOperator *E);
322   Value *VisitUnaryReal     (const UnaryOperator *E);
323   Value *VisitUnaryImag     (const UnaryOperator *E);
324   Value *VisitUnaryExtension(const UnaryOperator *E) {
325     return Visit(E->getSubExpr());
326   }
327     
328   // C++
329   Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) {
330     return EmitLoadOfLValue(E);
331   }
332     
333   Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
334     return Visit(DAE->getExpr());
335   }
336   Value *VisitCXXThisExpr(CXXThisExpr *TE) {
337     return CGF.LoadCXXThis();
338   }
339
340   Value *VisitExprWithCleanups(ExprWithCleanups *E) {
341     CGF.enterFullExpression(E);
342     CodeGenFunction::RunCleanupsScope Scope(CGF);
343     return Visit(E->getSubExpr());
344   }
345   Value *VisitCXXNewExpr(const CXXNewExpr *E) {
346     return CGF.EmitCXXNewExpr(E);
347   }
348   Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
349     CGF.EmitCXXDeleteExpr(E);
350     return 0;
351   }
352   Value *VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
353     return Builder.getInt1(E->getValue());
354   }
355
356   Value *VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
357     return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
358   }
359
360   Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
361     return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue());
362   }
363
364   Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
365     return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
366   }
367
368   Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
369     // C++ [expr.pseudo]p1:
370     //   The result shall only be used as the operand for the function call
371     //   operator (), and the result of such a call has type void. The only
372     //   effect is the evaluation of the postfix-expression before the dot or
373     //   arrow.
374     CGF.EmitScalarExpr(E->getBase());
375     return 0;
376   }
377
378   Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
379     return EmitNullValue(E->getType());
380   }
381
382   Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
383     CGF.EmitCXXThrowExpr(E);
384     return 0;
385   }
386
387   Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
388     return Builder.getInt1(E->getValue());
389   }
390
391   // Binary Operators.
392   Value *EmitMul(const BinOpInfo &Ops) {
393     if (Ops.Ty->isSignedIntegerOrEnumerationType()) {
394       switch (CGF.getContext().getLangOpts().getSignedOverflowBehavior()) {
395       case LangOptions::SOB_Undefined:
396         return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
397       case LangOptions::SOB_Defined:
398         return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
399       case LangOptions::SOB_Trapping:
400         return EmitOverflowCheckedBinOp(Ops);
401       }
402     }
403     
404     if (Ops.LHS->getType()->isFPOrFPVectorTy())
405       return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
406     return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
407   }
408   bool isTrapvOverflowBehavior() {
409     return CGF.getContext().getLangOpts().getSignedOverflowBehavior() 
410                == LangOptions::SOB_Trapping; 
411   }
412   /// Create a binary op that checks for overflow.
413   /// Currently only supports +, - and *.
414   Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
415   // Emit the overflow BB when -ftrapv option is activated. 
416   void EmitOverflowBB(llvm::BasicBlock *overflowBB) {
417     Builder.SetInsertPoint(overflowBB);
418     llvm::Function *Trap = CGF.CGM.getIntrinsic(llvm::Intrinsic::trap);
419     Builder.CreateCall(Trap);
420     Builder.CreateUnreachable();
421   }
422   // Check for undefined division and modulus behaviors.
423   void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops, 
424                                                   llvm::Value *Zero,bool isDiv);
425   Value *EmitDiv(const BinOpInfo &Ops);
426   Value *EmitRem(const BinOpInfo &Ops);
427   Value *EmitAdd(const BinOpInfo &Ops);
428   Value *EmitSub(const BinOpInfo &Ops);
429   Value *EmitShl(const BinOpInfo &Ops);
430   Value *EmitShr(const BinOpInfo &Ops);
431   Value *EmitAnd(const BinOpInfo &Ops) {
432     return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
433   }
434   Value *EmitXor(const BinOpInfo &Ops) {
435     return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
436   }
437   Value *EmitOr (const BinOpInfo &Ops) {
438     return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
439   }
440
441   BinOpInfo EmitBinOps(const BinaryOperator *E);
442   LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
443                             Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
444                                   Value *&Result);
445
446   Value *EmitCompoundAssign(const CompoundAssignOperator *E,
447                             Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
448
449   // Binary operators and binary compound assignment operators.
450 #define HANDLEBINOP(OP) \
451   Value *VisitBin ## OP(const BinaryOperator *E) {                         \
452     return Emit ## OP(EmitBinOps(E));                                      \
453   }                                                                        \
454   Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) {       \
455     return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP);          \
456   }
457   HANDLEBINOP(Mul)
458   HANDLEBINOP(Div)
459   HANDLEBINOP(Rem)
460   HANDLEBINOP(Add)
461   HANDLEBINOP(Sub)
462   HANDLEBINOP(Shl)
463   HANDLEBINOP(Shr)
464   HANDLEBINOP(And)
465   HANDLEBINOP(Xor)
466   HANDLEBINOP(Or)
467 #undef HANDLEBINOP
468
469   // Comparisons.
470   Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
471                      unsigned SICmpOpc, unsigned FCmpOpc);
472 #define VISITCOMP(CODE, UI, SI, FP) \
473     Value *VisitBin##CODE(const BinaryOperator *E) { \
474       return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
475                          llvm::FCmpInst::FP); }
476   VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT)
477   VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT)
478   VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE)
479   VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE)
480   VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ)
481   VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE)
482 #undef VISITCOMP
483
484   Value *VisitBinAssign     (const BinaryOperator *E);
485
486   Value *VisitBinLAnd       (const BinaryOperator *E);
487   Value *VisitBinLOr        (const BinaryOperator *E);
488   Value *VisitBinComma      (const BinaryOperator *E);
489
490   Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
491   Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
492
493   // Other Operators.
494   Value *VisitBlockExpr(const BlockExpr *BE);
495   Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
496   Value *VisitChooseExpr(ChooseExpr *CE);
497   Value *VisitVAArgExpr(VAArgExpr *VE);
498   Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
499     return CGF.EmitObjCStringLiteral(E);
500   }
501   Value *VisitObjCNumericLiteral(ObjCNumericLiteral *E) {
502     return CGF.EmitObjCNumericLiteral(E);
503   }
504   Value *VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
505     return CGF.EmitObjCArrayLiteral(E);
506   }
507   Value *VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
508     return CGF.EmitObjCDictionaryLiteral(E);
509   }
510   Value *VisitAsTypeExpr(AsTypeExpr *CE);
511   Value *VisitAtomicExpr(AtomicExpr *AE);
512 };
513 }  // end anonymous namespace.
514
515 //===----------------------------------------------------------------------===//
516 //                                Utilities
517 //===----------------------------------------------------------------------===//
518
519 /// EmitConversionToBool - Convert the specified expression value to a
520 /// boolean (i1) truth value.  This is equivalent to "Val != 0".
521 Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
522   assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
523
524   if (SrcType->isRealFloatingType())
525     return EmitFloatToBoolConversion(Src);
526
527   if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
528     return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
529
530   assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
531          "Unknown scalar type to convert");
532
533   if (isa<llvm::IntegerType>(Src->getType()))
534     return EmitIntToBoolConversion(Src);
535
536   assert(isa<llvm::PointerType>(Src->getType()));
537   return EmitPointerToBoolConversion(Src);
538 }
539
540 /// EmitScalarConversion - Emit a conversion from the specified type to the
541 /// specified destination type, both of which are LLVM scalar types.
542 Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
543                                                QualType DstType) {
544   SrcType = CGF.getContext().getCanonicalType(SrcType);
545   DstType = CGF.getContext().getCanonicalType(DstType);
546   if (SrcType == DstType) return Src;
547
548   if (DstType->isVoidType()) return 0;
549
550   llvm::Type *SrcTy = Src->getType();
551
552   // Floating casts might be a bit special: if we're doing casts to / from half
553   // FP, we should go via special intrinsics.
554   if (SrcType->isHalfType()) {
555     Src = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16), Src);
556     SrcType = CGF.getContext().FloatTy;
557     SrcTy = CGF.FloatTy;
558   }
559
560   // Handle conversions to bool first, they are special: comparisons against 0.
561   if (DstType->isBooleanType())
562     return EmitConversionToBool(Src, SrcType);
563
564   llvm::Type *DstTy = ConvertType(DstType);
565
566   // Ignore conversions like int -> uint.
567   if (SrcTy == DstTy)
568     return Src;
569
570   // Handle pointer conversions next: pointers can only be converted to/from
571   // other pointers and integers. Check for pointer types in terms of LLVM, as
572   // some native types (like Obj-C id) may map to a pointer type.
573   if (isa<llvm::PointerType>(DstTy)) {
574     // The source value may be an integer, or a pointer.
575     if (isa<llvm::PointerType>(SrcTy))
576       return Builder.CreateBitCast(Src, DstTy, "conv");
577
578     assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
579     // First, convert to the correct width so that we control the kind of
580     // extension.
581     llvm::Type *MiddleTy = CGF.IntPtrTy;
582     bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
583     llvm::Value* IntResult =
584         Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
585     // Then, cast to pointer.
586     return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
587   }
588
589   if (isa<llvm::PointerType>(SrcTy)) {
590     // Must be an ptr to int cast.
591     assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
592     return Builder.CreatePtrToInt(Src, DstTy, "conv");
593   }
594
595   // A scalar can be splatted to an extended vector of the same element type
596   if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
597     // Cast the scalar to element type
598     QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType();
599     llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
600
601     // Insert the element in element zero of an undef vector
602     llvm::Value *UnV = llvm::UndefValue::get(DstTy);
603     llvm::Value *Idx = Builder.getInt32(0);
604     UnV = Builder.CreateInsertElement(UnV, Elt, Idx);
605
606     // Splat the element across to all elements
607     unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
608     llvm::Constant *Mask = llvm::ConstantVector::getSplat(NumElements,
609                                                           Builder.getInt32(0));
610     llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
611     return Yay;
612   }
613
614   // Allow bitcast from vector to integer/fp of the same size.
615   if (isa<llvm::VectorType>(SrcTy) ||
616       isa<llvm::VectorType>(DstTy))
617     return Builder.CreateBitCast(Src, DstTy, "conv");
618
619   // Finally, we have the arithmetic types: real int/float.
620   Value *Res = NULL;
621   llvm::Type *ResTy = DstTy;
622
623   // Cast to half via float
624   if (DstType->isHalfType())
625     DstTy = CGF.FloatTy;
626
627   if (isa<llvm::IntegerType>(SrcTy)) {
628     bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
629     if (isa<llvm::IntegerType>(DstTy))
630       Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
631     else if (InputSigned)
632       Res = Builder.CreateSIToFP(Src, DstTy, "conv");
633     else
634       Res = Builder.CreateUIToFP(Src, DstTy, "conv");
635   } else if (isa<llvm::IntegerType>(DstTy)) {
636     assert(SrcTy->isFloatingPointTy() && "Unknown real conversion");
637     if (DstType->isSignedIntegerOrEnumerationType())
638       Res = Builder.CreateFPToSI(Src, DstTy, "conv");
639     else
640       Res = Builder.CreateFPToUI(Src, DstTy, "conv");
641   } else {
642     assert(SrcTy->isFloatingPointTy() && DstTy->isFloatingPointTy() &&
643            "Unknown real conversion");
644     if (DstTy->getTypeID() < SrcTy->getTypeID())
645       Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
646     else
647       Res = Builder.CreateFPExt(Src, DstTy, "conv");
648   }
649
650   if (DstTy != ResTy) {
651     assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion");
652     Res = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16), Res);
653   }
654
655   return Res;
656 }
657
658 /// EmitComplexToScalarConversion - Emit a conversion from the specified complex
659 /// type to the specified destination type, where the destination type is an
660 /// LLVM scalar type.
661 Value *ScalarExprEmitter::
662 EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
663                               QualType SrcTy, QualType DstTy) {
664   // Get the source element type.
665   SrcTy = SrcTy->getAs<ComplexType>()->getElementType();
666
667   // Handle conversions to bool first, they are special: comparisons against 0.
668   if (DstTy->isBooleanType()) {
669     //  Complex != 0  -> (Real != 0) | (Imag != 0)
670     Src.first  = EmitScalarConversion(Src.first, SrcTy, DstTy);
671     Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
672     return Builder.CreateOr(Src.first, Src.second, "tobool");
673   }
674
675   // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
676   // the imaginary part of the complex value is discarded and the value of the
677   // real part is converted according to the conversion rules for the
678   // corresponding real type.
679   return EmitScalarConversion(Src.first, SrcTy, DstTy);
680 }
681
682 Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
683   if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>())
684     return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
685
686   return llvm::Constant::getNullValue(ConvertType(Ty));
687 }
688
689 //===----------------------------------------------------------------------===//
690 //                            Visitor Methods
691 //===----------------------------------------------------------------------===//
692
693 Value *ScalarExprEmitter::VisitExpr(Expr *E) {
694   CGF.ErrorUnsupported(E, "scalar expression");
695   if (E->getType()->isVoidType())
696     return 0;
697   return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
698 }
699
700 Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
701   // Vector Mask Case
702   if (E->getNumSubExprs() == 2 || 
703       (E->getNumSubExprs() == 3 && E->getExpr(2)->getType()->isVectorType())) {
704     Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
705     Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
706     Value *Mask;
707     
708     llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
709     unsigned LHSElts = LTy->getNumElements();
710
711     if (E->getNumSubExprs() == 3) {
712       Mask = CGF.EmitScalarExpr(E->getExpr(2));
713       
714       // Shuffle LHS & RHS into one input vector.
715       SmallVector<llvm::Constant*, 32> concat;
716       for (unsigned i = 0; i != LHSElts; ++i) {
717         concat.push_back(Builder.getInt32(2*i));
718         concat.push_back(Builder.getInt32(2*i+1));
719       }
720       
721       Value* CV = llvm::ConstantVector::get(concat);
722       LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat");
723       LHSElts *= 2;
724     } else {
725       Mask = RHS;
726     }
727     
728     llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
729     llvm::Constant* EltMask;
730     
731     // Treat vec3 like vec4.
732     if ((LHSElts == 6) && (E->getNumSubExprs() == 3))
733       EltMask = llvm::ConstantInt::get(MTy->getElementType(),
734                                        (1 << llvm::Log2_32(LHSElts+2))-1);
735     else if ((LHSElts == 3) && (E->getNumSubExprs() == 2))
736       EltMask = llvm::ConstantInt::get(MTy->getElementType(),
737                                        (1 << llvm::Log2_32(LHSElts+1))-1);
738     else
739       EltMask = llvm::ConstantInt::get(MTy->getElementType(),
740                                        (1 << llvm::Log2_32(LHSElts))-1);
741              
742     // Mask off the high bits of each shuffle index.
743     Value *MaskBits = llvm::ConstantVector::getSplat(MTy->getNumElements(),
744                                                      EltMask);
745     Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
746     
747     // newv = undef
748     // mask = mask & maskbits
749     // for each elt
750     //   n = extract mask i
751     //   x = extract val n
752     //   newv = insert newv, x, i
753     llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
754                                                         MTy->getNumElements());
755     Value* NewV = llvm::UndefValue::get(RTy);
756     for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
757       Value *IIndx = Builder.getInt32(i);
758       Value *Indx = Builder.CreateExtractElement(Mask, IIndx, "shuf_idx");
759       Indx = Builder.CreateZExt(Indx, CGF.Int32Ty, "idx_zext");
760       
761       // Handle vec3 special since the index will be off by one for the RHS.
762       if ((LHSElts == 6) && (E->getNumSubExprs() == 3)) {
763         Value *cmpIndx, *newIndx;
764         cmpIndx = Builder.CreateICmpUGT(Indx, Builder.getInt32(3),
765                                         "cmp_shuf_idx");
766         newIndx = Builder.CreateSub(Indx, Builder.getInt32(1), "shuf_idx_adj");
767         Indx = Builder.CreateSelect(cmpIndx, newIndx, Indx, "sel_shuf_idx");
768       }
769       Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
770       NewV = Builder.CreateInsertElement(NewV, VExt, IIndx, "shuf_ins");
771     }
772     return NewV;
773   }
774   
775   Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
776   Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
777   
778   // Handle vec3 special since the index will be off by one for the RHS.
779   llvm::VectorType *VTy = cast<llvm::VectorType>(V1->getType());
780   SmallVector<llvm::Constant*, 32> indices;
781   for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
782     unsigned Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2);
783     if (VTy->getNumElements() == 3 && Idx > 3)
784       Idx -= 1;
785     indices.push_back(Builder.getInt32(Idx));
786   }
787
788   Value *SV = llvm::ConstantVector::get(indices);
789   return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
790 }
791 Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
792   llvm::APSInt Value;
793   if (E->EvaluateAsInt(Value, CGF.getContext(), Expr::SE_AllowSideEffects)) {
794     if (E->isArrow())
795       CGF.EmitScalarExpr(E->getBase());
796     else
797       EmitLValue(E->getBase());
798     return Builder.getInt(Value);
799   }
800
801   // Emit debug info for aggregate now, if it was delayed to reduce 
802   // debug info size.
803   CGDebugInfo *DI = CGF.getDebugInfo();
804   if (DI && CGF.CGM.getCodeGenOpts().LimitDebugInfo) {
805     QualType PQTy = E->getBase()->IgnoreParenImpCasts()->getType();
806     if (const PointerType * PTy = dyn_cast<PointerType>(PQTy))
807       if (FieldDecl *M = dyn_cast<FieldDecl>(E->getMemberDecl()))
808         DI->getOrCreateRecordType(PTy->getPointeeType(), 
809                                   M->getParent()->getLocation());
810   }
811   return EmitLoadOfLValue(E);
812 }
813
814 Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
815   TestAndClearIgnoreResultAssign();
816
817   // Emit subscript expressions in rvalue context's.  For most cases, this just
818   // loads the lvalue formed by the subscript expr.  However, we have to be
819   // careful, because the base of a vector subscript is occasionally an rvalue,
820   // so we can't get it as an lvalue.
821   if (!E->getBase()->getType()->isVectorType())
822     return EmitLoadOfLValue(E);
823
824   // Handle the vector case.  The base must be a vector, the index must be an
825   // integer value.
826   Value *Base = Visit(E->getBase());
827   Value *Idx  = Visit(E->getIdx());
828   bool IdxSigned = E->getIdx()->getType()->isSignedIntegerOrEnumerationType();
829   Idx = Builder.CreateIntCast(Idx, CGF.Int32Ty, IdxSigned, "vecidxcast");
830   return Builder.CreateExtractElement(Base, Idx, "vecext");
831 }
832
833 static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
834                                   unsigned Off, llvm::Type *I32Ty) {
835   int MV = SVI->getMaskValue(Idx);
836   if (MV == -1) 
837     return llvm::UndefValue::get(I32Ty);
838   return llvm::ConstantInt::get(I32Ty, Off+MV);
839 }
840
841 Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
842   bool Ignore = TestAndClearIgnoreResultAssign();
843   (void)Ignore;
844   assert (Ignore == false && "init list ignored");
845   unsigned NumInitElements = E->getNumInits();
846   
847   if (E->hadArrayRangeDesignator())
848     CGF.ErrorUnsupported(E, "GNU array range designator extension");
849   
850   llvm::VectorType *VType =
851     dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
852   
853   if (!VType) {
854     if (NumInitElements == 0) {
855       // C++11 value-initialization for the scalar.
856       return EmitNullValue(E->getType());
857     }
858     // We have a scalar in braces. Just use the first element.
859     return Visit(E->getInit(0));
860   }
861   
862   unsigned ResElts = VType->getNumElements();
863   
864   // Loop over initializers collecting the Value for each, and remembering 
865   // whether the source was swizzle (ExtVectorElementExpr).  This will allow
866   // us to fold the shuffle for the swizzle into the shuffle for the vector
867   // initializer, since LLVM optimizers generally do not want to touch
868   // shuffles.
869   unsigned CurIdx = 0;
870   bool VIsUndefShuffle = false;
871   llvm::Value *V = llvm::UndefValue::get(VType);
872   for (unsigned i = 0; i != NumInitElements; ++i) {
873     Expr *IE = E->getInit(i);
874     Value *Init = Visit(IE);
875     SmallVector<llvm::Constant*, 16> Args;
876     
877     llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
878     
879     // Handle scalar elements.  If the scalar initializer is actually one
880     // element of a different vector of the same width, use shuffle instead of 
881     // extract+insert.
882     if (!VVT) {
883       if (isa<ExtVectorElementExpr>(IE)) {
884         llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
885
886         if (EI->getVectorOperandType()->getNumElements() == ResElts) {
887           llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
888           Value *LHS = 0, *RHS = 0;
889           if (CurIdx == 0) {
890             // insert into undef -> shuffle (src, undef)
891             Args.push_back(C);
892             Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
893
894             LHS = EI->getVectorOperand();
895             RHS = V;
896             VIsUndefShuffle = true;
897           } else if (VIsUndefShuffle) {
898             // insert into undefshuffle && size match -> shuffle (v, src)
899             llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
900             for (unsigned j = 0; j != CurIdx; ++j)
901               Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
902             Args.push_back(Builder.getInt32(ResElts + C->getZExtValue()));
903             Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
904
905             LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
906             RHS = EI->getVectorOperand();
907             VIsUndefShuffle = false;
908           }
909           if (!Args.empty()) {
910             llvm::Constant *Mask = llvm::ConstantVector::get(Args);
911             V = Builder.CreateShuffleVector(LHS, RHS, Mask);
912             ++CurIdx;
913             continue;
914           }
915         }
916       }
917       V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx),
918                                       "vecinit");
919       VIsUndefShuffle = false;
920       ++CurIdx;
921       continue;
922     }
923     
924     unsigned InitElts = VVT->getNumElements();
925
926     // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's 
927     // input is the same width as the vector being constructed, generate an
928     // optimized shuffle of the swizzle input into the result.
929     unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
930     if (isa<ExtVectorElementExpr>(IE)) {
931       llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
932       Value *SVOp = SVI->getOperand(0);
933       llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
934       
935       if (OpTy->getNumElements() == ResElts) {
936         for (unsigned j = 0; j != CurIdx; ++j) {
937           // If the current vector initializer is a shuffle with undef, merge
938           // this shuffle directly into it.
939           if (VIsUndefShuffle) {
940             Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
941                                       CGF.Int32Ty));
942           } else {
943             Args.push_back(Builder.getInt32(j));
944           }
945         }
946         for (unsigned j = 0, je = InitElts; j != je; ++j)
947           Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
948         Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
949
950         if (VIsUndefShuffle)
951           V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
952
953         Init = SVOp;
954       }
955     }
956
957     // Extend init to result vector length, and then shuffle its contribution
958     // to the vector initializer into V.
959     if (Args.empty()) {
960       for (unsigned j = 0; j != InitElts; ++j)
961         Args.push_back(Builder.getInt32(j));
962       Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
963       llvm::Constant *Mask = llvm::ConstantVector::get(Args);
964       Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
965                                          Mask, "vext");
966
967       Args.clear();
968       for (unsigned j = 0; j != CurIdx; ++j)
969         Args.push_back(Builder.getInt32(j));
970       for (unsigned j = 0; j != InitElts; ++j)
971         Args.push_back(Builder.getInt32(j+Offset));
972       Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
973     }
974
975     // If V is undef, make sure it ends up on the RHS of the shuffle to aid
976     // merging subsequent shuffles into this one.
977     if (CurIdx == 0)
978       std::swap(V, Init);
979     llvm::Constant *Mask = llvm::ConstantVector::get(Args);
980     V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
981     VIsUndefShuffle = isa<llvm::UndefValue>(Init);
982     CurIdx += InitElts;
983   }
984   
985   // FIXME: evaluate codegen vs. shuffling against constant null vector.
986   // Emit remaining default initializers.
987   llvm::Type *EltTy = VType->getElementType();
988   
989   // Emit remaining default initializers
990   for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
991     Value *Idx = Builder.getInt32(CurIdx);
992     llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
993     V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
994   }
995   return V;
996 }
997
998 static bool ShouldNullCheckClassCastValue(const CastExpr *CE) {
999   const Expr *E = CE->getSubExpr();
1000
1001   if (CE->getCastKind() == CK_UncheckedDerivedToBase)
1002     return false;
1003   
1004   if (isa<CXXThisExpr>(E)) {
1005     // We always assume that 'this' is never null.
1006     return false;
1007   }
1008   
1009   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
1010     // And that glvalue casts are never null.
1011     if (ICE->getValueKind() != VK_RValue)
1012       return false;
1013   }
1014
1015   return true;
1016 }
1017
1018 // VisitCastExpr - Emit code for an explicit or implicit cast.  Implicit casts
1019 // have to handle a more broad range of conversions than explicit casts, as they
1020 // handle things like function to ptr-to-function decay etc.
1021 Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
1022   Expr *E = CE->getSubExpr();
1023   QualType DestTy = CE->getType();
1024   CastKind Kind = CE->getCastKind();
1025   
1026   if (!DestTy->isVoidType())
1027     TestAndClearIgnoreResultAssign();
1028
1029   // Since almost all cast kinds apply to scalars, this switch doesn't have
1030   // a default case, so the compiler will warn on a missing case.  The cases
1031   // are in the same order as in the CastKind enum.
1032   switch (Kind) {
1033   case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
1034       
1035   case CK_LValueBitCast: 
1036   case CK_ObjCObjectLValueCast: {
1037     Value *V = EmitLValue(E).getAddress();
1038     V = Builder.CreateBitCast(V, 
1039                           ConvertType(CGF.getContext().getPointerType(DestTy)));
1040     return EmitLoadOfLValue(CGF.MakeNaturalAlignAddrLValue(V, DestTy));
1041   }
1042
1043   case CK_CPointerToObjCPointerCast:
1044   case CK_BlockPointerToObjCPointerCast:
1045   case CK_AnyPointerToBlockPointerCast:
1046   case CK_BitCast: {
1047     Value *Src = Visit(const_cast<Expr*>(E));
1048     return Builder.CreateBitCast(Src, ConvertType(DestTy));
1049   }
1050   case CK_AtomicToNonAtomic:
1051   case CK_NonAtomicToAtomic:
1052   case CK_NoOp:
1053   case CK_UserDefinedConversion:
1054     return Visit(const_cast<Expr*>(E));
1055
1056   case CK_BaseToDerived: {
1057     const CXXRecordDecl *DerivedClassDecl = 
1058       DestTy->getCXXRecordDeclForPointerType();
1059     
1060     return CGF.GetAddressOfDerivedClass(Visit(E), DerivedClassDecl, 
1061                                         CE->path_begin(), CE->path_end(),
1062                                         ShouldNullCheckClassCastValue(CE));
1063   }
1064   case CK_UncheckedDerivedToBase:
1065   case CK_DerivedToBase: {
1066     const RecordType *DerivedClassTy = 
1067       E->getType()->getAs<PointerType>()->getPointeeType()->getAs<RecordType>();
1068     CXXRecordDecl *DerivedClassDecl = 
1069       cast<CXXRecordDecl>(DerivedClassTy->getDecl());
1070
1071     return CGF.GetAddressOfBaseClass(Visit(E), DerivedClassDecl, 
1072                                      CE->path_begin(), CE->path_end(),
1073                                      ShouldNullCheckClassCastValue(CE));
1074   }
1075   case CK_Dynamic: {
1076     Value *V = Visit(const_cast<Expr*>(E));
1077     const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
1078     return CGF.EmitDynamicCast(V, DCE);
1079   }
1080
1081   case CK_ArrayToPointerDecay: {
1082     assert(E->getType()->isArrayType() &&
1083            "Array to pointer decay must have array source type!");
1084
1085     Value *V = EmitLValue(E).getAddress();  // Bitfields can't be arrays.
1086
1087     // Note that VLA pointers are always decayed, so we don't need to do
1088     // anything here.
1089     if (!E->getType()->isVariableArrayType()) {
1090       assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
1091       assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
1092                                  ->getElementType()) &&
1093              "Expected pointer to array");
1094       V = Builder.CreateStructGEP(V, 0, "arraydecay");
1095     }
1096
1097     // Make sure the array decay ends up being the right type.  This matters if
1098     // the array type was of an incomplete type.
1099     return CGF.Builder.CreateBitCast(V, ConvertType(CE->getType()));
1100   }
1101   case CK_FunctionToPointerDecay:
1102     return EmitLValue(E).getAddress();
1103
1104   case CK_NullToPointer:
1105     if (MustVisitNullValue(E))
1106       (void) Visit(E);
1107
1108     return llvm::ConstantPointerNull::get(
1109                                cast<llvm::PointerType>(ConvertType(DestTy)));
1110
1111   case CK_NullToMemberPointer: {
1112     if (MustVisitNullValue(E))
1113       (void) Visit(E);
1114
1115     const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
1116     return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
1117   }
1118
1119   case CK_ReinterpretMemberPointer:
1120   case CK_BaseToDerivedMemberPointer:
1121   case CK_DerivedToBaseMemberPointer: {
1122     Value *Src = Visit(E);
1123     
1124     // Note that the AST doesn't distinguish between checked and
1125     // unchecked member pointer conversions, so we always have to
1126     // implement checked conversions here.  This is inefficient when
1127     // actual control flow may be required in order to perform the
1128     // check, which it is for data member pointers (but not member
1129     // function pointers on Itanium and ARM).
1130     return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
1131   }
1132
1133   case CK_ARCProduceObject:
1134     return CGF.EmitARCRetainScalarExpr(E);
1135   case CK_ARCConsumeObject:
1136     return CGF.EmitObjCConsumeObject(E->getType(), Visit(E));
1137   case CK_ARCReclaimReturnedObject: {
1138     llvm::Value *value = Visit(E);
1139     value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
1140     return CGF.EmitObjCConsumeObject(E->getType(), value);
1141   }
1142   case CK_ARCExtendBlockObject:
1143     return CGF.EmitARCExtendBlockObject(E);
1144
1145   case CK_CopyAndAutoreleaseBlockObject:
1146     return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType());
1147       
1148   case CK_FloatingRealToComplex:
1149   case CK_FloatingComplexCast:
1150   case CK_IntegralRealToComplex:
1151   case CK_IntegralComplexCast:
1152   case CK_IntegralComplexToFloatingComplex:
1153   case CK_FloatingComplexToIntegralComplex:
1154   case CK_ConstructorConversion:
1155   case CK_ToUnion:
1156     llvm_unreachable("scalar cast to non-scalar value");
1157
1158   case CK_LValueToRValue:
1159     assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
1160     assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
1161     return Visit(const_cast<Expr*>(E));
1162
1163   case CK_IntegralToPointer: {
1164     Value *Src = Visit(const_cast<Expr*>(E));
1165
1166     // First, convert to the correct width so that we control the kind of
1167     // extension.
1168     llvm::Type *MiddleTy = CGF.IntPtrTy;
1169     bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
1170     llvm::Value* IntResult =
1171       Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
1172
1173     return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy));
1174   }
1175   case CK_PointerToIntegral:
1176     assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
1177     return Builder.CreatePtrToInt(Visit(E), ConvertType(DestTy));
1178
1179   case CK_ToVoid: {
1180     CGF.EmitIgnoredExpr(E);
1181     return 0;
1182   }
1183   case CK_VectorSplat: {
1184     llvm::Type *DstTy = ConvertType(DestTy);
1185     Value *Elt = Visit(const_cast<Expr*>(E));
1186     Elt = EmitScalarConversion(Elt, E->getType(),
1187                                DestTy->getAs<VectorType>()->getElementType());
1188
1189     // Insert the element in element zero of an undef vector
1190     llvm::Value *UnV = llvm::UndefValue::get(DstTy);
1191     llvm::Value *Idx = Builder.getInt32(0);
1192     UnV = Builder.CreateInsertElement(UnV, Elt, Idx);
1193
1194     // Splat the element across to all elements
1195     unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
1196     llvm::Constant *Zero = Builder.getInt32(0);
1197     llvm::Constant *Mask = llvm::ConstantVector::getSplat(NumElements, Zero);
1198     llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
1199     return Yay;
1200   }
1201
1202   case CK_IntegralCast:
1203   case CK_IntegralToFloating:
1204   case CK_FloatingToIntegral:
1205   case CK_FloatingCast:
1206     return EmitScalarConversion(Visit(E), E->getType(), DestTy);
1207   case CK_IntegralToBoolean:
1208     return EmitIntToBoolConversion(Visit(E));
1209   case CK_PointerToBoolean:
1210     return EmitPointerToBoolConversion(Visit(E));
1211   case CK_FloatingToBoolean:
1212     return EmitFloatToBoolConversion(Visit(E));
1213   case CK_MemberPointerToBoolean: {
1214     llvm::Value *MemPtr = Visit(E);
1215     const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
1216     return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
1217   }
1218
1219   case CK_FloatingComplexToReal:
1220   case CK_IntegralComplexToReal:
1221     return CGF.EmitComplexExpr(E, false, true).first;
1222
1223   case CK_FloatingComplexToBoolean:
1224   case CK_IntegralComplexToBoolean: {
1225     CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
1226
1227     // TODO: kill this function off, inline appropriate case here
1228     return EmitComplexToScalarConversion(V, E->getType(), DestTy);
1229   }
1230
1231   }
1232
1233   llvm_unreachable("unknown scalar cast");
1234 }
1235
1236 Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
1237   CodeGenFunction::StmtExprEvaluation eval(CGF);
1238   return CGF.EmitCompoundStmt(*E->getSubStmt(), !E->getType()->isVoidType())
1239     .getScalarVal();
1240 }
1241
1242 //===----------------------------------------------------------------------===//
1243 //                             Unary Operators
1244 //===----------------------------------------------------------------------===//
1245
1246 llvm::Value *ScalarExprEmitter::
1247 EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
1248                                 llvm::Value *InVal,
1249                                 llvm::Value *NextVal, bool IsInc) {
1250   switch (CGF.getContext().getLangOpts().getSignedOverflowBehavior()) {
1251   case LangOptions::SOB_Undefined:
1252     return Builder.CreateNSWAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1253   case LangOptions::SOB_Defined:
1254     return Builder.CreateAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1255   case LangOptions::SOB_Trapping:
1256     BinOpInfo BinOp;
1257     BinOp.LHS = InVal;
1258     BinOp.RHS = NextVal;
1259     BinOp.Ty = E->getType();
1260     BinOp.Opcode = BO_Add;
1261     BinOp.E = E;
1262     return EmitOverflowCheckedBinOp(BinOp);
1263   }
1264   llvm_unreachable("Unknown SignedOverflowBehaviorTy");
1265 }
1266
1267 llvm::Value *
1268 ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1269                                            bool isInc, bool isPre) {
1270   
1271   QualType type = E->getSubExpr()->getType();
1272   llvm::Value *value = EmitLoadOfLValue(LV);
1273   llvm::Value *input = value;
1274   llvm::PHINode *atomicPHI = 0;
1275
1276   int amount = (isInc ? 1 : -1);
1277
1278   if (const AtomicType *atomicTy = type->getAs<AtomicType>()) {
1279     llvm::BasicBlock *startBB = Builder.GetInsertBlock();
1280     llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
1281     Builder.CreateBr(opBB);
1282     Builder.SetInsertPoint(opBB);
1283     atomicPHI = Builder.CreatePHI(value->getType(), 2);
1284     atomicPHI->addIncoming(value, startBB);
1285     type = atomicTy->getValueType();
1286     value = atomicPHI;
1287   }
1288
1289   // Special case of integer increment that we have to check first: bool++.
1290   // Due to promotion rules, we get:
1291   //   bool++ -> bool = bool + 1
1292   //          -> bool = (int)bool + 1
1293   //          -> bool = ((int)bool + 1 != 0)
1294   // An interesting aspect of this is that increment is always true.
1295   // Decrement does not have this property.
1296   if (isInc && type->isBooleanType()) {
1297     value = Builder.getTrue();
1298
1299   // Most common case by far: integer increment.
1300   } else if (type->isIntegerType()) {
1301
1302     llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1303
1304     // Note that signed integer inc/dec with width less than int can't
1305     // overflow because of promotion rules; we're just eliding a few steps here.
1306     if (type->isSignedIntegerOrEnumerationType() &&
1307         value->getType()->getPrimitiveSizeInBits() >=
1308             CGF.IntTy->getBitWidth())
1309       value = EmitAddConsiderOverflowBehavior(E, value, amt, isInc);
1310     else
1311       value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1312   
1313   // Next most common: pointer increment.
1314   } else if (const PointerType *ptr = type->getAs<PointerType>()) {
1315     QualType type = ptr->getPointeeType();
1316
1317     // VLA types don't have constant size.
1318     if (const VariableArrayType *vla
1319           = CGF.getContext().getAsVariableArrayType(type)) {
1320       llvm::Value *numElts = CGF.getVLASize(vla).first;
1321       if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize");
1322       if (CGF.getContext().getLangOpts().isSignedOverflowDefined())
1323         value = Builder.CreateGEP(value, numElts, "vla.inc");
1324       else
1325         value = Builder.CreateInBoundsGEP(value, numElts, "vla.inc");
1326     
1327     // Arithmetic on function pointers (!) is just +-1.
1328     } else if (type->isFunctionType()) {
1329       llvm::Value *amt = Builder.getInt32(amount);
1330
1331       value = CGF.EmitCastToVoidPtr(value);
1332       if (CGF.getContext().getLangOpts().isSignedOverflowDefined())
1333         value = Builder.CreateGEP(value, amt, "incdec.funcptr");
1334       else
1335         value = Builder.CreateInBoundsGEP(value, amt, "incdec.funcptr");
1336       value = Builder.CreateBitCast(value, input->getType());
1337
1338     // For everything else, we can just do a simple increment.
1339     } else {
1340       llvm::Value *amt = Builder.getInt32(amount);
1341       if (CGF.getContext().getLangOpts().isSignedOverflowDefined())
1342         value = Builder.CreateGEP(value, amt, "incdec.ptr");
1343       else
1344         value = Builder.CreateInBoundsGEP(value, amt, "incdec.ptr");
1345     }
1346
1347   // Vector increment/decrement.
1348   } else if (type->isVectorType()) {
1349     if (type->hasIntegerRepresentation()) {
1350       llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1351
1352       value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1353     } else {
1354       value = Builder.CreateFAdd(
1355                   value,
1356                   llvm::ConstantFP::get(value->getType(), amount),
1357                   isInc ? "inc" : "dec");
1358     }
1359
1360   // Floating point.
1361   } else if (type->isRealFloatingType()) {
1362     // Add the inc/dec to the real part.
1363     llvm::Value *amt;
1364
1365     if (type->isHalfType()) {
1366       // Another special case: half FP increment should be done via float
1367       value =
1368     Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16),
1369                        input);
1370     }
1371
1372     if (value->getType()->isFloatTy())
1373       amt = llvm::ConstantFP::get(VMContext,
1374                                   llvm::APFloat(static_cast<float>(amount)));
1375     else if (value->getType()->isDoubleTy())
1376       amt = llvm::ConstantFP::get(VMContext,
1377                                   llvm::APFloat(static_cast<double>(amount)));
1378     else {
1379       llvm::APFloat F(static_cast<float>(amount));
1380       bool ignored;
1381       F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
1382                 &ignored);
1383       amt = llvm::ConstantFP::get(VMContext, F);
1384     }
1385     value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
1386
1387     if (type->isHalfType())
1388       value =
1389        Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16),
1390                           value);
1391
1392   // Objective-C pointer types.
1393   } else {
1394     const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
1395     value = CGF.EmitCastToVoidPtr(value);
1396
1397     CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
1398     if (!isInc) size = -size;
1399     llvm::Value *sizeValue =
1400       llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
1401
1402     if (CGF.getContext().getLangOpts().isSignedOverflowDefined())
1403       value = Builder.CreateGEP(value, sizeValue, "incdec.objptr");
1404     else
1405       value = Builder.CreateInBoundsGEP(value, sizeValue, "incdec.objptr");
1406     value = Builder.CreateBitCast(value, input->getType());
1407   }
1408   
1409   if (atomicPHI) {
1410     llvm::BasicBlock *opBB = Builder.GetInsertBlock();
1411     llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
1412     llvm::Value *old = Builder.CreateAtomicCmpXchg(LV.getAddress(), atomicPHI,
1413         value, llvm::SequentiallyConsistent);
1414     atomicPHI->addIncoming(old, opBB);
1415     llvm::Value *success = Builder.CreateICmpEQ(old, atomicPHI);
1416     Builder.CreateCondBr(success, contBB, opBB);
1417     Builder.SetInsertPoint(contBB);
1418     return isPre ? value : input;
1419   }
1420
1421   // Store the updated result through the lvalue.
1422   if (LV.isBitField())
1423     CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
1424   else
1425     CGF.EmitStoreThroughLValue(RValue::get(value), LV);
1426
1427   // If this is a postinc, return the value read from memory, otherwise use the
1428   // updated value.
1429   return isPre ? value : input;
1430 }
1431
1432
1433
1434 Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
1435   TestAndClearIgnoreResultAssign();
1436   // Emit unary minus with EmitSub so we handle overflow cases etc.
1437   BinOpInfo BinOp;
1438   BinOp.RHS = Visit(E->getSubExpr());
1439   
1440   if (BinOp.RHS->getType()->isFPOrFPVectorTy())
1441     BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
1442   else 
1443     BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
1444   BinOp.Ty = E->getType();
1445   BinOp.Opcode = BO_Sub;
1446   BinOp.E = E;
1447   return EmitSub(BinOp);
1448 }
1449
1450 Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
1451   TestAndClearIgnoreResultAssign();
1452   Value *Op = Visit(E->getSubExpr());
1453   return Builder.CreateNot(Op, "neg");
1454 }
1455
1456 Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
1457   
1458   // Perform vector logical not on comparison with zero vector.
1459   if (E->getType()->isExtVectorType()) {
1460     Value *Oper = Visit(E->getSubExpr());
1461     Value *Zero = llvm::Constant::getNullValue(Oper->getType());
1462     Value *Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp");
1463     return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
1464   }
1465   
1466   // Compare operand to zero.
1467   Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
1468
1469   // Invert value.
1470   // TODO: Could dynamically modify easy computations here.  For example, if
1471   // the operand is an icmp ne, turn into icmp eq.
1472   BoolVal = Builder.CreateNot(BoolVal, "lnot");
1473
1474   // ZExt result to the expr type.
1475   return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
1476 }
1477
1478 Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
1479   // Try folding the offsetof to a constant.
1480   llvm::APSInt Value;
1481   if (E->EvaluateAsInt(Value, CGF.getContext()))
1482     return Builder.getInt(Value);
1483
1484   // Loop over the components of the offsetof to compute the value.
1485   unsigned n = E->getNumComponents();
1486   llvm::Type* ResultType = ConvertType(E->getType());
1487   llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
1488   QualType CurrentType = E->getTypeSourceInfo()->getType();
1489   for (unsigned i = 0; i != n; ++i) {
1490     OffsetOfExpr::OffsetOfNode ON = E->getComponent(i);
1491     llvm::Value *Offset = 0;
1492     switch (ON.getKind()) {
1493     case OffsetOfExpr::OffsetOfNode::Array: {
1494       // Compute the index
1495       Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
1496       llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
1497       bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
1498       Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
1499
1500       // Save the element type
1501       CurrentType =
1502           CGF.getContext().getAsArrayType(CurrentType)->getElementType();
1503
1504       // Compute the element size
1505       llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
1506           CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
1507
1508       // Multiply out to compute the result
1509       Offset = Builder.CreateMul(Idx, ElemSize);
1510       break;
1511     }
1512
1513     case OffsetOfExpr::OffsetOfNode::Field: {
1514       FieldDecl *MemberDecl = ON.getField();
1515       RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1516       const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1517
1518       // Compute the index of the field in its parent.
1519       unsigned i = 0;
1520       // FIXME: It would be nice if we didn't have to loop here!
1521       for (RecordDecl::field_iterator Field = RD->field_begin(),
1522                                       FieldEnd = RD->field_end();
1523            Field != FieldEnd; (void)++Field, ++i) {
1524         if (*Field == MemberDecl)
1525           break;
1526       }
1527       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1528
1529       // Compute the offset to the field
1530       int64_t OffsetInt = RL.getFieldOffset(i) /
1531                           CGF.getContext().getCharWidth();
1532       Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1533
1534       // Save the element type.
1535       CurrentType = MemberDecl->getType();
1536       break;
1537     }
1538
1539     case OffsetOfExpr::OffsetOfNode::Identifier:
1540       llvm_unreachable("dependent __builtin_offsetof");
1541
1542     case OffsetOfExpr::OffsetOfNode::Base: {
1543       if (ON.getBase()->isVirtual()) {
1544         CGF.ErrorUnsupported(E, "virtual base in offsetof");
1545         continue;
1546       }
1547
1548       RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1549       const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1550
1551       // Save the element type.
1552       CurrentType = ON.getBase()->getType();
1553       
1554       // Compute the offset to the base.
1555       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1556       CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
1557       int64_t OffsetInt = RL.getBaseClassOffsetInBits(BaseRD) /
1558                           CGF.getContext().getCharWidth();
1559       Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1560       break;
1561     }
1562     }
1563     Result = Builder.CreateAdd(Result, Offset);
1564   }
1565   return Result;
1566 }
1567
1568 /// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
1569 /// argument of the sizeof expression as an integer.
1570 Value *
1571 ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
1572                               const UnaryExprOrTypeTraitExpr *E) {
1573   QualType TypeToSize = E->getTypeOfArgument();
1574   if (E->getKind() == UETT_SizeOf) {
1575     if (const VariableArrayType *VAT =
1576           CGF.getContext().getAsVariableArrayType(TypeToSize)) {
1577       if (E->isArgumentType()) {
1578         // sizeof(type) - make sure to emit the VLA size.
1579         CGF.EmitVariablyModifiedType(TypeToSize);
1580       } else {
1581         // C99 6.5.3.4p2: If the argument is an expression of type
1582         // VLA, it is evaluated.
1583         CGF.EmitIgnoredExpr(E->getArgumentExpr());
1584       }
1585
1586       QualType eltType;
1587       llvm::Value *numElts;
1588       llvm::tie(numElts, eltType) = CGF.getVLASize(VAT);
1589
1590       llvm::Value *size = numElts;
1591
1592       // Scale the number of non-VLA elements by the non-VLA element size.
1593       CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
1594       if (!eltSize.isOne())
1595         size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), numElts);
1596
1597       return size;
1598     }
1599   }
1600
1601   // If this isn't sizeof(vla), the result must be constant; use the constant
1602   // folding logic so we don't have to duplicate it here.
1603   return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext()));
1604 }
1605
1606 Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
1607   Expr *Op = E->getSubExpr();
1608   if (Op->getType()->isAnyComplexType()) {
1609     // If it's an l-value, load through the appropriate subobject l-value.
1610     // Note that we have to ask E because Op might be an l-value that
1611     // this won't work for, e.g. an Obj-C property.
1612     if (E->isGLValue())
1613       return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal();
1614
1615     // Otherwise, calculate and project.
1616     return CGF.EmitComplexExpr(Op, false, true).first;
1617   }
1618
1619   return Visit(Op);
1620 }
1621
1622 Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
1623   Expr *Op = E->getSubExpr();
1624   if (Op->getType()->isAnyComplexType()) {
1625     // If it's an l-value, load through the appropriate subobject l-value.
1626     // Note that we have to ask E because Op might be an l-value that
1627     // this won't work for, e.g. an Obj-C property.
1628     if (Op->isGLValue())
1629       return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal();
1630
1631     // Otherwise, calculate and project.
1632     return CGF.EmitComplexExpr(Op, true, false).second;
1633   }
1634
1635   // __imag on a scalar returns zero.  Emit the subexpr to ensure side
1636   // effects are evaluated, but not the actual value.
1637   if (Op->isGLValue())
1638     CGF.EmitLValue(Op);
1639   else
1640     CGF.EmitScalarExpr(Op, true);
1641   return llvm::Constant::getNullValue(ConvertType(E->getType()));
1642 }
1643
1644 //===----------------------------------------------------------------------===//
1645 //                           Binary Operators
1646 //===----------------------------------------------------------------------===//
1647
1648 BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
1649   TestAndClearIgnoreResultAssign();
1650   BinOpInfo Result;
1651   Result.LHS = Visit(E->getLHS());
1652   Result.RHS = Visit(E->getRHS());
1653   Result.Ty  = E->getType();
1654   Result.Opcode = E->getOpcode();
1655   Result.E = E;
1656   return Result;
1657 }
1658
1659 LValue ScalarExprEmitter::EmitCompoundAssignLValue(
1660                                               const CompoundAssignOperator *E,
1661                         Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
1662                                                    Value *&Result) {
1663   QualType LHSTy = E->getLHS()->getType();
1664   BinOpInfo OpInfo;
1665   
1666   if (E->getComputationResultType()->isAnyComplexType()) {
1667     // This needs to go through the complex expression emitter, but it's a tad
1668     // complicated to do that... I'm leaving it out for now.  (Note that we do
1669     // actually need the imaginary part of the RHS for multiplication and
1670     // division.)
1671     CGF.ErrorUnsupported(E, "complex compound assignment");
1672     Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
1673     return LValue();
1674   }
1675   
1676   // Emit the RHS first.  __block variables need to have the rhs evaluated
1677   // first, plus this should improve codegen a little.
1678   OpInfo.RHS = Visit(E->getRHS());
1679   OpInfo.Ty = E->getComputationResultType();
1680   OpInfo.Opcode = E->getOpcode();
1681   OpInfo.E = E;
1682   // Load/convert the LHS.
1683   LValue LHSLV = EmitCheckedLValue(E->getLHS());
1684   OpInfo.LHS = EmitLoadOfLValue(LHSLV);
1685   OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
1686                                     E->getComputationLHSType());
1687
1688   llvm::PHINode *atomicPHI = 0;
1689   if (const AtomicType *atomicTy = OpInfo.Ty->getAs<AtomicType>()) {
1690     // FIXME: For floating point types, we should be saving and restoring the
1691     // floating point environment in the loop.
1692     llvm::BasicBlock *startBB = Builder.GetInsertBlock();
1693     llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
1694     Builder.CreateBr(opBB);
1695     Builder.SetInsertPoint(opBB);
1696     atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2);
1697     atomicPHI->addIncoming(OpInfo.LHS, startBB);
1698     OpInfo.Ty = atomicTy->getValueType();
1699     OpInfo.LHS = atomicPHI;
1700   }
1701   
1702   // Expand the binary operator.
1703   Result = (this->*Func)(OpInfo);
1704   
1705   // Convert the result back to the LHS type.
1706   Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
1707
1708   if (atomicPHI) {
1709     llvm::BasicBlock *opBB = Builder.GetInsertBlock();
1710     llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
1711     llvm::Value *old = Builder.CreateAtomicCmpXchg(LHSLV.getAddress(), atomicPHI,
1712         Result, llvm::SequentiallyConsistent);
1713     atomicPHI->addIncoming(old, opBB);
1714     llvm::Value *success = Builder.CreateICmpEQ(old, atomicPHI);
1715     Builder.CreateCondBr(success, contBB, opBB);
1716     Builder.SetInsertPoint(contBB);
1717     return LHSLV;
1718   }
1719   
1720   // Store the result value into the LHS lvalue. Bit-fields are handled
1721   // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
1722   // 'An assignment expression has the value of the left operand after the
1723   // assignment...'.
1724   if (LHSLV.isBitField())
1725     CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
1726   else
1727     CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
1728
1729   return LHSLV;
1730 }
1731
1732 Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
1733                       Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
1734   bool Ignore = TestAndClearIgnoreResultAssign();
1735   Value *RHS;
1736   LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
1737
1738   // If the result is clearly ignored, return now.
1739   if (Ignore)
1740     return 0;
1741
1742   // The result of an assignment in C is the assigned r-value.
1743   if (!CGF.getContext().getLangOpts().CPlusPlus)
1744     return RHS;
1745
1746   // If the lvalue is non-volatile, return the computed value of the assignment.
1747   if (!LHS.isVolatileQualified())
1748     return RHS;
1749
1750   // Otherwise, reload the value.
1751   return EmitLoadOfLValue(LHS);
1752 }
1753
1754 void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
1755                                             const BinOpInfo &Ops, 
1756                                             llvm::Value *Zero, bool isDiv) {
1757   llvm::Function::iterator insertPt = Builder.GetInsertBlock();
1758   llvm::BasicBlock *contBB =
1759     CGF.createBasicBlock(isDiv ? "div.cont" : "rem.cont", CGF.CurFn,
1760                          llvm::next(insertPt));
1761   llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
1762
1763   llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
1764
1765   if (Ops.Ty->hasSignedIntegerRepresentation()) {
1766     llvm::Value *IntMin =
1767       Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
1768     llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
1769
1770     llvm::Value *Cond1 = Builder.CreateICmpEQ(Ops.RHS, Zero);
1771     llvm::Value *LHSCmp = Builder.CreateICmpEQ(Ops.LHS, IntMin);
1772     llvm::Value *RHSCmp = Builder.CreateICmpEQ(Ops.RHS, NegOne);
1773     llvm::Value *Cond2 = Builder.CreateAnd(LHSCmp, RHSCmp, "and");
1774     Builder.CreateCondBr(Builder.CreateOr(Cond1, Cond2, "or"), 
1775                          overflowBB, contBB);
1776   } else {
1777     CGF.Builder.CreateCondBr(Builder.CreateICmpEQ(Ops.RHS, Zero), 
1778                              overflowBB, contBB);
1779   }
1780   EmitOverflowBB(overflowBB);
1781   Builder.SetInsertPoint(contBB);
1782 }
1783
1784 Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
1785   if (isTrapvOverflowBehavior()) { 
1786     llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1787
1788     if (Ops.Ty->isIntegerType())
1789       EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
1790     else if (Ops.Ty->isRealFloatingType()) {
1791       llvm::Function::iterator insertPt = Builder.GetInsertBlock();
1792       llvm::BasicBlock *DivCont = CGF.createBasicBlock("div.cont", CGF.CurFn,
1793                                                        llvm::next(insertPt));
1794       llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow",
1795                                                           CGF.CurFn);
1796       CGF.Builder.CreateCondBr(Builder.CreateFCmpOEQ(Ops.RHS, Zero), 
1797                                overflowBB, DivCont);
1798       EmitOverflowBB(overflowBB);
1799       Builder.SetInsertPoint(DivCont);
1800     }
1801   }
1802   if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
1803     llvm::Value *Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
1804     if (CGF.getContext().getLangOpts().OpenCL) {
1805       // OpenCL 1.1 7.4: minimum accuracy of single precision / is 2.5ulp
1806       llvm::Type *ValTy = Val->getType();
1807       if (ValTy->isFloatTy() ||
1808           (isa<llvm::VectorType>(ValTy) &&
1809            cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy()))
1810         CGF.SetFPAccuracy(Val, 2.5);
1811     }
1812     return Val;
1813   }
1814   else if (Ops.Ty->hasUnsignedIntegerRepresentation())
1815     return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
1816   else
1817     return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
1818 }
1819
1820 Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
1821   // Rem in C can't be a floating point type: C99 6.5.5p2.
1822   if (isTrapvOverflowBehavior()) {
1823     llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1824
1825     if (Ops.Ty->isIntegerType()) 
1826       EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
1827   }
1828
1829   if (Ops.Ty->hasUnsignedIntegerRepresentation())
1830     return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
1831   else
1832     return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
1833 }
1834
1835 Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
1836   unsigned IID;
1837   unsigned OpID = 0;
1838
1839   switch (Ops.Opcode) {
1840   case BO_Add:
1841   case BO_AddAssign:
1842     OpID = 1;
1843     IID = llvm::Intrinsic::sadd_with_overflow;
1844     break;
1845   case BO_Sub:
1846   case BO_SubAssign:
1847     OpID = 2;
1848     IID = llvm::Intrinsic::ssub_with_overflow;
1849     break;
1850   case BO_Mul:
1851   case BO_MulAssign:
1852     OpID = 3;
1853     IID = llvm::Intrinsic::smul_with_overflow;
1854     break;
1855   default:
1856     llvm_unreachable("Unsupported operation for overflow detection");
1857   }
1858   OpID <<= 1;
1859   OpID |= 1;
1860
1861   llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
1862
1863   llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
1864
1865   Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
1866   Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
1867   Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
1868
1869   // Branch in case of overflow.
1870   llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
1871   llvm::Function::iterator insertPt = initialBB;
1872   llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn,
1873                                                       llvm::next(insertPt));
1874   llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
1875
1876   Builder.CreateCondBr(overflow, overflowBB, continueBB);
1877
1878   // Handle overflow with llvm.trap.
1879   const std::string *handlerName = 
1880     &CGF.getContext().getLangOpts().OverflowHandler;
1881   if (handlerName->empty()) {
1882     EmitOverflowBB(overflowBB);
1883     Builder.SetInsertPoint(continueBB);
1884     return result;
1885   }
1886
1887   // If an overflow handler is set, then we want to call it and then use its
1888   // result, if it returns.
1889   Builder.SetInsertPoint(overflowBB);
1890
1891   // Get the overflow handler.
1892   llvm::Type *Int8Ty = CGF.Int8Ty;
1893   llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
1894   llvm::FunctionType *handlerTy =
1895       llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
1896   llvm::Value *handler = CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
1897
1898   // Sign extend the args to 64-bit, so that we can use the same handler for
1899   // all types of overflow.
1900   llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
1901   llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
1902
1903   // Call the handler with the two arguments, the operation, and the size of
1904   // the result.
1905   llvm::Value *handlerResult = Builder.CreateCall4(handler, lhs, rhs,
1906       Builder.getInt8(OpID),
1907       Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth()));
1908
1909   // Truncate the result back to the desired size.
1910   handlerResult = Builder.CreateTrunc(handlerResult, opTy);
1911   Builder.CreateBr(continueBB);
1912
1913   Builder.SetInsertPoint(continueBB);
1914   llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
1915   phi->addIncoming(result, initialBB);
1916   phi->addIncoming(handlerResult, overflowBB);
1917
1918   return phi;
1919 }
1920
1921 /// Emit pointer + index arithmetic.
1922 static Value *emitPointerArithmetic(CodeGenFunction &CGF,
1923                                     const BinOpInfo &op,
1924                                     bool isSubtraction) {
1925   // Must have binary (not unary) expr here.  Unary pointer
1926   // increment/decrement doesn't use this path.
1927   const BinaryOperator *expr = cast<BinaryOperator>(op.E);
1928   
1929   Value *pointer = op.LHS;
1930   Expr *pointerOperand = expr->getLHS();
1931   Value *index = op.RHS;
1932   Expr *indexOperand = expr->getRHS();
1933
1934   // In a subtraction, the LHS is always the pointer.
1935   if (!isSubtraction && !pointer->getType()->isPointerTy()) {
1936     std::swap(pointer, index);
1937     std::swap(pointerOperand, indexOperand);
1938   }
1939
1940   unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
1941   if (width != CGF.PointerWidthInBits) {
1942     // Zero-extend or sign-extend the pointer value according to
1943     // whether the index is signed or not.
1944     bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
1945     index = CGF.Builder.CreateIntCast(index, CGF.PtrDiffTy, isSigned,
1946                                       "idx.ext");
1947   }
1948
1949   // If this is subtraction, negate the index.
1950   if (isSubtraction)
1951     index = CGF.Builder.CreateNeg(index, "idx.neg");
1952
1953   const PointerType *pointerType
1954     = pointerOperand->getType()->getAs<PointerType>();
1955   if (!pointerType) {
1956     QualType objectType = pointerOperand->getType()
1957                                         ->castAs<ObjCObjectPointerType>()
1958                                         ->getPointeeType();
1959     llvm::Value *objectSize
1960       = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
1961
1962     index = CGF.Builder.CreateMul(index, objectSize);
1963
1964     Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
1965     result = CGF.Builder.CreateGEP(result, index, "add.ptr");
1966     return CGF.Builder.CreateBitCast(result, pointer->getType());
1967   }
1968
1969   QualType elementType = pointerType->getPointeeType();
1970   if (const VariableArrayType *vla
1971         = CGF.getContext().getAsVariableArrayType(elementType)) {
1972     // The element count here is the total number of non-VLA elements.
1973     llvm::Value *numElements = CGF.getVLASize(vla).first;
1974
1975     // Effectively, the multiply by the VLA size is part of the GEP.
1976     // GEP indexes are signed, and scaling an index isn't permitted to
1977     // signed-overflow, so we use the same semantics for our explicit
1978     // multiply.  We suppress this if overflow is not undefined behavior.
1979     if (CGF.getLangOpts().isSignedOverflowDefined()) {
1980       index = CGF.Builder.CreateMul(index, numElements, "vla.index");
1981       pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr");
1982     } else {
1983       index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
1984       pointer = CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
1985     }
1986     return pointer;
1987   }
1988
1989   // Explicitly handle GNU void* and function pointer arithmetic extensions. The
1990   // GNU void* casts amount to no-ops since our void* type is i8*, but this is
1991   // future proof.
1992   if (elementType->isVoidType() || elementType->isFunctionType()) {
1993     Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
1994     result = CGF.Builder.CreateGEP(result, index, "add.ptr");
1995     return CGF.Builder.CreateBitCast(result, pointer->getType());
1996   }
1997
1998   if (CGF.getLangOpts().isSignedOverflowDefined())
1999     return CGF.Builder.CreateGEP(pointer, index, "add.ptr");
2000
2001   return CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
2002 }
2003
2004 Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
2005   if (op.LHS->getType()->isPointerTy() ||
2006       op.RHS->getType()->isPointerTy())
2007     return emitPointerArithmetic(CGF, op, /*subtraction*/ false);
2008
2009   if (op.Ty->isSignedIntegerOrEnumerationType()) {
2010     switch (CGF.getContext().getLangOpts().getSignedOverflowBehavior()) {
2011     case LangOptions::SOB_Undefined:
2012       return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
2013     case LangOptions::SOB_Defined:
2014       return Builder.CreateAdd(op.LHS, op.RHS, "add");
2015     case LangOptions::SOB_Trapping:
2016       return EmitOverflowCheckedBinOp(op);
2017     }
2018   }
2019     
2020   if (op.LHS->getType()->isFPOrFPVectorTy())
2021     return Builder.CreateFAdd(op.LHS, op.RHS, "add");
2022
2023   return Builder.CreateAdd(op.LHS, op.RHS, "add");
2024 }
2025
2026 Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
2027   // The LHS is always a pointer if either side is.
2028   if (!op.LHS->getType()->isPointerTy()) {
2029     if (op.Ty->isSignedIntegerOrEnumerationType()) {
2030       switch (CGF.getContext().getLangOpts().getSignedOverflowBehavior()) {
2031       case LangOptions::SOB_Undefined:
2032         return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
2033       case LangOptions::SOB_Defined:
2034         return Builder.CreateSub(op.LHS, op.RHS, "sub");
2035       case LangOptions::SOB_Trapping:
2036         return EmitOverflowCheckedBinOp(op);
2037       }
2038     }
2039     
2040     if (op.LHS->getType()->isFPOrFPVectorTy())
2041       return Builder.CreateFSub(op.LHS, op.RHS, "sub");
2042
2043     return Builder.CreateSub(op.LHS, op.RHS, "sub");
2044   }
2045
2046   // If the RHS is not a pointer, then we have normal pointer
2047   // arithmetic.
2048   if (!op.RHS->getType()->isPointerTy())
2049     return emitPointerArithmetic(CGF, op, /*subtraction*/ true);
2050
2051   // Otherwise, this is a pointer subtraction.
2052
2053   // Do the raw subtraction part.
2054   llvm::Value *LHS
2055     = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
2056   llvm::Value *RHS
2057     = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
2058   Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
2059
2060   // Okay, figure out the element size.
2061   const BinaryOperator *expr = cast<BinaryOperator>(op.E);
2062   QualType elementType = expr->getLHS()->getType()->getPointeeType();
2063
2064   llvm::Value *divisor = 0;
2065
2066   // For a variable-length array, this is going to be non-constant.
2067   if (const VariableArrayType *vla
2068         = CGF.getContext().getAsVariableArrayType(elementType)) {
2069     llvm::Value *numElements;
2070     llvm::tie(numElements, elementType) = CGF.getVLASize(vla);
2071
2072     divisor = numElements;
2073
2074     // Scale the number of non-VLA elements by the non-VLA element size.
2075     CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
2076     if (!eltSize.isOne())
2077       divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
2078
2079   // For everything elese, we can just compute it, safe in the
2080   // assumption that Sema won't let anything through that we can't
2081   // safely compute the size of.
2082   } else {
2083     CharUnits elementSize;
2084     // Handle GCC extension for pointer arithmetic on void* and
2085     // function pointer types.
2086     if (elementType->isVoidType() || elementType->isFunctionType())
2087       elementSize = CharUnits::One();
2088     else
2089       elementSize = CGF.getContext().getTypeSizeInChars(elementType);
2090
2091     // Don't even emit the divide for element size of 1.
2092     if (elementSize.isOne())
2093       return diffInChars;
2094
2095     divisor = CGF.CGM.getSize(elementSize);
2096   }
2097   
2098   // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
2099   // pointer difference in C is only defined in the case where both operands
2100   // are pointing to elements of an array.
2101   return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
2102 }
2103
2104 Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
2105   // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2106   // RHS to the same size as the LHS.
2107   Value *RHS = Ops.RHS;
2108   if (Ops.LHS->getType() != RHS->getType())
2109     RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
2110
2111   if (CGF.CatchUndefined 
2112       && isa<llvm::IntegerType>(Ops.LHS->getType())) {
2113     unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
2114     llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
2115     CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS,
2116                                  llvm::ConstantInt::get(RHS->getType(), Width)),
2117                              Cont, CGF.getTrapBB());
2118     CGF.EmitBlock(Cont);
2119   }
2120
2121   return Builder.CreateShl(Ops.LHS, RHS, "shl");
2122 }
2123
2124 Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
2125   // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2126   // RHS to the same size as the LHS.
2127   Value *RHS = Ops.RHS;
2128   if (Ops.LHS->getType() != RHS->getType())
2129     RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
2130
2131   if (CGF.CatchUndefined 
2132       && isa<llvm::IntegerType>(Ops.LHS->getType())) {
2133     unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
2134     llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
2135     CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS,
2136                                  llvm::ConstantInt::get(RHS->getType(), Width)),
2137                              Cont, CGF.getTrapBB());
2138     CGF.EmitBlock(Cont);
2139   }
2140
2141   if (Ops.Ty->hasUnsignedIntegerRepresentation())
2142     return Builder.CreateLShr(Ops.LHS, RHS, "shr");
2143   return Builder.CreateAShr(Ops.LHS, RHS, "shr");
2144 }
2145
2146 enum IntrinsicType { VCMPEQ, VCMPGT };
2147 // return corresponding comparison intrinsic for given vector type
2148 static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
2149                                         BuiltinType::Kind ElemKind) {
2150   switch (ElemKind) {
2151   default: llvm_unreachable("unexpected element type");
2152   case BuiltinType::Char_U:
2153   case BuiltinType::UChar:
2154     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2155                             llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
2156   case BuiltinType::Char_S:
2157   case BuiltinType::SChar:
2158     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2159                             llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
2160   case BuiltinType::UShort:
2161     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2162                             llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
2163   case BuiltinType::Short:
2164     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2165                             llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
2166   case BuiltinType::UInt:
2167   case BuiltinType::ULong:
2168     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2169                             llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
2170   case BuiltinType::Int:
2171   case BuiltinType::Long:
2172     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2173                             llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
2174   case BuiltinType::Float:
2175     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
2176                             llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
2177   }
2178 }
2179
2180 Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
2181                                       unsigned SICmpOpc, unsigned FCmpOpc) {
2182   TestAndClearIgnoreResultAssign();
2183   Value *Result;
2184   QualType LHSTy = E->getLHS()->getType();
2185   if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
2186     assert(E->getOpcode() == BO_EQ ||
2187            E->getOpcode() == BO_NE);
2188     Value *LHS = CGF.EmitScalarExpr(E->getLHS());
2189     Value *RHS = CGF.EmitScalarExpr(E->getRHS());
2190     Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
2191                    CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
2192   } else if (!LHSTy->isAnyComplexType()) {
2193     Value *LHS = Visit(E->getLHS());
2194     Value *RHS = Visit(E->getRHS());
2195
2196     // If AltiVec, the comparison results in a numeric type, so we use
2197     // intrinsics comparing vectors and giving 0 or 1 as a result
2198     if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
2199       // constants for mapping CR6 register bits to predicate result
2200       enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
2201
2202       llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
2203
2204       // in several cases vector arguments order will be reversed
2205       Value *FirstVecArg = LHS,
2206             *SecondVecArg = RHS;
2207
2208       QualType ElTy = LHSTy->getAs<VectorType>()->getElementType();
2209       const BuiltinType *BTy = ElTy->getAs<BuiltinType>();
2210       BuiltinType::Kind ElementKind = BTy->getKind();
2211
2212       switch(E->getOpcode()) {
2213       default: llvm_unreachable("is not a comparison operation");
2214       case BO_EQ:
2215         CR6 = CR6_LT;
2216         ID = GetIntrinsic(VCMPEQ, ElementKind);
2217         break;
2218       case BO_NE:
2219         CR6 = CR6_EQ;
2220         ID = GetIntrinsic(VCMPEQ, ElementKind);
2221         break;
2222       case BO_LT:
2223         CR6 = CR6_LT;
2224         ID = GetIntrinsic(VCMPGT, ElementKind);
2225         std::swap(FirstVecArg, SecondVecArg);
2226         break;
2227       case BO_GT:
2228         CR6 = CR6_LT;
2229         ID = GetIntrinsic(VCMPGT, ElementKind);
2230         break;
2231       case BO_LE:
2232         if (ElementKind == BuiltinType::Float) {
2233           CR6 = CR6_LT;
2234           ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2235           std::swap(FirstVecArg, SecondVecArg);
2236         }
2237         else {
2238           CR6 = CR6_EQ;
2239           ID = GetIntrinsic(VCMPGT, ElementKind);
2240         }
2241         break;
2242       case BO_GE:
2243         if (ElementKind == BuiltinType::Float) {
2244           CR6 = CR6_LT;
2245           ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2246         }
2247         else {
2248           CR6 = CR6_EQ;
2249           ID = GetIntrinsic(VCMPGT, ElementKind);
2250           std::swap(FirstVecArg, SecondVecArg);
2251         }
2252         break;
2253       }
2254
2255       Value *CR6Param = Builder.getInt32(CR6);
2256       llvm::Function *F = CGF.CGM.getIntrinsic(ID);
2257       Result = Builder.CreateCall3(F, CR6Param, FirstVecArg, SecondVecArg, "");
2258       return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
2259     }
2260
2261     if (LHS->getType()->isFPOrFPVectorTy()) {
2262       Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
2263                                   LHS, RHS, "cmp");
2264     } else if (LHSTy->hasSignedIntegerRepresentation()) {
2265       Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
2266                                   LHS, RHS, "cmp");
2267     } else {
2268       // Unsigned integers and pointers.
2269       Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2270                                   LHS, RHS, "cmp");
2271     }
2272
2273     // If this is a vector comparison, sign extend the result to the appropriate
2274     // vector integer type and return it (don't convert to bool).
2275     if (LHSTy->isVectorType())
2276       return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
2277
2278   } else {
2279     // Complex Comparison: can only be an equality comparison.
2280     CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
2281     CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
2282
2283     QualType CETy = LHSTy->getAs<ComplexType>()->getElementType();
2284
2285     Value *ResultR, *ResultI;
2286     if (CETy->isRealFloatingType()) {
2287       ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2288                                    LHS.first, RHS.first, "cmp.r");
2289       ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2290                                    LHS.second, RHS.second, "cmp.i");
2291     } else {
2292       // Complex comparisons can only be equality comparisons.  As such, signed
2293       // and unsigned opcodes are the same.
2294       ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2295                                    LHS.first, RHS.first, "cmp.r");
2296       ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2297                                    LHS.second, RHS.second, "cmp.i");
2298     }
2299
2300     if (E->getOpcode() == BO_EQ) {
2301       Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
2302     } else {
2303       assert(E->getOpcode() == BO_NE &&
2304              "Complex comparison other than == or != ?");
2305       Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
2306     }
2307   }
2308
2309   return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
2310 }
2311
2312 Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
2313   bool Ignore = TestAndClearIgnoreResultAssign();
2314
2315   Value *RHS;
2316   LValue LHS;
2317
2318   switch (E->getLHS()->getType().getObjCLifetime()) {
2319   case Qualifiers::OCL_Strong:
2320     llvm::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
2321     break;
2322
2323   case Qualifiers::OCL_Autoreleasing:
2324     llvm::tie(LHS,RHS) = CGF.EmitARCStoreAutoreleasing(E);
2325     break;
2326
2327   case Qualifiers::OCL_Weak:
2328     RHS = Visit(E->getRHS());
2329     LHS = EmitCheckedLValue(E->getLHS());    
2330     RHS = CGF.EmitARCStoreWeak(LHS.getAddress(), RHS, Ignore);
2331     break;
2332
2333   // No reason to do any of these differently.
2334   case Qualifiers::OCL_None:
2335   case Qualifiers::OCL_ExplicitNone:
2336     // __block variables need to have the rhs evaluated first, plus
2337     // this should improve codegen just a little.
2338     RHS = Visit(E->getRHS());
2339     LHS = EmitCheckedLValue(E->getLHS());
2340
2341     // Store the value into the LHS.  Bit-fields are handled specially
2342     // because the result is altered by the store, i.e., [C99 6.5.16p1]
2343     // 'An assignment expression has the value of the left operand after
2344     // the assignment...'.
2345     if (LHS.isBitField())
2346       CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
2347     else
2348       CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
2349   }
2350
2351   // If the result is clearly ignored, return now.
2352   if (Ignore)
2353     return 0;
2354
2355   // The result of an assignment in C is the assigned r-value.
2356   if (!CGF.getContext().getLangOpts().CPlusPlus)
2357     return RHS;
2358
2359   // If the lvalue is non-volatile, return the computed value of the assignment.
2360   if (!LHS.isVolatileQualified())
2361     return RHS;
2362
2363   // Otherwise, reload the value.
2364   return EmitLoadOfLValue(LHS);
2365 }
2366
2367 Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
2368   
2369   // Perform vector logical and on comparisons with zero vectors.
2370   if (E->getType()->isVectorType()) {
2371     Value *LHS = Visit(E->getLHS());
2372     Value *RHS = Visit(E->getRHS());
2373     Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
2374     LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
2375     RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
2376     Value *And = Builder.CreateAnd(LHS, RHS);
2377     return Builder.CreateSExt(And, Zero->getType(), "sext");
2378   }
2379   
2380   llvm::Type *ResTy = ConvertType(E->getType());
2381   
2382   // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
2383   // If we have 1 && X, just emit X without inserting the control flow.
2384   bool LHSCondVal;
2385   if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
2386     if (LHSCondVal) { // If we have 1 && X, just emit X.
2387       Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
2388       // ZExt result to int or bool.
2389       return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
2390     }
2391
2392     // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
2393     if (!CGF.ContainsLabel(E->getRHS()))
2394       return llvm::Constant::getNullValue(ResTy);
2395   }
2396
2397   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
2398   llvm::BasicBlock *RHSBlock  = CGF.createBasicBlock("land.rhs");
2399
2400   CodeGenFunction::ConditionalEvaluation eval(CGF);
2401
2402   // Branch on the LHS first.  If it is false, go to the failure (cont) block.
2403   CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
2404
2405   // Any edges into the ContBlock are now from an (indeterminate number of)
2406   // edges from this first condition.  All of these values will be false.  Start
2407   // setting up the PHI node in the Cont Block for this.
2408   llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
2409                                             "", ContBlock);
2410   for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2411        PI != PE; ++PI)
2412     PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
2413
2414   eval.begin(CGF);
2415   CGF.EmitBlock(RHSBlock);
2416   Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
2417   eval.end(CGF);
2418
2419   // Reaquire the RHS block, as there may be subblocks inserted.
2420   RHSBlock = Builder.GetInsertBlock();
2421
2422   // Emit an unconditional branch from this block to ContBlock.  Insert an entry
2423   // into the phi node for the edge with the value of RHSCond.
2424   if (CGF.getDebugInfo())
2425     // There is no need to emit line number for unconditional branch.
2426     Builder.SetCurrentDebugLocation(llvm::DebugLoc());
2427   CGF.EmitBlock(ContBlock);
2428   PN->addIncoming(RHSCond, RHSBlock);
2429
2430   // ZExt result to int.
2431   return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
2432 }
2433
2434 Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
2435   
2436   // Perform vector logical or on comparisons with zero vectors.
2437   if (E->getType()->isVectorType()) {
2438     Value *LHS = Visit(E->getLHS());
2439     Value *RHS = Visit(E->getRHS());
2440     Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
2441     LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
2442     RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
2443     Value *Or = Builder.CreateOr(LHS, RHS);
2444     return Builder.CreateSExt(Or, Zero->getType(), "sext");
2445   }
2446   
2447   llvm::Type *ResTy = ConvertType(E->getType());
2448   
2449   // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
2450   // If we have 0 || X, just emit X without inserting the control flow.
2451   bool LHSCondVal;
2452   if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
2453     if (!LHSCondVal) { // If we have 0 || X, just emit X.
2454       Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
2455       // ZExt result to int or bool.
2456       return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
2457     }
2458
2459     // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
2460     if (!CGF.ContainsLabel(E->getRHS()))
2461       return llvm::ConstantInt::get(ResTy, 1);
2462   }
2463
2464   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
2465   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
2466
2467   CodeGenFunction::ConditionalEvaluation eval(CGF);
2468
2469   // Branch on the LHS first.  If it is true, go to the success (cont) block.
2470   CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
2471
2472   // Any edges into the ContBlock are now from an (indeterminate number of)
2473   // edges from this first condition.  All of these values will be true.  Start
2474   // setting up the PHI node in the Cont Block for this.
2475   llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
2476                                             "", ContBlock);
2477   for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2478        PI != PE; ++PI)
2479     PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
2480
2481   eval.begin(CGF);
2482
2483   // Emit the RHS condition as a bool value.
2484   CGF.EmitBlock(RHSBlock);
2485   Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
2486
2487   eval.end(CGF);
2488
2489   // Reaquire the RHS block, as there may be subblocks inserted.
2490   RHSBlock = Builder.GetInsertBlock();
2491
2492   // Emit an unconditional branch from this block to ContBlock.  Insert an entry
2493   // into the phi node for the edge with the value of RHSCond.
2494   CGF.EmitBlock(ContBlock);
2495   PN->addIncoming(RHSCond, RHSBlock);
2496
2497   // ZExt result to int.
2498   return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
2499 }
2500
2501 Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
2502   CGF.EmitIgnoredExpr(E->getLHS());
2503   CGF.EnsureInsertPoint();
2504   return Visit(E->getRHS());
2505 }
2506
2507 //===----------------------------------------------------------------------===//
2508 //                             Other Operators
2509 //===----------------------------------------------------------------------===//
2510
2511 /// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
2512 /// expression is cheap enough and side-effect-free enough to evaluate
2513 /// unconditionally instead of conditionally.  This is used to convert control
2514 /// flow into selects in some cases.
2515 static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
2516                                                    CodeGenFunction &CGF) {
2517   E = E->IgnoreParens();
2518
2519   // Anything that is an integer or floating point constant is fine.
2520   if (E->isConstantInitializer(CGF.getContext(), false))
2521     return true;
2522
2523   // Non-volatile automatic variables too, to get "cond ? X : Y" where
2524   // X and Y are local variables.
2525   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2526     if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
2527       if (VD->hasLocalStorage() && !(CGF.getContext()
2528                                      .getCanonicalType(VD->getType())
2529                                      .isVolatileQualified()))
2530         return true;
2531
2532   return false;
2533 }
2534
2535
2536 Value *ScalarExprEmitter::
2537 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
2538   TestAndClearIgnoreResultAssign();
2539
2540   // Bind the common expression if necessary.
2541   CodeGenFunction::OpaqueValueMapping binding(CGF, E);
2542
2543   Expr *condExpr = E->getCond();
2544   Expr *lhsExpr = E->getTrueExpr();
2545   Expr *rhsExpr = E->getFalseExpr();
2546
2547   // If the condition constant folds and can be elided, try to avoid emitting
2548   // the condition and the dead arm.
2549   bool CondExprBool;
2550   if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
2551     Expr *live = lhsExpr, *dead = rhsExpr;
2552     if (!CondExprBool) std::swap(live, dead);
2553
2554     // If the dead side doesn't have labels we need, just emit the Live part.
2555     if (!CGF.ContainsLabel(dead)) {
2556       Value *Result = Visit(live);
2557
2558       // If the live part is a throw expression, it acts like it has a void
2559       // type, so evaluating it returns a null Value*.  However, a conditional
2560       // with non-void type must return a non-null Value*.
2561       if (!Result && !E->getType()->isVoidType())
2562         Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
2563
2564       return Result;
2565     }
2566   }
2567
2568   // OpenCL: If the condition is a vector, we can treat this condition like
2569   // the select function.
2570   if (CGF.getContext().getLangOpts().OpenCL 
2571       && condExpr->getType()->isVectorType()) {
2572     llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
2573     llvm::Value *LHS = Visit(lhsExpr);
2574     llvm::Value *RHS = Visit(rhsExpr);
2575     
2576     llvm::Type *condType = ConvertType(condExpr->getType());
2577     llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
2578     
2579     unsigned numElem = vecTy->getNumElements();      
2580     llvm::Type *elemType = vecTy->getElementType();
2581     
2582     llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy);
2583     llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
2584     llvm::Value *tmp = Builder.CreateSExt(TestMSB, 
2585                                           llvm::VectorType::get(elemType,
2586                                                                 numElem),         
2587                                           "sext");
2588     llvm::Value *tmp2 = Builder.CreateNot(tmp);
2589     
2590     // Cast float to int to perform ANDs if necessary.
2591     llvm::Value *RHSTmp = RHS;
2592     llvm::Value *LHSTmp = LHS;
2593     bool wasCast = false;
2594     llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
2595     if (rhsVTy->getElementType()->isFloatTy()) {
2596       RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
2597       LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
2598       wasCast = true;
2599     }
2600     
2601     llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
2602     llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
2603     llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
2604     if (wasCast)
2605       tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
2606
2607     return tmp5;
2608   }
2609   
2610   // If this is a really simple expression (like x ? 4 : 5), emit this as a
2611   // select instead of as control flow.  We can only do this if it is cheap and
2612   // safe to evaluate the LHS and RHS unconditionally.
2613   if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
2614       isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
2615     llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
2616     llvm::Value *LHS = Visit(lhsExpr);
2617     llvm::Value *RHS = Visit(rhsExpr);
2618     if (!LHS) {
2619       // If the conditional has void type, make sure we return a null Value*.
2620       assert(!RHS && "LHS and RHS types must match");
2621       return 0;
2622     }
2623     return Builder.CreateSelect(CondV, LHS, RHS, "cond");
2624   }
2625
2626   llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
2627   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
2628   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
2629
2630   CodeGenFunction::ConditionalEvaluation eval(CGF);
2631   CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock);
2632
2633   CGF.EmitBlock(LHSBlock);
2634   eval.begin(CGF);
2635   Value *LHS = Visit(lhsExpr);
2636   eval.end(CGF);
2637
2638   LHSBlock = Builder.GetInsertBlock();
2639   Builder.CreateBr(ContBlock);
2640
2641   CGF.EmitBlock(RHSBlock);
2642   eval.begin(CGF);
2643   Value *RHS = Visit(rhsExpr);
2644   eval.end(CGF);
2645
2646   RHSBlock = Builder.GetInsertBlock();
2647   CGF.EmitBlock(ContBlock);
2648
2649   // If the LHS or RHS is a throw expression, it will be legitimately null.
2650   if (!LHS)
2651     return RHS;
2652   if (!RHS)
2653     return LHS;
2654
2655   // Create a PHI node for the real part.
2656   llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
2657   PN->addIncoming(LHS, LHSBlock);
2658   PN->addIncoming(RHS, RHSBlock);
2659   return PN;
2660 }
2661
2662 Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
2663   return Visit(E->getChosenSubExpr(CGF.getContext()));
2664 }
2665
2666 Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
2667   llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
2668   llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
2669
2670   // If EmitVAArg fails, we fall back to the LLVM instruction.
2671   if (!ArgPtr)
2672     return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
2673
2674   // FIXME Volatility.
2675   return Builder.CreateLoad(ArgPtr);
2676 }
2677
2678 Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
2679   return CGF.EmitBlockLiteral(block);
2680 }
2681
2682 Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
2683   Value *Src  = CGF.EmitScalarExpr(E->getSrcExpr());
2684   llvm::Type *DstTy = ConvertType(E->getType());
2685   
2686   // Going from vec4->vec3 or vec3->vec4 is a special case and requires
2687   // a shuffle vector instead of a bitcast.
2688   llvm::Type *SrcTy = Src->getType();
2689   if (isa<llvm::VectorType>(DstTy) && isa<llvm::VectorType>(SrcTy)) {
2690     unsigned numElementsDst = cast<llvm::VectorType>(DstTy)->getNumElements();
2691     unsigned numElementsSrc = cast<llvm::VectorType>(SrcTy)->getNumElements();
2692     if ((numElementsDst == 3 && numElementsSrc == 4) 
2693         || (numElementsDst == 4 && numElementsSrc == 3)) {
2694       
2695       
2696       // In the case of going from int4->float3, a bitcast is needed before
2697       // doing a shuffle.
2698       llvm::Type *srcElemTy = 
2699       cast<llvm::VectorType>(SrcTy)->getElementType();
2700       llvm::Type *dstElemTy = 
2701       cast<llvm::VectorType>(DstTy)->getElementType();
2702       
2703       if ((srcElemTy->isIntegerTy() && dstElemTy->isFloatTy())
2704           || (srcElemTy->isFloatTy() && dstElemTy->isIntegerTy())) {
2705         // Create a float type of the same size as the source or destination.
2706         llvm::VectorType *newSrcTy = llvm::VectorType::get(dstElemTy,
2707                                                                  numElementsSrc);
2708         
2709         Src = Builder.CreateBitCast(Src, newSrcTy, "astypeCast");
2710       }
2711       
2712       llvm::Value *UnV = llvm::UndefValue::get(Src->getType());
2713       
2714       SmallVector<llvm::Constant*, 3> Args;
2715       Args.push_back(Builder.getInt32(0));
2716       Args.push_back(Builder.getInt32(1));
2717       Args.push_back(Builder.getInt32(2));
2718  
2719       if (numElementsDst == 4)
2720         Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
2721       
2722       llvm::Constant *Mask = llvm::ConstantVector::get(Args);
2723       
2724       return Builder.CreateShuffleVector(Src, UnV, Mask, "astype");
2725     }
2726   }
2727   
2728   return Builder.CreateBitCast(Src, DstTy, "astype");
2729 }
2730
2731 Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
2732   return CGF.EmitAtomicExpr(E).getScalarVal();
2733 }
2734
2735 //===----------------------------------------------------------------------===//
2736 //                         Entry Point into this File
2737 //===----------------------------------------------------------------------===//
2738
2739 /// EmitScalarExpr - Emit the computation of the specified expression of scalar
2740 /// type, ignoring the result.
2741 Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
2742   assert(E && !hasAggregateLLVMType(E->getType()) &&
2743          "Invalid scalar expression to emit");
2744
2745   if (isa<CXXDefaultArgExpr>(E))
2746     disableDebugInfo();
2747   Value *V = ScalarExprEmitter(*this, IgnoreResultAssign)
2748     .Visit(const_cast<Expr*>(E));
2749   if (isa<CXXDefaultArgExpr>(E))
2750     enableDebugInfo();
2751   return V;
2752 }
2753
2754 /// EmitScalarConversion - Emit a conversion from the specified type to the
2755 /// specified destination type, both of which are LLVM scalar types.
2756 Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
2757                                              QualType DstTy) {
2758   assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
2759          "Invalid scalar expression to emit");
2760   return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
2761 }
2762
2763 /// EmitComplexToScalarConversion - Emit a conversion from the specified complex
2764 /// type to the specified destination type, where the destination type is an
2765 /// LLVM scalar type.
2766 Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
2767                                                       QualType SrcTy,
2768                                                       QualType DstTy) {
2769   assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
2770          "Invalid complex -> scalar conversion");
2771   return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
2772                                                                 DstTy);
2773 }
2774
2775
2776 llvm::Value *CodeGenFunction::
2777 EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2778                         bool isInc, bool isPre) {
2779   return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
2780 }
2781
2782 LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
2783   llvm::Value *V;
2784   // object->isa or (*object).isa
2785   // Generate code as for: *(Class*)object
2786   // build Class* type
2787   llvm::Type *ClassPtrTy = ConvertType(E->getType());
2788
2789   Expr *BaseExpr = E->getBase();
2790   if (BaseExpr->isRValue()) {
2791     V = CreateMemTemp(E->getType(), "resval");
2792     llvm::Value *Src = EmitScalarExpr(BaseExpr);
2793     Builder.CreateStore(Src, V);
2794     V = ScalarExprEmitter(*this).EmitLoadOfLValue(
2795       MakeNaturalAlignAddrLValue(V, E->getType()));
2796   } else {
2797     if (E->isArrow())
2798       V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr);
2799     else
2800       V = EmitLValue(BaseExpr).getAddress();
2801   }
2802   
2803   // build Class* type
2804   ClassPtrTy = ClassPtrTy->getPointerTo();
2805   V = Builder.CreateBitCast(V, ClassPtrTy);
2806   return MakeNaturalAlignAddrLValue(V, E->getType());
2807 }
2808
2809
2810 LValue CodeGenFunction::EmitCompoundAssignmentLValue(
2811                                             const CompoundAssignOperator *E) {
2812   ScalarExprEmitter Scalar(*this);
2813   Value *Result = 0;
2814   switch (E->getOpcode()) {
2815 #define COMPOUND_OP(Op)                                                       \
2816     case BO_##Op##Assign:                                                     \
2817       return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
2818                                              Result)
2819   COMPOUND_OP(Mul);
2820   COMPOUND_OP(Div);
2821   COMPOUND_OP(Rem);
2822   COMPOUND_OP(Add);
2823   COMPOUND_OP(Sub);
2824   COMPOUND_OP(Shl);
2825   COMPOUND_OP(Shr);
2826   COMPOUND_OP(And);
2827   COMPOUND_OP(Xor);
2828   COMPOUND_OP(Or);
2829 #undef COMPOUND_OP
2830       
2831   case BO_PtrMemD:
2832   case BO_PtrMemI:
2833   case BO_Mul:
2834   case BO_Div:
2835   case BO_Rem:
2836   case BO_Add:
2837   case BO_Sub:
2838   case BO_Shl:
2839   case BO_Shr:
2840   case BO_LT:
2841   case BO_GT:
2842   case BO_LE:
2843   case BO_GE:
2844   case BO_EQ:
2845   case BO_NE:
2846   case BO_And:
2847   case BO_Xor:
2848   case BO_Or:
2849   case BO_LAnd:
2850   case BO_LOr:
2851   case BO_Assign:
2852   case BO_Comma:
2853     llvm_unreachable("Not valid compound assignment operators");
2854   }
2855    
2856   llvm_unreachable("Unhandled compound assignment operator");
2857 }