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       V = CGF.Builder.CreatePointerCast(
1415           V, ConvertType(E->getType())->getPointerTo(
1416             V->getType()->getPointerAddressSpace()));
1417 
1418       assert(isa<llvm::ArrayType>(V->getType()->getPointerElementType()) &&
1419              "Expected pointer to array");
1420       V = Builder.CreateStructGEP(V, 0, "arraydecay");
1421     }
1422 
1423     // Make sure the array decay ends up being the right type.  This matters if
1424     // the array type was of an incomplete type.
1425     return CGF.Builder.CreatePointerCast(V, ConvertType(CE->getType()));
1426   }
1427   case CK_FunctionToPointerDecay:
1428     return EmitLValue(E).getAddress();
1429 
1430   case CK_NullToPointer:
1431     if (MustVisitNullValue(E))
1432       (void) Visit(E);
1433 
1434     return llvm::ConstantPointerNull::get(
1435                                cast<llvm::PointerType>(ConvertType(DestTy)));
1436 
1437   case CK_NullToMemberPointer: {
1438     if (MustVisitNullValue(E))
1439       (void) Visit(E);
1440 
1441     const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
1442     return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
1443   }
1444 
1445   case CK_ReinterpretMemberPointer:
1446   case CK_BaseToDerivedMemberPointer:
1447   case CK_DerivedToBaseMemberPointer: {
1448     Value *Src = Visit(E);
1449 
1450     // Note that the AST doesn't distinguish between checked and
1451     // unchecked member pointer conversions, so we always have to
1452     // implement checked conversions here.  This is inefficient when
1453     // actual control flow may be required in order to perform the
1454     // check, which it is for data member pointers (but not member
1455     // function pointers on Itanium and ARM).
1456     return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
1457   }
1458 
1459   case CK_ARCProduceObject:
1460     return CGF.EmitARCRetainScalarExpr(E);
1461   case CK_ARCConsumeObject:
1462     return CGF.EmitObjCConsumeObject(E->getType(), Visit(E));
1463   case CK_ARCReclaimReturnedObject: {
1464     llvm::Value *value = Visit(E);
1465     value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
1466     return CGF.EmitObjCConsumeObject(E->getType(), value);
1467   }
1468   case CK_ARCExtendBlockObject:
1469     return CGF.EmitARCExtendBlockObject(E);
1470 
1471   case CK_CopyAndAutoreleaseBlockObject:
1472     return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType());
1473 
1474   case CK_FloatingRealToComplex:
1475   case CK_FloatingComplexCast:
1476   case CK_IntegralRealToComplex:
1477   case CK_IntegralComplexCast:
1478   case CK_IntegralComplexToFloatingComplex:
1479   case CK_FloatingComplexToIntegralComplex:
1480   case CK_ConstructorConversion:
1481   case CK_ToUnion:
1482     llvm_unreachable("scalar cast to non-scalar value");
1483 
1484   case CK_LValueToRValue:
1485     assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
1486     assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
1487     return Visit(const_cast<Expr*>(E));
1488 
1489   case CK_IntegralToPointer: {
1490     Value *Src = Visit(const_cast<Expr*>(E));
1491 
1492     // First, convert to the correct width so that we control the kind of
1493     // extension.
1494     llvm::Type *MiddleTy = CGF.IntPtrTy;
1495     bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
1496     llvm::Value* IntResult =
1497       Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
1498 
1499     return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy));
1500   }
1501   case CK_PointerToIntegral:
1502     assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
1503     return Builder.CreatePtrToInt(Visit(E), ConvertType(DestTy));
1504 
1505   case CK_ToVoid: {
1506     CGF.EmitIgnoredExpr(E);
1507     return nullptr;
1508   }
1509   case CK_VectorSplat: {
1510     llvm::Type *DstTy = ConvertType(DestTy);
1511     Value *Elt = Visit(const_cast<Expr*>(E));
1512     Elt = EmitScalarConversion(Elt, E->getType(),
1513                                DestTy->getAs<VectorType>()->getElementType());
1514 
1515     // Splat the element across to all elements
1516     unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
1517     return Builder.CreateVectorSplat(NumElements, Elt, "splat");
1518   }
1519 
1520   case CK_IntegralCast:
1521   case CK_IntegralToFloating:
1522   case CK_FloatingToIntegral:
1523   case CK_FloatingCast:
1524     return EmitScalarConversion(Visit(E), E->getType(), DestTy);
1525   case CK_IntegralToBoolean:
1526     return EmitIntToBoolConversion(Visit(E));
1527   case CK_PointerToBoolean:
1528     return EmitPointerToBoolConversion(Visit(E));
1529   case CK_FloatingToBoolean:
1530     return EmitFloatToBoolConversion(Visit(E));
1531   case CK_MemberPointerToBoolean: {
1532     llvm::Value *MemPtr = Visit(E);
1533     const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
1534     return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
1535   }
1536 
1537   case CK_FloatingComplexToReal:
1538   case CK_IntegralComplexToReal:
1539     return CGF.EmitComplexExpr(E, false, true).first;
1540 
1541   case CK_FloatingComplexToBoolean:
1542   case CK_IntegralComplexToBoolean: {
1543     CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
1544 
1545     // TODO: kill this function off, inline appropriate case here
1546     return EmitComplexToScalarConversion(V, E->getType(), DestTy);
1547   }
1548 
1549   case CK_ZeroToOCLEvent: {
1550     assert(DestTy->isEventT() && "CK_ZeroToOCLEvent cast on non-event type");
1551     return llvm::Constant::getNullValue(ConvertType(DestTy));
1552   }
1553 
1554   }
1555 
1556   llvm_unreachable("unknown scalar cast");
1557 }
1558 
1559 Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
1560   CodeGenFunction::StmtExprEvaluation eval(CGF);
1561   llvm::Value *RetAlloca = CGF.EmitCompoundStmt(*E->getSubStmt(),
1562                                                 !E->getType()->isVoidType());
1563   if (!RetAlloca)
1564     return nullptr;
1565   return CGF.EmitLoadOfScalar(CGF.MakeAddrLValue(RetAlloca, E->getType()),
1566                               E->getExprLoc());
1567 }
1568 
1569 //===----------------------------------------------------------------------===//
1570 //                             Unary Operators
1571 //===----------------------------------------------------------------------===//
1572 
1573 llvm::Value *ScalarExprEmitter::
1574 EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
1575                                 llvm::Value *InVal,
1576                                 llvm::Value *NextVal, bool IsInc) {
1577   switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
1578   case LangOptions::SOB_Defined:
1579     return Builder.CreateAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1580   case LangOptions::SOB_Undefined:
1581     if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
1582       return Builder.CreateNSWAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1583     // Fall through.
1584   case LangOptions::SOB_Trapping:
1585     BinOpInfo BinOp;
1586     BinOp.LHS = InVal;
1587     BinOp.RHS = NextVal;
1588     BinOp.Ty = E->getType();
1589     BinOp.Opcode = BO_Add;
1590     BinOp.FPContractable = false;
1591     BinOp.E = E;
1592     return EmitOverflowCheckedBinOp(BinOp);
1593   }
1594   llvm_unreachable("Unknown SignedOverflowBehaviorTy");
1595 }
1596 
1597 llvm::Value *
1598 ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1599                                            bool isInc, bool isPre) {
1600 
1601   QualType type = E->getSubExpr()->getType();
1602   llvm::PHINode *atomicPHI = nullptr;
1603   llvm::Value *value;
1604   llvm::Value *input;
1605 
1606   int amount = (isInc ? 1 : -1);
1607 
1608   if (const AtomicType *atomicTy = type->getAs<AtomicType>()) {
1609     type = atomicTy->getValueType();
1610     if (isInc && type->isBooleanType()) {
1611       llvm::Value *True = CGF.EmitToMemory(Builder.getTrue(), type);
1612       if (isPre) {
1613         Builder.Insert(new llvm::StoreInst(True,
1614               LV.getAddress(), LV.isVolatileQualified(),
1615               LV.getAlignment().getQuantity(),
1616               llvm::SequentiallyConsistent));
1617         return Builder.getTrue();
1618       }
1619       // For atomic bool increment, we just store true and return it for
1620       // preincrement, do an atomic swap with true for postincrement
1621         return Builder.CreateAtomicRMW(llvm::AtomicRMWInst::Xchg,
1622             LV.getAddress(), True, llvm::SequentiallyConsistent);
1623     }
1624     // Special case for atomic increment / decrement on integers, emit
1625     // atomicrmw instructions.  We skip this if we want to be doing overflow
1626     // checking, and fall into the slow path with the atomic cmpxchg loop.
1627     if (!type->isBooleanType() && type->isIntegerType() &&
1628         !(type->isUnsignedIntegerType() &&
1629           CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
1630         CGF.getLangOpts().getSignedOverflowBehavior() !=
1631             LangOptions::SOB_Trapping) {
1632       llvm::AtomicRMWInst::BinOp aop = isInc ? llvm::AtomicRMWInst::Add :
1633         llvm::AtomicRMWInst::Sub;
1634       llvm::Instruction::BinaryOps op = isInc ? llvm::Instruction::Add :
1635         llvm::Instruction::Sub;
1636       llvm::Value *amt = CGF.EmitToMemory(
1637           llvm::ConstantInt::get(ConvertType(type), 1, true), type);
1638       llvm::Value *old = Builder.CreateAtomicRMW(aop,
1639           LV.getAddress(), amt, llvm::SequentiallyConsistent);
1640       return isPre ? Builder.CreateBinOp(op, old, amt) : old;
1641     }
1642     value = EmitLoadOfLValue(LV, E->getExprLoc());
1643     input = value;
1644     // For every other atomic operation, we need to emit a load-op-cmpxchg loop
1645     llvm::BasicBlock *startBB = Builder.GetInsertBlock();
1646     llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
1647     value = CGF.EmitToMemory(value, type);
1648     Builder.CreateBr(opBB);
1649     Builder.SetInsertPoint(opBB);
1650     atomicPHI = Builder.CreatePHI(value->getType(), 2);
1651     atomicPHI->addIncoming(value, startBB);
1652     value = atomicPHI;
1653   } else {
1654     value = EmitLoadOfLValue(LV, E->getExprLoc());
1655     input = value;
1656   }
1657 
1658   // Special case of integer increment that we have to check first: bool++.
1659   // Due to promotion rules, we get:
1660   //   bool++ -> bool = bool + 1
1661   //          -> bool = (int)bool + 1
1662   //          -> bool = ((int)bool + 1 != 0)
1663   // An interesting aspect of this is that increment is always true.
1664   // Decrement does not have this property.
1665   if (isInc && type->isBooleanType()) {
1666     value = Builder.getTrue();
1667 
1668   // Most common case by far: integer increment.
1669   } else if (type->isIntegerType()) {
1670 
1671     llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount, true);
1672 
1673     // Note that signed integer inc/dec with width less than int can't
1674     // overflow because of promotion rules; we're just eliding a few steps here.
1675     bool CanOverflow = value->getType()->getIntegerBitWidth() >=
1676                        CGF.IntTy->getIntegerBitWidth();
1677     if (CanOverflow && type->isSignedIntegerOrEnumerationType()) {
1678       value = EmitAddConsiderOverflowBehavior(E, value, amt, isInc);
1679     } else if (CanOverflow && type->isUnsignedIntegerType() &&
1680                CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) {
1681       BinOpInfo BinOp;
1682       BinOp.LHS = value;
1683       BinOp.RHS = llvm::ConstantInt::get(value->getType(), 1, false);
1684       BinOp.Ty = E->getType();
1685       BinOp.Opcode = isInc ? BO_Add : BO_Sub;
1686       BinOp.FPContractable = false;
1687       BinOp.E = E;
1688       value = EmitOverflowCheckedBinOp(BinOp);
1689     } else
1690       value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1691 
1692   // Next most common: pointer increment.
1693   } else if (const PointerType *ptr = type->getAs<PointerType>()) {
1694     QualType type = ptr->getPointeeType();
1695 
1696     // VLA types don't have constant size.
1697     if (const VariableArrayType *vla
1698           = CGF.getContext().getAsVariableArrayType(type)) {
1699       llvm::Value *numElts = CGF.getVLASize(vla).first;
1700       if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize");
1701       if (CGF.getLangOpts().isSignedOverflowDefined())
1702         value = Builder.CreateGEP(value, numElts, "vla.inc");
1703       else
1704         value = Builder.CreateInBoundsGEP(value, numElts, "vla.inc");
1705 
1706     // Arithmetic on function pointers (!) is just +-1.
1707     } else if (type->isFunctionType()) {
1708       llvm::Value *amt = Builder.getInt32(amount);
1709 
1710       value = CGF.EmitCastToVoidPtr(value);
1711       if (CGF.getLangOpts().isSignedOverflowDefined())
1712         value = Builder.CreateGEP(value, amt, "incdec.funcptr");
1713       else
1714         value = Builder.CreateInBoundsGEP(value, amt, "incdec.funcptr");
1715       value = Builder.CreateBitCast(value, input->getType());
1716 
1717     // For everything else, we can just do a simple increment.
1718     } else {
1719       llvm::Value *amt = Builder.getInt32(amount);
1720       if (CGF.getLangOpts().isSignedOverflowDefined())
1721         value = Builder.CreateGEP(value, amt, "incdec.ptr");
1722       else
1723         value = Builder.CreateInBoundsGEP(value, amt, "incdec.ptr");
1724     }
1725 
1726   // Vector increment/decrement.
1727   } else if (type->isVectorType()) {
1728     if (type->hasIntegerRepresentation()) {
1729       llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1730 
1731       value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1732     } else {
1733       value = Builder.CreateFAdd(
1734                   value,
1735                   llvm::ConstantFP::get(value->getType(), amount),
1736                   isInc ? "inc" : "dec");
1737     }
1738 
1739   // Floating point.
1740   } else if (type->isRealFloatingType()) {
1741     // Add the inc/dec to the real part.
1742     llvm::Value *amt;
1743 
1744     if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType &&
1745         !CGF.getContext().getLangOpts().HalfArgsAndReturns) {
1746       // Another special case: half FP increment should be done via float
1747       value = Builder.CreateCall(
1748           CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16,
1749                                CGF.CGM.FloatTy),
1750           input);
1751     }
1752 
1753     if (value->getType()->isFloatTy())
1754       amt = llvm::ConstantFP::get(VMContext,
1755                                   llvm::APFloat(static_cast<float>(amount)));
1756     else if (value->getType()->isDoubleTy())
1757       amt = llvm::ConstantFP::get(VMContext,
1758                                   llvm::APFloat(static_cast<double>(amount)));
1759     else {
1760       llvm::APFloat F(static_cast<float>(amount));
1761       bool ignored;
1762       F.convert(CGF.getTarget().getLongDoubleFormat(),
1763                 llvm::APFloat::rmTowardZero, &ignored);
1764       amt = llvm::ConstantFP::get(VMContext, F);
1765     }
1766     value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
1767 
1768     if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType &&
1769         !CGF.getContext().getLangOpts().HalfArgsAndReturns)
1770       value = Builder.CreateCall(
1771           CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16,
1772                                CGF.CGM.FloatTy),
1773           value);
1774 
1775   // Objective-C pointer types.
1776   } else {
1777     const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
1778     value = CGF.EmitCastToVoidPtr(value);
1779 
1780     CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
1781     if (!isInc) size = -size;
1782     llvm::Value *sizeValue =
1783       llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
1784 
1785     if (CGF.getLangOpts().isSignedOverflowDefined())
1786       value = Builder.CreateGEP(value, sizeValue, "incdec.objptr");
1787     else
1788       value = Builder.CreateInBoundsGEP(value, sizeValue, "incdec.objptr");
1789     value = Builder.CreateBitCast(value, input->getType());
1790   }
1791 
1792   if (atomicPHI) {
1793     llvm::BasicBlock *opBB = Builder.GetInsertBlock();
1794     llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
1795     auto Pair = CGF.EmitAtomicCompareExchange(
1796         LV, RValue::get(atomicPHI), RValue::get(CGF.EmitToMemory(value, type)),
1797         E->getExprLoc());
1798     llvm::Value *old = Pair.first.getScalarVal();
1799     llvm::Value *success = Pair.second.getScalarVal();
1800     atomicPHI->addIncoming(old, opBB);
1801     Builder.CreateCondBr(success, contBB, opBB);
1802     Builder.SetInsertPoint(contBB);
1803     return isPre ? value : input;
1804   }
1805 
1806   // Store the updated result through the lvalue.
1807   if (LV.isBitField())
1808     CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
1809   else
1810     CGF.EmitStoreThroughLValue(RValue::get(value), LV);
1811 
1812   // If this is a postinc, return the value read from memory, otherwise use the
1813   // updated value.
1814   return isPre ? value : input;
1815 }
1816 
1817 
1818 
1819 Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
1820   TestAndClearIgnoreResultAssign();
1821   // Emit unary minus with EmitSub so we handle overflow cases etc.
1822   BinOpInfo BinOp;
1823   BinOp.RHS = Visit(E->getSubExpr());
1824 
1825   if (BinOp.RHS->getType()->isFPOrFPVectorTy())
1826     BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
1827   else
1828     BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
1829   BinOp.Ty = E->getType();
1830   BinOp.Opcode = BO_Sub;
1831   BinOp.FPContractable = false;
1832   BinOp.E = E;
1833   return EmitSub(BinOp);
1834 }
1835 
1836 Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
1837   TestAndClearIgnoreResultAssign();
1838   Value *Op = Visit(E->getSubExpr());
1839   return Builder.CreateNot(Op, "neg");
1840 }
1841 
1842 Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
1843   // Perform vector logical not on comparison with zero vector.
1844   if (E->getType()->isExtVectorType()) {
1845     Value *Oper = Visit(E->getSubExpr());
1846     Value *Zero = llvm::Constant::getNullValue(Oper->getType());
1847     Value *Result;
1848     if (Oper->getType()->isFPOrFPVectorTy())
1849       Result = Builder.CreateFCmp(llvm::CmpInst::FCMP_OEQ, Oper, Zero, "cmp");
1850     else
1851       Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp");
1852     return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
1853   }
1854 
1855   // Compare operand to zero.
1856   Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
1857 
1858   // Invert value.
1859   // TODO: Could dynamically modify easy computations here.  For example, if
1860   // the operand is an icmp ne, turn into icmp eq.
1861   BoolVal = Builder.CreateNot(BoolVal, "lnot");
1862 
1863   // ZExt result to the expr type.
1864   return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
1865 }
1866 
1867 Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
1868   // Try folding the offsetof to a constant.
1869   llvm::APSInt Value;
1870   if (E->EvaluateAsInt(Value, CGF.getContext()))
1871     return Builder.getInt(Value);
1872 
1873   // Loop over the components of the offsetof to compute the value.
1874   unsigned n = E->getNumComponents();
1875   llvm::Type* ResultType = ConvertType(E->getType());
1876   llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
1877   QualType CurrentType = E->getTypeSourceInfo()->getType();
1878   for (unsigned i = 0; i != n; ++i) {
1879     OffsetOfExpr::OffsetOfNode ON = E->getComponent(i);
1880     llvm::Value *Offset = nullptr;
1881     switch (ON.getKind()) {
1882     case OffsetOfExpr::OffsetOfNode::Array: {
1883       // Compute the index
1884       Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
1885       llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
1886       bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
1887       Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
1888 
1889       // Save the element type
1890       CurrentType =
1891           CGF.getContext().getAsArrayType(CurrentType)->getElementType();
1892 
1893       // Compute the element size
1894       llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
1895           CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
1896 
1897       // Multiply out to compute the result
1898       Offset = Builder.CreateMul(Idx, ElemSize);
1899       break;
1900     }
1901 
1902     case OffsetOfExpr::OffsetOfNode::Field: {
1903       FieldDecl *MemberDecl = ON.getField();
1904       RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1905       const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1906 
1907       // Compute the index of the field in its parent.
1908       unsigned i = 0;
1909       // FIXME: It would be nice if we didn't have to loop here!
1910       for (RecordDecl::field_iterator Field = RD->field_begin(),
1911                                       FieldEnd = RD->field_end();
1912            Field != FieldEnd; ++Field, ++i) {
1913         if (*Field == MemberDecl)
1914           break;
1915       }
1916       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1917 
1918       // Compute the offset to the field
1919       int64_t OffsetInt = RL.getFieldOffset(i) /
1920                           CGF.getContext().getCharWidth();
1921       Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1922 
1923       // Save the element type.
1924       CurrentType = MemberDecl->getType();
1925       break;
1926     }
1927 
1928     case OffsetOfExpr::OffsetOfNode::Identifier:
1929       llvm_unreachable("dependent __builtin_offsetof");
1930 
1931     case OffsetOfExpr::OffsetOfNode::Base: {
1932       if (ON.getBase()->isVirtual()) {
1933         CGF.ErrorUnsupported(E, "virtual base in offsetof");
1934         continue;
1935       }
1936 
1937       RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1938       const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1939 
1940       // Save the element type.
1941       CurrentType = ON.getBase()->getType();
1942 
1943       // Compute the offset to the base.
1944       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1945       CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
1946       CharUnits OffsetInt = RL.getBaseClassOffset(BaseRD);
1947       Offset = llvm::ConstantInt::get(ResultType, OffsetInt.getQuantity());
1948       break;
1949     }
1950     }
1951     Result = Builder.CreateAdd(Result, Offset);
1952   }
1953   return Result;
1954 }
1955 
1956 /// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
1957 /// argument of the sizeof expression as an integer.
1958 Value *
1959 ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
1960                               const UnaryExprOrTypeTraitExpr *E) {
1961   QualType TypeToSize = E->getTypeOfArgument();
1962   if (E->getKind() == UETT_SizeOf) {
1963     if (const VariableArrayType *VAT =
1964           CGF.getContext().getAsVariableArrayType(TypeToSize)) {
1965       if (E->isArgumentType()) {
1966         // sizeof(type) - make sure to emit the VLA size.
1967         CGF.EmitVariablyModifiedType(TypeToSize);
1968       } else {
1969         // C99 6.5.3.4p2: If the argument is an expression of type
1970         // VLA, it is evaluated.
1971         CGF.EmitIgnoredExpr(E->getArgumentExpr());
1972       }
1973 
1974       QualType eltType;
1975       llvm::Value *numElts;
1976       std::tie(numElts, eltType) = CGF.getVLASize(VAT);
1977 
1978       llvm::Value *size = numElts;
1979 
1980       // Scale the number of non-VLA elements by the non-VLA element size.
1981       CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
1982       if (!eltSize.isOne())
1983         size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), numElts);
1984 
1985       return size;
1986     }
1987   }
1988 
1989   // If this isn't sizeof(vla), the result must be constant; use the constant
1990   // folding logic so we don't have to duplicate it here.
1991   return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext()));
1992 }
1993 
1994 Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
1995   Expr *Op = E->getSubExpr();
1996   if (Op->getType()->isAnyComplexType()) {
1997     // If it's an l-value, load through the appropriate subobject l-value.
1998     // Note that we have to ask E because Op might be an l-value that
1999     // this won't work for, e.g. an Obj-C property.
2000     if (E->isGLValue())
2001       return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
2002                                   E->getExprLoc()).getScalarVal();
2003 
2004     // Otherwise, calculate and project.
2005     return CGF.EmitComplexExpr(Op, false, true).first;
2006   }
2007 
2008   return Visit(Op);
2009 }
2010 
2011 Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
2012   Expr *Op = E->getSubExpr();
2013   if (Op->getType()->isAnyComplexType()) {
2014     // If it's an l-value, load through the appropriate subobject l-value.
2015     // Note that we have to ask E because Op might be an l-value that
2016     // this won't work for, e.g. an Obj-C property.
2017     if (Op->isGLValue())
2018       return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
2019                                   E->getExprLoc()).getScalarVal();
2020 
2021     // Otherwise, calculate and project.
2022     return CGF.EmitComplexExpr(Op, true, false).second;
2023   }
2024 
2025   // __imag on a scalar returns zero.  Emit the subexpr to ensure side
2026   // effects are evaluated, but not the actual value.
2027   if (Op->isGLValue())
2028     CGF.EmitLValue(Op);
2029   else
2030     CGF.EmitScalarExpr(Op, true);
2031   return llvm::Constant::getNullValue(ConvertType(E->getType()));
2032 }
2033 
2034 //===----------------------------------------------------------------------===//
2035 //                           Binary Operators
2036 //===----------------------------------------------------------------------===//
2037 
2038 BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
2039   TestAndClearIgnoreResultAssign();
2040   BinOpInfo Result;
2041   Result.LHS = Visit(E->getLHS());
2042   Result.RHS = Visit(E->getRHS());
2043   Result.Ty  = E->getType();
2044   Result.Opcode = E->getOpcode();
2045   Result.FPContractable = E->isFPContractable();
2046   Result.E = E;
2047   return Result;
2048 }
2049 
2050 LValue ScalarExprEmitter::EmitCompoundAssignLValue(
2051                                               const CompoundAssignOperator *E,
2052                         Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
2053                                                    Value *&Result) {
2054   QualType LHSTy = E->getLHS()->getType();
2055   BinOpInfo OpInfo;
2056 
2057   if (E->getComputationResultType()->isAnyComplexType())
2058     return CGF.EmitScalarCompooundAssignWithComplex(E, Result);
2059 
2060   // Emit the RHS first.  __block variables need to have the rhs evaluated
2061   // first, plus this should improve codegen a little.
2062   OpInfo.RHS = Visit(E->getRHS());
2063   OpInfo.Ty = E->getComputationResultType();
2064   OpInfo.Opcode = E->getOpcode();
2065   OpInfo.FPContractable = false;
2066   OpInfo.E = E;
2067   // Load/convert the LHS.
2068   LValue LHSLV = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
2069 
2070   llvm::PHINode *atomicPHI = nullptr;
2071   if (const AtomicType *atomicTy = LHSTy->getAs<AtomicType>()) {
2072     QualType type = atomicTy->getValueType();
2073     if (!type->isBooleanType() && type->isIntegerType() &&
2074         !(type->isUnsignedIntegerType() &&
2075           CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
2076         CGF.getLangOpts().getSignedOverflowBehavior() !=
2077             LangOptions::SOB_Trapping) {
2078       llvm::AtomicRMWInst::BinOp aop = llvm::AtomicRMWInst::BAD_BINOP;
2079       switch (OpInfo.Opcode) {
2080         // We don't have atomicrmw operands for *, %, /, <<, >>
2081         case BO_MulAssign: case BO_DivAssign:
2082         case BO_RemAssign:
2083         case BO_ShlAssign:
2084         case BO_ShrAssign:
2085           break;
2086         case BO_AddAssign:
2087           aop = llvm::AtomicRMWInst::Add;
2088           break;
2089         case BO_SubAssign:
2090           aop = llvm::AtomicRMWInst::Sub;
2091           break;
2092         case BO_AndAssign:
2093           aop = llvm::AtomicRMWInst::And;
2094           break;
2095         case BO_XorAssign:
2096           aop = llvm::AtomicRMWInst::Xor;
2097           break;
2098         case BO_OrAssign:
2099           aop = llvm::AtomicRMWInst::Or;
2100           break;
2101         default:
2102           llvm_unreachable("Invalid compound assignment type");
2103       }
2104       if (aop != llvm::AtomicRMWInst::BAD_BINOP) {
2105         llvm::Value *amt = CGF.EmitToMemory(EmitScalarConversion(OpInfo.RHS,
2106               E->getRHS()->getType(), LHSTy), LHSTy);
2107         Builder.CreateAtomicRMW(aop, LHSLV.getAddress(), amt,
2108             llvm::SequentiallyConsistent);
2109         return LHSLV;
2110       }
2111     }
2112     // FIXME: For floating point types, we should be saving and restoring the
2113     // floating point environment in the loop.
2114     llvm::BasicBlock *startBB = Builder.GetInsertBlock();
2115     llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
2116     OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
2117     OpInfo.LHS = CGF.EmitToMemory(OpInfo.LHS, type);
2118     Builder.CreateBr(opBB);
2119     Builder.SetInsertPoint(opBB);
2120     atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2);
2121     atomicPHI->addIncoming(OpInfo.LHS, startBB);
2122     OpInfo.LHS = atomicPHI;
2123   }
2124   else
2125     OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
2126 
2127   OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
2128                                     E->getComputationLHSType());
2129 
2130   // Expand the binary operator.
2131   Result = (this->*Func)(OpInfo);
2132 
2133   // Convert the result back to the LHS type.
2134   Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
2135 
2136   if (atomicPHI) {
2137     llvm::BasicBlock *opBB = Builder.GetInsertBlock();
2138     llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
2139     auto Pair = CGF.EmitAtomicCompareExchange(
2140         LHSLV, RValue::get(atomicPHI),
2141         RValue::get(CGF.EmitToMemory(Result, LHSTy)), E->getExprLoc());
2142     llvm::Value *old = Pair.first.getScalarVal();
2143     llvm::Value *success = Pair.second.getScalarVal();
2144     atomicPHI->addIncoming(old, opBB);
2145     Builder.CreateCondBr(success, contBB, opBB);
2146     Builder.SetInsertPoint(contBB);
2147     return LHSLV;
2148   }
2149 
2150   // Store the result value into the LHS lvalue. Bit-fields are handled
2151   // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
2152   // 'An assignment expression has the value of the left operand after the
2153   // assignment...'.
2154   if (LHSLV.isBitField())
2155     CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
2156   else
2157     CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
2158 
2159   return LHSLV;
2160 }
2161 
2162 Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
2163                       Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
2164   bool Ignore = TestAndClearIgnoreResultAssign();
2165   Value *RHS;
2166   LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
2167 
2168   // If the result is clearly ignored, return now.
2169   if (Ignore)
2170     return nullptr;
2171 
2172   // The result of an assignment in C is the assigned r-value.
2173   if (!CGF.getLangOpts().CPlusPlus)
2174     return RHS;
2175 
2176   // If the lvalue is non-volatile, return the computed value of the assignment.
2177   if (!LHS.isVolatileQualified())
2178     return RHS;
2179 
2180   // Otherwise, reload the value.
2181   return EmitLoadOfLValue(LHS, E->getExprLoc());
2182 }
2183 
2184 void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
2185     const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) {
2186   SmallVector<std::pair<llvm::Value *, SanitizerKind>, 2> Checks;
2187 
2188   if (CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero)) {
2189     Checks.push_back(std::make_pair(Builder.CreateICmpNE(Ops.RHS, Zero),
2190                                     SanitizerKind::IntegerDivideByZero));
2191   }
2192 
2193   if (CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow) &&
2194       Ops.Ty->hasSignedIntegerRepresentation()) {
2195     llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
2196 
2197     llvm::Value *IntMin =
2198       Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
2199     llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
2200 
2201     llvm::Value *LHSCmp = Builder.CreateICmpNE(Ops.LHS, IntMin);
2202     llvm::Value *RHSCmp = Builder.CreateICmpNE(Ops.RHS, NegOne);
2203     llvm::Value *NotOverflow = Builder.CreateOr(LHSCmp, RHSCmp, "or");
2204     Checks.push_back(
2205         std::make_pair(NotOverflow, SanitizerKind::SignedIntegerOverflow));
2206   }
2207 
2208   if (Checks.size() > 0)
2209     EmitBinOpCheck(Checks, Ops);
2210 }
2211 
2212 Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
2213   {
2214     CodeGenFunction::SanitizerScope SanScope(&CGF);
2215     if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) ||
2216          CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) &&
2217         Ops.Ty->isIntegerType()) {
2218       llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
2219       EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
2220     } else if (CGF.SanOpts.has(SanitizerKind::FloatDivideByZero) &&
2221                Ops.Ty->isRealFloatingType()) {
2222       llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
2223       llvm::Value *NonZero = Builder.CreateFCmpUNE(Ops.RHS, Zero);
2224       EmitBinOpCheck(std::make_pair(NonZero, SanitizerKind::FloatDivideByZero),
2225                      Ops);
2226     }
2227   }
2228 
2229   if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
2230     llvm::Value *Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
2231     if (CGF.getLangOpts().OpenCL) {
2232       // OpenCL 1.1 7.4: minimum accuracy of single precision / is 2.5ulp
2233       llvm::Type *ValTy = Val->getType();
2234       if (ValTy->isFloatTy() ||
2235           (isa<llvm::VectorType>(ValTy) &&
2236            cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy()))
2237         CGF.SetFPAccuracy(Val, 2.5);
2238     }
2239     return Val;
2240   }
2241   else if (Ops.Ty->hasUnsignedIntegerRepresentation())
2242     return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
2243   else
2244     return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
2245 }
2246 
2247 Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
2248   // Rem in C can't be a floating point type: C99 6.5.5p2.
2249   if (CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero)) {
2250     CodeGenFunction::SanitizerScope SanScope(&CGF);
2251     llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
2252 
2253     if (Ops.Ty->isIntegerType())
2254       EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
2255   }
2256 
2257   if (Ops.Ty->hasUnsignedIntegerRepresentation())
2258     return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
2259   else
2260     return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
2261 }
2262 
2263 Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
2264   unsigned IID;
2265   unsigned OpID = 0;
2266 
2267   bool isSigned = Ops.Ty->isSignedIntegerOrEnumerationType();
2268   switch (Ops.Opcode) {
2269   case BO_Add:
2270   case BO_AddAssign:
2271     OpID = 1;
2272     IID = isSigned ? llvm::Intrinsic::sadd_with_overflow :
2273                      llvm::Intrinsic::uadd_with_overflow;
2274     break;
2275   case BO_Sub:
2276   case BO_SubAssign:
2277     OpID = 2;
2278     IID = isSigned ? llvm::Intrinsic::ssub_with_overflow :
2279                      llvm::Intrinsic::usub_with_overflow;
2280     break;
2281   case BO_Mul:
2282   case BO_MulAssign:
2283     OpID = 3;
2284     IID = isSigned ? llvm::Intrinsic::smul_with_overflow :
2285                      llvm::Intrinsic::umul_with_overflow;
2286     break;
2287   default:
2288     llvm_unreachable("Unsupported operation for overflow detection");
2289   }
2290   OpID <<= 1;
2291   if (isSigned)
2292     OpID |= 1;
2293 
2294   llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
2295 
2296   llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
2297 
2298   Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
2299   Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
2300   Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
2301 
2302   // Handle overflow with llvm.trap if no custom handler has been specified.
2303   const std::string *handlerName =
2304     &CGF.getLangOpts().OverflowHandler;
2305   if (handlerName->empty()) {
2306     // If the signed-integer-overflow sanitizer is enabled, emit a call to its
2307     // runtime. Otherwise, this is a -ftrapv check, so just emit a trap.
2308     if (!isSigned || CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) {
2309       CodeGenFunction::SanitizerScope SanScope(&CGF);
2310       llvm::Value *NotOverflow = Builder.CreateNot(overflow);
2311       SanitizerKind Kind = isSigned ? SanitizerKind::SignedIntegerOverflow
2312                               : SanitizerKind::UnsignedIntegerOverflow;
2313       EmitBinOpCheck(std::make_pair(NotOverflow, Kind), Ops);
2314     } else
2315       CGF.EmitTrapCheck(Builder.CreateNot(overflow));
2316     return result;
2317   }
2318 
2319   // Branch in case of overflow.
2320   llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
2321   llvm::Function::iterator insertPt = initialBB;
2322   llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn,
2323                                                       std::next(insertPt));
2324   llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
2325 
2326   Builder.CreateCondBr(overflow, overflowBB, continueBB);
2327 
2328   // If an overflow handler is set, then we want to call it and then use its
2329   // result, if it returns.
2330   Builder.SetInsertPoint(overflowBB);
2331 
2332   // Get the overflow handler.
2333   llvm::Type *Int8Ty = CGF.Int8Ty;
2334   llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
2335   llvm::FunctionType *handlerTy =
2336       llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
2337   llvm::Value *handler = CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
2338 
2339   // Sign extend the args to 64-bit, so that we can use the same handler for
2340   // all types of overflow.
2341   llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
2342   llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
2343 
2344   // Call the handler with the two arguments, the operation, and the size of
2345   // the result.
2346   llvm::Value *handlerArgs[] = {
2347     lhs,
2348     rhs,
2349     Builder.getInt8(OpID),
2350     Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth())
2351   };
2352   llvm::Value *handlerResult =
2353     CGF.EmitNounwindRuntimeCall(handler, handlerArgs);
2354 
2355   // Truncate the result back to the desired size.
2356   handlerResult = Builder.CreateTrunc(handlerResult, opTy);
2357   Builder.CreateBr(continueBB);
2358 
2359   Builder.SetInsertPoint(continueBB);
2360   llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
2361   phi->addIncoming(result, initialBB);
2362   phi->addIncoming(handlerResult, overflowBB);
2363 
2364   return phi;
2365 }
2366 
2367 /// Emit pointer + index arithmetic.
2368 static Value *emitPointerArithmetic(CodeGenFunction &CGF,
2369                                     const BinOpInfo &op,
2370                                     bool isSubtraction) {
2371   // Must have binary (not unary) expr here.  Unary pointer
2372   // increment/decrement doesn't use this path.
2373   const BinaryOperator *expr = cast<BinaryOperator>(op.E);
2374 
2375   Value *pointer = op.LHS;
2376   Expr *pointerOperand = expr->getLHS();
2377   Value *index = op.RHS;
2378   Expr *indexOperand = expr->getRHS();
2379 
2380   // In a subtraction, the LHS is always the pointer.
2381   if (!isSubtraction && !pointer->getType()->isPointerTy()) {
2382     std::swap(pointer, index);
2383     std::swap(pointerOperand, indexOperand);
2384   }
2385 
2386   unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
2387   if (width != CGF.PointerWidthInBits) {
2388     // Zero-extend or sign-extend the pointer value according to
2389     // whether the index is signed or not.
2390     bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
2391     index = CGF.Builder.CreateIntCast(index, CGF.PtrDiffTy, isSigned,
2392                                       "idx.ext");
2393   }
2394 
2395   // If this is subtraction, negate the index.
2396   if (isSubtraction)
2397     index = CGF.Builder.CreateNeg(index, "idx.neg");
2398 
2399   if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
2400     CGF.EmitBoundsCheck(op.E, pointerOperand, index, indexOperand->getType(),
2401                         /*Accessed*/ false);
2402 
2403   const PointerType *pointerType
2404     = pointerOperand->getType()->getAs<PointerType>();
2405   if (!pointerType) {
2406     QualType objectType = pointerOperand->getType()
2407                                         ->castAs<ObjCObjectPointerType>()
2408                                         ->getPointeeType();
2409     llvm::Value *objectSize
2410       = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
2411 
2412     index = CGF.Builder.CreateMul(index, objectSize);
2413 
2414     Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
2415     result = CGF.Builder.CreateGEP(result, index, "add.ptr");
2416     return CGF.Builder.CreateBitCast(result, pointer->getType());
2417   }
2418 
2419   QualType elementType = pointerType->getPointeeType();
2420   if (const VariableArrayType *vla
2421         = CGF.getContext().getAsVariableArrayType(elementType)) {
2422     // The element count here is the total number of non-VLA elements.
2423     llvm::Value *numElements = CGF.getVLASize(vla).first;
2424 
2425     // Effectively, the multiply by the VLA size is part of the GEP.
2426     // GEP indexes are signed, and scaling an index isn't permitted to
2427     // signed-overflow, so we use the same semantics for our explicit
2428     // multiply.  We suppress this if overflow is not undefined behavior.
2429     if (CGF.getLangOpts().isSignedOverflowDefined()) {
2430       index = CGF.Builder.CreateMul(index, numElements, "vla.index");
2431       pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr");
2432     } else {
2433       index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
2434       pointer = CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
2435     }
2436     return pointer;
2437   }
2438 
2439   // Explicitly handle GNU void* and function pointer arithmetic extensions. The
2440   // GNU void* casts amount to no-ops since our void* type is i8*, but this is
2441   // future proof.
2442   if (elementType->isVoidType() || elementType->isFunctionType()) {
2443     Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
2444     result = CGF.Builder.CreateGEP(result, index, "add.ptr");
2445     return CGF.Builder.CreateBitCast(result, pointer->getType());
2446   }
2447 
2448   if (CGF.getLangOpts().isSignedOverflowDefined())
2449     return CGF.Builder.CreateGEP(pointer, index, "add.ptr");
2450 
2451   return CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
2452 }
2453 
2454 // Construct an fmuladd intrinsic to represent a fused mul-add of MulOp and
2455 // Addend. Use negMul and negAdd to negate the first operand of the Mul or
2456 // the add operand respectively. This allows fmuladd to represent a*b-c, or
2457 // c-a*b. Patterns in LLVM should catch the negated forms and translate them to
2458 // efficient operations.
2459 static Value* buildFMulAdd(llvm::BinaryOperator *MulOp, Value *Addend,
2460                            const CodeGenFunction &CGF, CGBuilderTy &Builder,
2461                            bool negMul, bool negAdd) {
2462   assert(!(negMul && negAdd) && "Only one of negMul and negAdd should be set.");
2463 
2464   Value *MulOp0 = MulOp->getOperand(0);
2465   Value *MulOp1 = MulOp->getOperand(1);
2466   if (negMul) {
2467     MulOp0 =
2468       Builder.CreateFSub(
2469         llvm::ConstantFP::getZeroValueForNegation(MulOp0->getType()), MulOp0,
2470         "neg");
2471   } else if (negAdd) {
2472     Addend =
2473       Builder.CreateFSub(
2474         llvm::ConstantFP::getZeroValueForNegation(Addend->getType()), Addend,
2475         "neg");
2476   }
2477 
2478   Value *FMulAdd =
2479     Builder.CreateCall3(
2480       CGF.CGM.getIntrinsic(llvm::Intrinsic::fmuladd, Addend->getType()),
2481                            MulOp0, MulOp1, Addend);
2482    MulOp->eraseFromParent();
2483 
2484    return FMulAdd;
2485 }
2486 
2487 // Check whether it would be legal to emit an fmuladd intrinsic call to
2488 // represent op and if so, build the fmuladd.
2489 //
2490 // Checks that (a) the operation is fusable, and (b) -ffp-contract=on.
2491 // Does NOT check the type of the operation - it's assumed that this function
2492 // will be called from contexts where it's known that the type is contractable.
2493 static Value* tryEmitFMulAdd(const BinOpInfo &op,
2494                          const CodeGenFunction &CGF, CGBuilderTy &Builder,
2495                          bool isSub=false) {
2496 
2497   assert((op.Opcode == BO_Add || op.Opcode == BO_AddAssign ||
2498           op.Opcode == BO_Sub || op.Opcode == BO_SubAssign) &&
2499          "Only fadd/fsub can be the root of an fmuladd.");
2500 
2501   // Check whether this op is marked as fusable.
2502   if (!op.FPContractable)
2503     return nullptr;
2504 
2505   // Check whether -ffp-contract=on. (If -ffp-contract=off/fast, fusing is
2506   // either disabled, or handled entirely by the LLVM backend).
2507   if (CGF.CGM.getCodeGenOpts().getFPContractMode() != CodeGenOptions::FPC_On)
2508     return nullptr;
2509 
2510   // We have a potentially fusable op. Look for a mul on one of the operands.
2511   if (llvm::BinaryOperator* LHSBinOp = dyn_cast<llvm::BinaryOperator>(op.LHS)) {
2512     if (LHSBinOp->getOpcode() == llvm::Instruction::FMul) {
2513       assert(LHSBinOp->getNumUses() == 0 &&
2514              "Operations with multiple uses shouldn't be contracted.");
2515       return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub);
2516     }
2517   } else if (llvm::BinaryOperator* RHSBinOp =
2518                dyn_cast<llvm::BinaryOperator>(op.RHS)) {
2519     if (RHSBinOp->getOpcode() == llvm::Instruction::FMul) {
2520       assert(RHSBinOp->getNumUses() == 0 &&
2521              "Operations with multiple uses shouldn't be contracted.");
2522       return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false);
2523     }
2524   }
2525 
2526   return nullptr;
2527 }
2528 
2529 Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
2530   if (op.LHS->getType()->isPointerTy() ||
2531       op.RHS->getType()->isPointerTy())
2532     return emitPointerArithmetic(CGF, op, /*subtraction*/ false);
2533 
2534   if (op.Ty->isSignedIntegerOrEnumerationType()) {
2535     switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
2536     case LangOptions::SOB_Defined:
2537       return Builder.CreateAdd(op.LHS, op.RHS, "add");
2538     case LangOptions::SOB_Undefined:
2539       if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
2540         return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
2541       // Fall through.
2542     case LangOptions::SOB_Trapping:
2543       return EmitOverflowCheckedBinOp(op);
2544     }
2545   }
2546 
2547   if (op.Ty->isUnsignedIntegerType() &&
2548       CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow))
2549     return EmitOverflowCheckedBinOp(op);
2550 
2551   if (op.LHS->getType()->isFPOrFPVectorTy()) {
2552     // Try to form an fmuladd.
2553     if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder))
2554       return FMulAdd;
2555 
2556     return Builder.CreateFAdd(op.LHS, op.RHS, "add");
2557   }
2558 
2559   return Builder.CreateAdd(op.LHS, op.RHS, "add");
2560 }
2561 
2562 Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
2563   // The LHS is always a pointer if either side is.
2564   if (!op.LHS->getType()->isPointerTy()) {
2565     if (op.Ty->isSignedIntegerOrEnumerationType()) {
2566       switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
2567       case LangOptions::SOB_Defined:
2568         return Builder.CreateSub(op.LHS, op.RHS, "sub");
2569       case LangOptions::SOB_Undefined:
2570         if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
2571           return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
2572         // Fall through.
2573       case LangOptions::SOB_Trapping:
2574         return EmitOverflowCheckedBinOp(op);
2575       }
2576     }
2577 
2578     if (op.Ty->isUnsignedIntegerType() &&
2579         CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow))
2580       return EmitOverflowCheckedBinOp(op);
2581 
2582     if (op.LHS->getType()->isFPOrFPVectorTy()) {
2583       // Try to form an fmuladd.
2584       if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder, true))
2585         return FMulAdd;
2586       return Builder.CreateFSub(op.LHS, op.RHS, "sub");
2587     }
2588 
2589     return Builder.CreateSub(op.LHS, op.RHS, "sub");
2590   }
2591 
2592   // If the RHS is not a pointer, then we have normal pointer
2593   // arithmetic.
2594   if (!op.RHS->getType()->isPointerTy())
2595     return emitPointerArithmetic(CGF, op, /*subtraction*/ true);
2596 
2597   // Otherwise, this is a pointer subtraction.
2598 
2599   // Do the raw subtraction part.
2600   llvm::Value *LHS
2601     = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
2602   llvm::Value *RHS
2603     = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
2604   Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
2605 
2606   // Okay, figure out the element size.
2607   const BinaryOperator *expr = cast<BinaryOperator>(op.E);
2608   QualType elementType = expr->getLHS()->getType()->getPointeeType();
2609 
2610   llvm::Value *divisor = nullptr;
2611 
2612   // For a variable-length array, this is going to be non-constant.
2613   if (const VariableArrayType *vla
2614         = CGF.getContext().getAsVariableArrayType(elementType)) {
2615     llvm::Value *numElements;
2616     std::tie(numElements, elementType) = CGF.getVLASize(vla);
2617 
2618     divisor = numElements;
2619 
2620     // Scale the number of non-VLA elements by the non-VLA element size.
2621     CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
2622     if (!eltSize.isOne())
2623       divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
2624 
2625   // For everything elese, we can just compute it, safe in the
2626   // assumption that Sema won't let anything through that we can't
2627   // safely compute the size of.
2628   } else {
2629     CharUnits elementSize;
2630     // Handle GCC extension for pointer arithmetic on void* and
2631     // function pointer types.
2632     if (elementType->isVoidType() || elementType->isFunctionType())
2633       elementSize = CharUnits::One();
2634     else
2635       elementSize = CGF.getContext().getTypeSizeInChars(elementType);
2636 
2637     // Don't even emit the divide for element size of 1.
2638     if (elementSize.isOne())
2639       return diffInChars;
2640 
2641     divisor = CGF.CGM.getSize(elementSize);
2642   }
2643 
2644   // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
2645   // pointer difference in C is only defined in the case where both operands
2646   // are pointing to elements of an array.
2647   return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
2648 }
2649 
2650 Value *ScalarExprEmitter::GetWidthMinusOneValue(Value* LHS,Value* RHS) {
2651   llvm::IntegerType *Ty;
2652   if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(LHS->getType()))
2653     Ty = cast<llvm::IntegerType>(VT->getElementType());
2654   else
2655     Ty = cast<llvm::IntegerType>(LHS->getType());
2656   return llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth() - 1);
2657 }
2658 
2659 Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
2660   // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2661   // RHS to the same size as the LHS.
2662   Value *RHS = Ops.RHS;
2663   if (Ops.LHS->getType() != RHS->getType())
2664     RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
2665 
2666   if (CGF.SanOpts.has(SanitizerKind::Shift) && !CGF.getLangOpts().OpenCL &&
2667       isa<llvm::IntegerType>(Ops.LHS->getType())) {
2668     CodeGenFunction::SanitizerScope SanScope(&CGF);
2669     llvm::Value *WidthMinusOne = GetWidthMinusOneValue(Ops.LHS, RHS);
2670     llvm::Value *Valid = Builder.CreateICmpULE(RHS, WidthMinusOne);
2671 
2672     if (Ops.Ty->hasSignedIntegerRepresentation()) {
2673       llvm::BasicBlock *Orig = Builder.GetInsertBlock();
2674       llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
2675       llvm::BasicBlock *CheckBitsShifted = CGF.createBasicBlock("check");
2676       Builder.CreateCondBr(Valid, CheckBitsShifted, Cont);
2677 
2678       // Check whether we are shifting any non-zero bits off the top of the
2679       // integer.
2680       CGF.EmitBlock(CheckBitsShifted);
2681       llvm::Value *BitsShiftedOff =
2682         Builder.CreateLShr(Ops.LHS,
2683                            Builder.CreateSub(WidthMinusOne, RHS, "shl.zeros",
2684                                              /*NUW*/true, /*NSW*/true),
2685                            "shl.check");
2686       if (CGF.getLangOpts().CPlusPlus) {
2687         // In C99, we are not permitted to shift a 1 bit into the sign bit.
2688         // Under C++11's rules, shifting a 1 bit into the sign bit is
2689         // OK, but shifting a 1 bit out of it is not. (C89 and C++03 don't
2690         // define signed left shifts, so we use the C99 and C++11 rules there).
2691         llvm::Value *One = llvm::ConstantInt::get(BitsShiftedOff->getType(), 1);
2692         BitsShiftedOff = Builder.CreateLShr(BitsShiftedOff, One);
2693       }
2694       llvm::Value *Zero = llvm::ConstantInt::get(BitsShiftedOff->getType(), 0);
2695       llvm::Value *SecondCheck = Builder.CreateICmpEQ(BitsShiftedOff, Zero);
2696       CGF.EmitBlock(Cont);
2697       llvm::PHINode *P = Builder.CreatePHI(Valid->getType(), 2);
2698       P->addIncoming(Valid, Orig);
2699       P->addIncoming(SecondCheck, CheckBitsShifted);
2700       Valid = P;
2701     }
2702 
2703     EmitBinOpCheck(std::make_pair(Valid, SanitizerKind::Shift), Ops);
2704   }
2705   // OpenCL 6.3j: shift values are effectively % word size of LHS.
2706   if (CGF.getLangOpts().OpenCL)
2707     RHS = Builder.CreateAnd(RHS, GetWidthMinusOneValue(Ops.LHS, RHS), "shl.mask");
2708 
2709   return Builder.CreateShl(Ops.LHS, RHS, "shl");
2710 }
2711 
2712 Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
2713   // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2714   // RHS to the same size as the LHS.
2715   Value *RHS = Ops.RHS;
2716   if (Ops.LHS->getType() != RHS->getType())
2717     RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
2718 
2719   if (CGF.SanOpts.has(SanitizerKind::Shift) && !CGF.getLangOpts().OpenCL &&
2720       isa<llvm::IntegerType>(Ops.LHS->getType())) {
2721     CodeGenFunction::SanitizerScope SanScope(&CGF);
2722     llvm::Value *Valid =
2723         Builder.CreateICmpULE(RHS, GetWidthMinusOneValue(Ops.LHS, RHS));
2724     EmitBinOpCheck(std::make_pair(Valid, SanitizerKind::Shift), Ops);
2725   }
2726 
2727   // OpenCL 6.3j: shift values are effectively % word size of LHS.
2728   if (CGF.getLangOpts().OpenCL)
2729     RHS = Builder.CreateAnd(RHS, GetWidthMinusOneValue(Ops.LHS, RHS), "shr.mask");
2730 
2731   if (Ops.Ty->hasUnsignedIntegerRepresentation())
2732     return Builder.CreateLShr(Ops.LHS, RHS, "shr");
2733   return Builder.CreateAShr(Ops.LHS, RHS, "shr");
2734 }
2735 
2736 enum IntrinsicType { VCMPEQ, VCMPGT };
2737 // return corresponding comparison intrinsic for given vector type
2738 static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
2739                                         BuiltinType::Kind ElemKind) {
2740   switch (ElemKind) {
2741   default: llvm_unreachable("unexpected element type");
2742   case BuiltinType::Char_U:
2743   case BuiltinType::UChar:
2744     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2745                             llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
2746   case BuiltinType::Char_S:
2747   case BuiltinType::SChar:
2748     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2749                             llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
2750   case BuiltinType::UShort:
2751     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2752                             llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
2753   case BuiltinType::Short:
2754     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2755                             llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
2756   case BuiltinType::UInt:
2757   case BuiltinType::ULong:
2758     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2759                             llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
2760   case BuiltinType::Int:
2761   case BuiltinType::Long:
2762     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2763                             llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
2764   case BuiltinType::Float:
2765     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
2766                             llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
2767   }
2768 }
2769 
2770 Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
2771                                       unsigned SICmpOpc, unsigned FCmpOpc) {
2772   TestAndClearIgnoreResultAssign();
2773   Value *Result;
2774   QualType LHSTy = E->getLHS()->getType();
2775   QualType RHSTy = E->getRHS()->getType();
2776   if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
2777     assert(E->getOpcode() == BO_EQ ||
2778            E->getOpcode() == BO_NE);
2779     Value *LHS = CGF.EmitScalarExpr(E->getLHS());
2780     Value *RHS = CGF.EmitScalarExpr(E->getRHS());
2781     Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
2782                    CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
2783   } else if (!LHSTy->isAnyComplexType() && !RHSTy->isAnyComplexType()) {
2784     Value *LHS = Visit(E->getLHS());
2785     Value *RHS = Visit(E->getRHS());
2786 
2787     // If AltiVec, the comparison results in a numeric type, so we use
2788     // intrinsics comparing vectors and giving 0 or 1 as a result
2789     if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
2790       // constants for mapping CR6 register bits to predicate result
2791       enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
2792 
2793       llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
2794 
2795       // in several cases vector arguments order will be reversed
2796       Value *FirstVecArg = LHS,
2797             *SecondVecArg = RHS;
2798 
2799       QualType ElTy = LHSTy->getAs<VectorType>()->getElementType();
2800       const BuiltinType *BTy = ElTy->getAs<BuiltinType>();
2801       BuiltinType::Kind ElementKind = BTy->getKind();
2802 
2803       switch(E->getOpcode()) {
2804       default: llvm_unreachable("is not a comparison operation");
2805       case BO_EQ:
2806         CR6 = CR6_LT;
2807         ID = GetIntrinsic(VCMPEQ, ElementKind);
2808         break;
2809       case BO_NE:
2810         CR6 = CR6_EQ;
2811         ID = GetIntrinsic(VCMPEQ, ElementKind);
2812         break;
2813       case BO_LT:
2814         CR6 = CR6_LT;
2815         ID = GetIntrinsic(VCMPGT, ElementKind);
2816         std::swap(FirstVecArg, SecondVecArg);
2817         break;
2818       case BO_GT:
2819         CR6 = CR6_LT;
2820         ID = GetIntrinsic(VCMPGT, ElementKind);
2821         break;
2822       case BO_LE:
2823         if (ElementKind == BuiltinType::Float) {
2824           CR6 = CR6_LT;
2825           ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2826           std::swap(FirstVecArg, SecondVecArg);
2827         }
2828         else {
2829           CR6 = CR6_EQ;
2830           ID = GetIntrinsic(VCMPGT, ElementKind);
2831         }
2832         break;
2833       case BO_GE:
2834         if (ElementKind == BuiltinType::Float) {
2835           CR6 = CR6_LT;
2836           ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2837         }
2838         else {
2839           CR6 = CR6_EQ;
2840           ID = GetIntrinsic(VCMPGT, ElementKind);
2841           std::swap(FirstVecArg, SecondVecArg);
2842         }
2843         break;
2844       }
2845 
2846       Value *CR6Param = Builder.getInt32(CR6);
2847       llvm::Function *F = CGF.CGM.getIntrinsic(ID);
2848       Result = Builder.CreateCall3(F, CR6Param, FirstVecArg, SecondVecArg, "");
2849       return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
2850     }
2851 
2852     if (LHS->getType()->isFPOrFPVectorTy()) {
2853       Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
2854                                   LHS, RHS, "cmp");
2855     } else if (LHSTy->hasSignedIntegerRepresentation()) {
2856       Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
2857                                   LHS, RHS, "cmp");
2858     } else {
2859       // Unsigned integers and pointers.
2860       Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2861                                   LHS, RHS, "cmp");
2862     }
2863 
2864     // If this is a vector comparison, sign extend the result to the appropriate
2865     // vector integer type and return it (don't convert to bool).
2866     if (LHSTy->isVectorType())
2867       return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
2868 
2869   } else {
2870     // Complex Comparison: can only be an equality comparison.
2871     CodeGenFunction::ComplexPairTy LHS, RHS;
2872     QualType CETy;
2873     if (auto *CTy = LHSTy->getAs<ComplexType>()) {
2874       LHS = CGF.EmitComplexExpr(E->getLHS());
2875       CETy = CTy->getElementType();
2876     } else {
2877       LHS.first = Visit(E->getLHS());
2878       LHS.second = llvm::Constant::getNullValue(LHS.first->getType());
2879       CETy = LHSTy;
2880     }
2881     if (auto *CTy = RHSTy->getAs<ComplexType>()) {
2882       RHS = CGF.EmitComplexExpr(E->getRHS());
2883       assert(CGF.getContext().hasSameUnqualifiedType(CETy,
2884                                                      CTy->getElementType()) &&
2885              "The element types must always match.");
2886       (void)CTy;
2887     } else {
2888       RHS.first = Visit(E->getRHS());
2889       RHS.second = llvm::Constant::getNullValue(RHS.first->getType());
2890       assert(CGF.getContext().hasSameUnqualifiedType(CETy, RHSTy) &&
2891              "The element types must always match.");
2892     }
2893 
2894     Value *ResultR, *ResultI;
2895     if (CETy->isRealFloatingType()) {
2896       ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2897                                    LHS.first, RHS.first, "cmp.r");
2898       ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2899                                    LHS.second, RHS.second, "cmp.i");
2900     } else {
2901       // Complex comparisons can only be equality comparisons.  As such, signed
2902       // and unsigned opcodes are the same.
2903       ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2904                                    LHS.first, RHS.first, "cmp.r");
2905       ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2906                                    LHS.second, RHS.second, "cmp.i");
2907     }
2908 
2909     if (E->getOpcode() == BO_EQ) {
2910       Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
2911     } else {
2912       assert(E->getOpcode() == BO_NE &&
2913              "Complex comparison other than == or != ?");
2914       Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
2915     }
2916   }
2917 
2918   return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
2919 }
2920 
2921 Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
2922   bool Ignore = TestAndClearIgnoreResultAssign();
2923 
2924   Value *RHS;
2925   LValue LHS;
2926 
2927   switch (E->getLHS()->getType().getObjCLifetime()) {
2928   case Qualifiers::OCL_Strong:
2929     std::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
2930     break;
2931 
2932   case Qualifiers::OCL_Autoreleasing:
2933     std::tie(LHS, RHS) = CGF.EmitARCStoreAutoreleasing(E);
2934     break;
2935 
2936   case Qualifiers::OCL_Weak:
2937     RHS = Visit(E->getRHS());
2938     LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
2939     RHS = CGF.EmitARCStoreWeak(LHS.getAddress(), RHS, Ignore);
2940     break;
2941 
2942   // No reason to do any of these differently.
2943   case Qualifiers::OCL_None:
2944   case Qualifiers::OCL_ExplicitNone:
2945     // __block variables need to have the rhs evaluated first, plus
2946     // this should improve codegen just a little.
2947     RHS = Visit(E->getRHS());
2948     LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
2949 
2950     // Store the value into the LHS.  Bit-fields are handled specially
2951     // because the result is altered by the store, i.e., [C99 6.5.16p1]
2952     // 'An assignment expression has the value of the left operand after
2953     // the assignment...'.
2954     if (LHS.isBitField())
2955       CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
2956     else
2957       CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
2958   }
2959 
2960   // If the result is clearly ignored, return now.
2961   if (Ignore)
2962     return nullptr;
2963 
2964   // The result of an assignment in C is the assigned r-value.
2965   if (!CGF.getLangOpts().CPlusPlus)
2966     return RHS;
2967 
2968   // If the lvalue is non-volatile, return the computed value of the assignment.
2969   if (!LHS.isVolatileQualified())
2970     return RHS;
2971 
2972   // Otherwise, reload the value.
2973   return EmitLoadOfLValue(LHS, E->getExprLoc());
2974 }
2975 
2976 Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
2977   RegionCounter Cnt = CGF.getPGORegionCounter(E);
2978 
2979   // Perform vector logical and on comparisons with zero vectors.
2980   if (E->getType()->isVectorType()) {
2981     Cnt.beginRegion(Builder);
2982 
2983     Value *LHS = Visit(E->getLHS());
2984     Value *RHS = Visit(E->getRHS());
2985     Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
2986     if (LHS->getType()->isFPOrFPVectorTy()) {
2987       LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
2988       RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
2989     } else {
2990       LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
2991       RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
2992     }
2993     Value *And = Builder.CreateAnd(LHS, RHS);
2994     return Builder.CreateSExt(And, ConvertType(E->getType()), "sext");
2995   }
2996 
2997   llvm::Type *ResTy = ConvertType(E->getType());
2998 
2999   // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
3000   // If we have 1 && X, just emit X without inserting the control flow.
3001   bool LHSCondVal;
3002   if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
3003     if (LHSCondVal) { // If we have 1 && X, just emit X.
3004       Cnt.beginRegion(Builder);
3005 
3006       Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
3007       // ZExt result to int or bool.
3008       return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
3009     }
3010 
3011     // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
3012     if (!CGF.ContainsLabel(E->getRHS()))
3013       return llvm::Constant::getNullValue(ResTy);
3014   }
3015 
3016   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
3017   llvm::BasicBlock *RHSBlock  = CGF.createBasicBlock("land.rhs");
3018 
3019   CodeGenFunction::ConditionalEvaluation eval(CGF);
3020 
3021   // Branch on the LHS first.  If it is false, go to the failure (cont) block.
3022   CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock, Cnt.getCount());
3023 
3024   // Any edges into the ContBlock are now from an (indeterminate number of)
3025   // edges from this first condition.  All of these values will be false.  Start
3026   // setting up the PHI node in the Cont Block for this.
3027   llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
3028                                             "", ContBlock);
3029   for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
3030        PI != PE; ++PI)
3031     PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
3032 
3033   eval.begin(CGF);
3034   CGF.EmitBlock(RHSBlock);
3035   Cnt.beginRegion(Builder);
3036   Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
3037   eval.end(CGF);
3038 
3039   // Reaquire the RHS block, as there may be subblocks inserted.
3040   RHSBlock = Builder.GetInsertBlock();
3041 
3042   // Emit an unconditional branch from this block to ContBlock.
3043   {
3044     // There is no need to emit line number for unconditional branch.
3045     SuppressDebugLocation S(Builder);
3046     CGF.EmitBlock(ContBlock);
3047   }
3048   // Insert an entry into the phi node for the edge with the value of RHSCond.
3049   PN->addIncoming(RHSCond, RHSBlock);
3050 
3051   // ZExt result to int.
3052   return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
3053 }
3054 
3055 Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
3056   RegionCounter Cnt = CGF.getPGORegionCounter(E);
3057 
3058   // Perform vector logical or on comparisons with zero vectors.
3059   if (E->getType()->isVectorType()) {
3060     Cnt.beginRegion(Builder);
3061 
3062     Value *LHS = Visit(E->getLHS());
3063     Value *RHS = Visit(E->getRHS());
3064     Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
3065     if (LHS->getType()->isFPOrFPVectorTy()) {
3066       LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
3067       RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
3068     } else {
3069       LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
3070       RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
3071     }
3072     Value *Or = Builder.CreateOr(LHS, RHS);
3073     return Builder.CreateSExt(Or, ConvertType(E->getType()), "sext");
3074   }
3075 
3076   llvm::Type *ResTy = ConvertType(E->getType());
3077 
3078   // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
3079   // If we have 0 || X, just emit X without inserting the control flow.
3080   bool LHSCondVal;
3081   if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
3082     if (!LHSCondVal) { // If we have 0 || X, just emit X.
3083       Cnt.beginRegion(Builder);
3084 
3085       Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
3086       // ZExt result to int or bool.
3087       return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
3088     }
3089 
3090     // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
3091     if (!CGF.ContainsLabel(E->getRHS()))
3092       return llvm::ConstantInt::get(ResTy, 1);
3093   }
3094 
3095   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
3096   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
3097 
3098   CodeGenFunction::ConditionalEvaluation eval(CGF);
3099 
3100   // Branch on the LHS first.  If it is true, go to the success (cont) block.
3101   CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock,
3102                            Cnt.getParentCount() - Cnt.getCount());
3103 
3104   // Any edges into the ContBlock are now from an (indeterminate number of)
3105   // edges from this first condition.  All of these values will be true.  Start
3106   // setting up the PHI node in the Cont Block for this.
3107   llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
3108                                             "", ContBlock);
3109   for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
3110        PI != PE; ++PI)
3111     PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
3112 
3113   eval.begin(CGF);
3114 
3115   // Emit the RHS condition as a bool value.
3116   CGF.EmitBlock(RHSBlock);
3117   Cnt.beginRegion(Builder);
3118   Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
3119 
3120   eval.end(CGF);
3121 
3122   // Reaquire the RHS block, as there may be subblocks inserted.
3123   RHSBlock = Builder.GetInsertBlock();
3124 
3125   // Emit an unconditional branch from this block to ContBlock.  Insert an entry
3126   // into the phi node for the edge with the value of RHSCond.
3127   CGF.EmitBlock(ContBlock);
3128   PN->addIncoming(RHSCond, RHSBlock);
3129 
3130   // ZExt result to int.
3131   return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
3132 }
3133 
3134 Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
3135   CGF.EmitIgnoredExpr(E->getLHS());
3136   CGF.EnsureInsertPoint();
3137   return Visit(E->getRHS());
3138 }
3139 
3140 //===----------------------------------------------------------------------===//
3141 //                             Other Operators
3142 //===----------------------------------------------------------------------===//
3143 
3144 /// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
3145 /// expression is cheap enough and side-effect-free enough to evaluate
3146 /// unconditionally instead of conditionally.  This is used to convert control
3147 /// flow into selects in some cases.
3148 static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
3149                                                    CodeGenFunction &CGF) {
3150   // Anything that is an integer or floating point constant is fine.
3151   return E->IgnoreParens()->isEvaluatable(CGF.getContext());
3152 
3153   // Even non-volatile automatic variables can't be evaluated unconditionally.
3154   // Referencing a thread_local may cause non-trivial initialization work to
3155   // occur. If we're inside a lambda and one of the variables is from the scope
3156   // outside the lambda, that function may have returned already. Reading its
3157   // locals is a bad idea. Also, these reads may introduce races there didn't
3158   // exist in the source-level program.
3159 }
3160 
3161 
3162 Value *ScalarExprEmitter::
3163 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
3164   TestAndClearIgnoreResultAssign();
3165 
3166   // Bind the common expression if necessary.
3167   CodeGenFunction::OpaqueValueMapping binding(CGF, E);
3168   RegionCounter Cnt = CGF.getPGORegionCounter(E);
3169 
3170   Expr *condExpr = E->getCond();
3171   Expr *lhsExpr = E->getTrueExpr();
3172   Expr *rhsExpr = E->getFalseExpr();
3173 
3174   // If the condition constant folds and can be elided, try to avoid emitting
3175   // the condition and the dead arm.
3176   bool CondExprBool;
3177   if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
3178     Expr *live = lhsExpr, *dead = rhsExpr;
3179     if (!CondExprBool) std::swap(live, dead);
3180 
3181     // If the dead side doesn't have labels we need, just emit the Live part.
3182     if (!CGF.ContainsLabel(dead)) {
3183       if (CondExprBool)
3184         Cnt.beginRegion(Builder);
3185       Value *Result = Visit(live);
3186 
3187       // If the live part is a throw expression, it acts like it has a void
3188       // type, so evaluating it returns a null Value*.  However, a conditional
3189       // with non-void type must return a non-null Value*.
3190       if (!Result && !E->getType()->isVoidType())
3191         Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
3192 
3193       return Result;
3194     }
3195   }
3196 
3197   // OpenCL: If the condition is a vector, we can treat this condition like
3198   // the select function.
3199   if (CGF.getLangOpts().OpenCL
3200       && condExpr->getType()->isVectorType()) {
3201     Cnt.beginRegion(Builder);
3202 
3203     llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
3204     llvm::Value *LHS = Visit(lhsExpr);
3205     llvm::Value *RHS = Visit(rhsExpr);
3206 
3207     llvm::Type *condType = ConvertType(condExpr->getType());
3208     llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
3209 
3210     unsigned numElem = vecTy->getNumElements();
3211     llvm::Type *elemType = vecTy->getElementType();
3212 
3213     llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy);
3214     llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
3215     llvm::Value *tmp = Builder.CreateSExt(TestMSB,
3216                                           llvm::VectorType::get(elemType,
3217                                                                 numElem),
3218                                           "sext");
3219     llvm::Value *tmp2 = Builder.CreateNot(tmp);
3220 
3221     // Cast float to int to perform ANDs if necessary.
3222     llvm::Value *RHSTmp = RHS;
3223     llvm::Value *LHSTmp = LHS;
3224     bool wasCast = false;
3225     llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
3226     if (rhsVTy->getElementType()->isFloatingPointTy()) {
3227       RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
3228       LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
3229       wasCast = true;
3230     }
3231 
3232     llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
3233     llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
3234     llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
3235     if (wasCast)
3236       tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
3237 
3238     return tmp5;
3239   }
3240 
3241   // If this is a really simple expression (like x ? 4 : 5), emit this as a
3242   // select instead of as control flow.  We can only do this if it is cheap and
3243   // safe to evaluate the LHS and RHS unconditionally.
3244   if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
3245       isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
3246     Cnt.beginRegion(Builder);
3247 
3248     llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
3249     llvm::Value *LHS = Visit(lhsExpr);
3250     llvm::Value *RHS = Visit(rhsExpr);
3251     if (!LHS) {
3252       // If the conditional has void type, make sure we return a null Value*.
3253       assert(!RHS && "LHS and RHS types must match");
3254       return nullptr;
3255     }
3256     return Builder.CreateSelect(CondV, LHS, RHS, "cond");
3257   }
3258 
3259   llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
3260   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
3261   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
3262 
3263   CodeGenFunction::ConditionalEvaluation eval(CGF);
3264   CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock, Cnt.getCount());
3265 
3266   CGF.EmitBlock(LHSBlock);
3267   Cnt.beginRegion(Builder);
3268   eval.begin(CGF);
3269   Value *LHS = Visit(lhsExpr);
3270   eval.end(CGF);
3271 
3272   LHSBlock = Builder.GetInsertBlock();
3273   Builder.CreateBr(ContBlock);
3274 
3275   CGF.EmitBlock(RHSBlock);
3276   eval.begin(CGF);
3277   Value *RHS = Visit(rhsExpr);
3278   eval.end(CGF);
3279 
3280   RHSBlock = Builder.GetInsertBlock();
3281   CGF.EmitBlock(ContBlock);
3282 
3283   // If the LHS or RHS is a throw expression, it will be legitimately null.
3284   if (!LHS)
3285     return RHS;
3286   if (!RHS)
3287     return LHS;
3288 
3289   // Create a PHI node for the real part.
3290   llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
3291   PN->addIncoming(LHS, LHSBlock);
3292   PN->addIncoming(RHS, RHSBlock);
3293   return PN;
3294 }
3295 
3296 Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
3297   return Visit(E->getChosenSubExpr());
3298 }
3299 
3300 Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
3301   QualType Ty = VE->getType();
3302 
3303   if (Ty->isVariablyModifiedType())
3304     CGF.EmitVariablyModifiedType(Ty);
3305 
3306   llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
3307   llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
3308   llvm::Type *ArgTy = ConvertType(VE->getType());
3309 
3310   // If EmitVAArg fails, we fall back to the LLVM instruction.
3311   if (!ArgPtr)
3312     return Builder.CreateVAArg(ArgValue, ArgTy);
3313 
3314   // FIXME Volatility.
3315   llvm::Value *Val = Builder.CreateLoad(ArgPtr);
3316 
3317   // If EmitVAArg promoted the type, we must truncate it.
3318   if (ArgTy != Val->getType())
3319     Val = Builder.CreateTrunc(Val, ArgTy);
3320 
3321   return Val;
3322 }
3323 
3324 Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
3325   return CGF.EmitBlockLiteral(block);
3326 }
3327 
3328 Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
3329   Value *Src  = CGF.EmitScalarExpr(E->getSrcExpr());
3330   llvm::Type *DstTy = ConvertType(E->getType());
3331 
3332   // Going from vec4->vec3 or vec3->vec4 is a special case and requires
3333   // a shuffle vector instead of a bitcast.
3334   llvm::Type *SrcTy = Src->getType();
3335   if (isa<llvm::VectorType>(DstTy) && isa<llvm::VectorType>(SrcTy)) {
3336     unsigned numElementsDst = cast<llvm::VectorType>(DstTy)->getNumElements();
3337     unsigned numElementsSrc = cast<llvm::VectorType>(SrcTy)->getNumElements();
3338     if ((numElementsDst == 3 && numElementsSrc == 4)
3339         || (numElementsDst == 4 && numElementsSrc == 3)) {
3340 
3341 
3342       // In the case of going from int4->float3, a bitcast is needed before
3343       // doing a shuffle.
3344       llvm::Type *srcElemTy =
3345       cast<llvm::VectorType>(SrcTy)->getElementType();
3346       llvm::Type *dstElemTy =
3347       cast<llvm::VectorType>(DstTy)->getElementType();
3348 
3349       if ((srcElemTy->isIntegerTy() && dstElemTy->isFloatTy())
3350           || (srcElemTy->isFloatTy() && dstElemTy->isIntegerTy())) {
3351         // Create a float type of the same size as the source or destination.
3352         llvm::VectorType *newSrcTy = llvm::VectorType::get(dstElemTy,
3353                                                                  numElementsSrc);
3354 
3355         Src = Builder.CreateBitCast(Src, newSrcTy, "astypeCast");
3356       }
3357 
3358       llvm::Value *UnV = llvm::UndefValue::get(Src->getType());
3359 
3360       SmallVector<llvm::Constant*, 3> Args;
3361       Args.push_back(Builder.getInt32(0));
3362       Args.push_back(Builder.getInt32(1));
3363       Args.push_back(Builder.getInt32(2));
3364 
3365       if (numElementsDst == 4)
3366         Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
3367 
3368       llvm::Constant *Mask = llvm::ConstantVector::get(Args);
3369 
3370       return Builder.CreateShuffleVector(Src, UnV, Mask, "astype");
3371     }
3372   }
3373 
3374   return Builder.CreateBitCast(Src, DstTy, "astype");
3375 }
3376 
3377 Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
3378   return CGF.EmitAtomicExpr(E).getScalarVal();
3379 }
3380 
3381 //===----------------------------------------------------------------------===//
3382 //                         Entry Point into this File
3383 //===----------------------------------------------------------------------===//
3384 
3385 /// EmitScalarExpr - Emit the computation of the specified expression of scalar
3386 /// type, ignoring the result.
3387 Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
3388   assert(E && hasScalarEvaluationKind(E->getType()) &&
3389          "Invalid scalar expression to emit");
3390 
3391   if (isa<CXXDefaultArgExpr>(E))
3392     disableDebugInfo();
3393   Value *V = ScalarExprEmitter(*this, IgnoreResultAssign)
3394     .Visit(const_cast<Expr*>(E));
3395   if (isa<CXXDefaultArgExpr>(E))
3396     enableDebugInfo();
3397   return V;
3398 }
3399 
3400 /// EmitScalarConversion - Emit a conversion from the specified type to the
3401 /// specified destination type, both of which are LLVM scalar types.
3402 Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
3403                                              QualType DstTy) {
3404   assert(hasScalarEvaluationKind(SrcTy) && hasScalarEvaluationKind(DstTy) &&
3405          "Invalid scalar expression to emit");
3406   return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
3407 }
3408 
3409 /// EmitComplexToScalarConversion - Emit a conversion from the specified complex
3410 /// type to the specified destination type, where the destination type is an
3411 /// LLVM scalar type.
3412 Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
3413                                                       QualType SrcTy,
3414                                                       QualType DstTy) {
3415   assert(SrcTy->isAnyComplexType() && hasScalarEvaluationKind(DstTy) &&
3416          "Invalid complex -> scalar conversion");
3417   return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
3418                                                                 DstTy);
3419 }
3420 
3421 
3422 llvm::Value *CodeGenFunction::
3423 EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
3424                         bool isInc, bool isPre) {
3425   return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
3426 }
3427 
3428 LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
3429   llvm::Value *V;
3430   // object->isa or (*object).isa
3431   // Generate code as for: *(Class*)object
3432   // build Class* type
3433   llvm::Type *ClassPtrTy = ConvertType(E->getType());
3434 
3435   Expr *BaseExpr = E->getBase();
3436   if (BaseExpr->isRValue()) {
3437     V = CreateMemTemp(E->getType(), "resval");
3438     llvm::Value *Src = EmitScalarExpr(BaseExpr);
3439     Builder.CreateStore(Src, V);
3440     V = ScalarExprEmitter(*this).EmitLoadOfLValue(
3441       MakeNaturalAlignAddrLValue(V, E->getType()), E->getExprLoc());
3442   } else {
3443     if (E->isArrow())
3444       V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr);
3445     else
3446       V = EmitLValue(BaseExpr).getAddress();
3447   }
3448 
3449   // build Class* type
3450   ClassPtrTy = ClassPtrTy->getPointerTo();
3451   V = Builder.CreateBitCast(V, ClassPtrTy);
3452   return MakeNaturalAlignAddrLValue(V, E->getType());
3453 }
3454 
3455 
3456 LValue CodeGenFunction::EmitCompoundAssignmentLValue(
3457                                             const CompoundAssignOperator *E) {
3458   ScalarExprEmitter Scalar(*this);
3459   Value *Result = nullptr;
3460   switch (E->getOpcode()) {
3461 #define COMPOUND_OP(Op)                                                       \
3462     case BO_##Op##Assign:                                                     \
3463       return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
3464                                              Result)
3465   COMPOUND_OP(Mul);
3466   COMPOUND_OP(Div);
3467   COMPOUND_OP(Rem);
3468   COMPOUND_OP(Add);
3469   COMPOUND_OP(Sub);
3470   COMPOUND_OP(Shl);
3471   COMPOUND_OP(Shr);
3472   COMPOUND_OP(And);
3473   COMPOUND_OP(Xor);
3474   COMPOUND_OP(Or);
3475 #undef COMPOUND_OP
3476 
3477   case BO_PtrMemD:
3478   case BO_PtrMemI:
3479   case BO_Mul:
3480   case BO_Div:
3481   case BO_Rem:
3482   case BO_Add:
3483   case BO_Sub:
3484   case BO_Shl:
3485   case BO_Shr:
3486   case BO_LT:
3487   case BO_GT:
3488   case BO_LE:
3489   case BO_GE:
3490   case BO_EQ:
3491   case BO_NE:
3492   case BO_And:
3493   case BO_Xor:
3494   case BO_Or:
3495   case BO_LAnd:
3496   case BO_LOr:
3497   case BO_Assign:
3498   case BO_Comma:
3499     llvm_unreachable("Not valid compound assignment operators");
3500   }
3501 
3502   llvm_unreachable("Unhandled compound assignment operator");
3503 }
3504