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