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