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