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