1 //===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This contains code to emit Expr nodes with scalar LLVM types as LLVM code.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "CGCXXABI.h"
14 #include "CGCleanup.h"
15 #include "CGDebugInfo.h"
16 #include "CGObjCRuntime.h"
17 #include "CGOpenMPRuntime.h"
18 #include "CodeGenFunction.h"
19 #include "CodeGenModule.h"
20 #include "ConstantEmitter.h"
21 #include "TargetInfo.h"
22 #include "clang/AST/ASTContext.h"
23 #include "clang/AST/Attr.h"
24 #include "clang/AST/DeclObjC.h"
25 #include "clang/AST/Expr.h"
26 #include "clang/AST/RecordLayout.h"
27 #include "clang/AST/StmtVisitor.h"
28 #include "clang/Basic/CodeGenOptions.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "llvm/ADT/APFixedPoint.h"
31 #include "llvm/ADT/Optional.h"
32 #include "llvm/IR/CFG.h"
33 #include "llvm/IR/Constants.h"
34 #include "llvm/IR/DataLayout.h"
35 #include "llvm/IR/FixedPointBuilder.h"
36 #include "llvm/IR/Function.h"
37 #include "llvm/IR/GetElementPtrTypeIterator.h"
38 #include "llvm/IR/GlobalVariable.h"
39 #include "llvm/IR/Intrinsics.h"
40 #include "llvm/IR/IntrinsicsPowerPC.h"
41 #include "llvm/IR/MatrixBuilder.h"
42 #include "llvm/IR/Module.h"
43 #include <cstdarg>
44
45 using namespace clang;
46 using namespace CodeGen;
47 using llvm::Value;
48
49 //===----------------------------------------------------------------------===//
50 // Scalar Expression Emitter
51 //===----------------------------------------------------------------------===//
52
53 namespace {
54
55 /// Determine whether the given binary operation may overflow.
56 /// Sets \p Result to the value of the operation for BO_Add, BO_Sub, BO_Mul,
57 /// and signed BO_{Div,Rem}. For these opcodes, and for unsigned BO_{Div,Rem},
58 /// the returned overflow check is precise. The returned value is 'true' for
59 /// all other opcodes, to be conservative.
mayHaveIntegerOverflow(llvm::ConstantInt * LHS,llvm::ConstantInt * RHS,BinaryOperator::Opcode Opcode,bool Signed,llvm::APInt & Result)60 bool mayHaveIntegerOverflow(llvm::ConstantInt *LHS, llvm::ConstantInt *RHS,
61 BinaryOperator::Opcode Opcode, bool Signed,
62 llvm::APInt &Result) {
63 // Assume overflow is possible, unless we can prove otherwise.
64 bool Overflow = true;
65 const auto &LHSAP = LHS->getValue();
66 const auto &RHSAP = RHS->getValue();
67 if (Opcode == BO_Add) {
68 if (Signed)
69 Result = LHSAP.sadd_ov(RHSAP, Overflow);
70 else
71 Result = LHSAP.uadd_ov(RHSAP, Overflow);
72 } else if (Opcode == BO_Sub) {
73 if (Signed)
74 Result = LHSAP.ssub_ov(RHSAP, Overflow);
75 else
76 Result = LHSAP.usub_ov(RHSAP, Overflow);
77 } else if (Opcode == BO_Mul) {
78 if (Signed)
79 Result = LHSAP.smul_ov(RHSAP, Overflow);
80 else
81 Result = LHSAP.umul_ov(RHSAP, Overflow);
82 } else if (Opcode == BO_Div || Opcode == BO_Rem) {
83 if (Signed && !RHS->isZero())
84 Result = LHSAP.sdiv_ov(RHSAP, Overflow);
85 else
86 return false;
87 }
88 return Overflow;
89 }
90
91 struct BinOpInfo {
92 Value *LHS;
93 Value *RHS;
94 QualType Ty; // Computation Type.
95 BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform
96 FPOptions FPFeatures;
97 const Expr *E; // Entire expr, for error unsupported. May not be binop.
98
99 /// Check if the binop can result in integer overflow.
mayHaveIntegerOverflow__anon75d0f0ad0111::BinOpInfo100 bool mayHaveIntegerOverflow() const {
101 // Without constant input, we can't rule out overflow.
102 auto *LHSCI = dyn_cast<llvm::ConstantInt>(LHS);
103 auto *RHSCI = dyn_cast<llvm::ConstantInt>(RHS);
104 if (!LHSCI || !RHSCI)
105 return true;
106
107 llvm::APInt Result;
108 return ::mayHaveIntegerOverflow(
109 LHSCI, RHSCI, Opcode, Ty->hasSignedIntegerRepresentation(), Result);
110 }
111
112 /// Check if the binop computes a division or a remainder.
isDivremOp__anon75d0f0ad0111::BinOpInfo113 bool isDivremOp() const {
114 return Opcode == BO_Div || Opcode == BO_Rem || Opcode == BO_DivAssign ||
115 Opcode == BO_RemAssign;
116 }
117
118 /// Check if the binop can result in an integer division by zero.
mayHaveIntegerDivisionByZero__anon75d0f0ad0111::BinOpInfo119 bool mayHaveIntegerDivisionByZero() const {
120 if (isDivremOp())
121 if (auto *CI = dyn_cast<llvm::ConstantInt>(RHS))
122 return CI->isZero();
123 return true;
124 }
125
126 /// Check if the binop can result in a float division by zero.
mayHaveFloatDivisionByZero__anon75d0f0ad0111::BinOpInfo127 bool mayHaveFloatDivisionByZero() const {
128 if (isDivremOp())
129 if (auto *CFP = dyn_cast<llvm::ConstantFP>(RHS))
130 return CFP->isZero();
131 return true;
132 }
133
134 /// Check if at least one operand is a fixed point type. In such cases, this
135 /// operation did not follow usual arithmetic conversion and both operands
136 /// might not be of the same type.
isFixedPointOp__anon75d0f0ad0111::BinOpInfo137 bool isFixedPointOp() const {
138 // We cannot simply check the result type since comparison operations return
139 // an int.
140 if (const auto *BinOp = dyn_cast<BinaryOperator>(E)) {
141 QualType LHSType = BinOp->getLHS()->getType();
142 QualType RHSType = BinOp->getRHS()->getType();
143 return LHSType->isFixedPointType() || RHSType->isFixedPointType();
144 }
145 if (const auto *UnOp = dyn_cast<UnaryOperator>(E))
146 return UnOp->getSubExpr()->getType()->isFixedPointType();
147 return false;
148 }
149 };
150
MustVisitNullValue(const Expr * E)151 static bool MustVisitNullValue(const Expr *E) {
152 // If a null pointer expression's type is the C++0x nullptr_t, then
153 // it's not necessarily a simple constant and it must be evaluated
154 // for its potential side effects.
155 return E->getType()->isNullPtrType();
156 }
157
158 /// If \p E is a widened promoted integer, get its base (unpromoted) type.
getUnwidenedIntegerType(const ASTContext & Ctx,const Expr * E)159 static llvm::Optional<QualType> getUnwidenedIntegerType(const ASTContext &Ctx,
160 const Expr *E) {
161 const Expr *Base = E->IgnoreImpCasts();
162 if (E == Base)
163 return llvm::None;
164
165 QualType BaseTy = Base->getType();
166 if (!BaseTy->isPromotableIntegerType() ||
167 Ctx.getTypeSize(BaseTy) >= Ctx.getTypeSize(E->getType()))
168 return llvm::None;
169
170 return BaseTy;
171 }
172
173 /// Check if \p E is a widened promoted integer.
IsWidenedIntegerOp(const ASTContext & Ctx,const Expr * E)174 static bool IsWidenedIntegerOp(const ASTContext &Ctx, const Expr *E) {
175 return getUnwidenedIntegerType(Ctx, E).hasValue();
176 }
177
178 /// Check if we can skip the overflow check for \p Op.
CanElideOverflowCheck(const ASTContext & Ctx,const BinOpInfo & Op)179 static bool CanElideOverflowCheck(const ASTContext &Ctx, const BinOpInfo &Op) {
180 assert((isa<UnaryOperator>(Op.E) || isa<BinaryOperator>(Op.E)) &&
181 "Expected a unary or binary operator");
182
183 // If the binop has constant inputs and we can prove there is no overflow,
184 // we can elide the overflow check.
185 if (!Op.mayHaveIntegerOverflow())
186 return true;
187
188 // If a unary op has a widened operand, the op cannot overflow.
189 if (const auto *UO = dyn_cast<UnaryOperator>(Op.E))
190 return !UO->canOverflow();
191
192 // We usually don't need overflow checks for binops with widened operands.
193 // Multiplication with promoted unsigned operands is a special case.
194 const auto *BO = cast<BinaryOperator>(Op.E);
195 auto OptionalLHSTy = getUnwidenedIntegerType(Ctx, BO->getLHS());
196 if (!OptionalLHSTy)
197 return false;
198
199 auto OptionalRHSTy = getUnwidenedIntegerType(Ctx, BO->getRHS());
200 if (!OptionalRHSTy)
201 return false;
202
203 QualType LHSTy = *OptionalLHSTy;
204 QualType RHSTy = *OptionalRHSTy;
205
206 // This is the simple case: binops without unsigned multiplication, and with
207 // widened operands. No overflow check is needed here.
208 if ((Op.Opcode != BO_Mul && Op.Opcode != BO_MulAssign) ||
209 !LHSTy->isUnsignedIntegerType() || !RHSTy->isUnsignedIntegerType())
210 return true;
211
212 // For unsigned multiplication the overflow check can be elided if either one
213 // of the unpromoted types are less than half the size of the promoted type.
214 unsigned PromotedSize = Ctx.getTypeSize(Op.E->getType());
215 return (2 * Ctx.getTypeSize(LHSTy)) < PromotedSize ||
216 (2 * Ctx.getTypeSize(RHSTy)) < PromotedSize;
217 }
218
219 class ScalarExprEmitter
220 : public StmtVisitor<ScalarExprEmitter, Value*> {
221 CodeGenFunction &CGF;
222 CGBuilderTy &Builder;
223 bool IgnoreResultAssign;
224 llvm::LLVMContext &VMContext;
225 public:
226
ScalarExprEmitter(CodeGenFunction & cgf,bool ira=false)227 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
228 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
229 VMContext(cgf.getLLVMContext()) {
230 }
231
232 //===--------------------------------------------------------------------===//
233 // Utilities
234 //===--------------------------------------------------------------------===//
235
TestAndClearIgnoreResultAssign()236 bool TestAndClearIgnoreResultAssign() {
237 bool I = IgnoreResultAssign;
238 IgnoreResultAssign = false;
239 return I;
240 }
241
ConvertType(QualType T)242 llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
EmitLValue(const Expr * E)243 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
EmitCheckedLValue(const Expr * E,CodeGenFunction::TypeCheckKind TCK)244 LValue EmitCheckedLValue(const Expr *E, CodeGenFunction::TypeCheckKind TCK) {
245 return CGF.EmitCheckedLValue(E, TCK);
246 }
247
248 void EmitBinOpCheck(ArrayRef<std::pair<Value *, SanitizerMask>> Checks,
249 const BinOpInfo &Info);
250
EmitLoadOfLValue(LValue LV,SourceLocation Loc)251 Value *EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
252 return CGF.EmitLoadOfLValue(LV, Loc).getScalarVal();
253 }
254
EmitLValueAlignmentAssumption(const Expr * E,Value * V)255 void EmitLValueAlignmentAssumption(const Expr *E, Value *V) {
256 const AlignValueAttr *AVAttr = nullptr;
257 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
258 const ValueDecl *VD = DRE->getDecl();
259
260 if (VD->getType()->isReferenceType()) {
261 if (const auto *TTy =
262 dyn_cast<TypedefType>(VD->getType().getNonReferenceType()))
263 AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
264 } else {
265 // Assumptions for function parameters are emitted at the start of the
266 // function, so there is no need to repeat that here,
267 // unless the alignment-assumption sanitizer is enabled,
268 // then we prefer the assumption over alignment attribute
269 // on IR function param.
270 if (isa<ParmVarDecl>(VD) && !CGF.SanOpts.has(SanitizerKind::Alignment))
271 return;
272
273 AVAttr = VD->getAttr<AlignValueAttr>();
274 }
275 }
276
277 if (!AVAttr)
278 if (const auto *TTy =
279 dyn_cast<TypedefType>(E->getType()))
280 AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
281
282 if (!AVAttr)
283 return;
284
285 Value *AlignmentValue = CGF.EmitScalarExpr(AVAttr->getAlignment());
286 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(AlignmentValue);
287 CGF.emitAlignmentAssumption(V, E, AVAttr->getLocation(), AlignmentCI);
288 }
289
290 /// EmitLoadOfLValue - Given an expression with complex type that represents a
291 /// value l-value, this method emits the address of the l-value, then loads
292 /// and returns the result.
EmitLoadOfLValue(const Expr * E)293 Value *EmitLoadOfLValue(const Expr *E) {
294 Value *V = EmitLoadOfLValue(EmitCheckedLValue(E, CodeGenFunction::TCK_Load),
295 E->getExprLoc());
296
297 EmitLValueAlignmentAssumption(E, V);
298 return V;
299 }
300
301 /// EmitConversionToBool - Convert the specified expression value to a
302 /// boolean (i1) truth value. This is equivalent to "Val != 0".
303 Value *EmitConversionToBool(Value *Src, QualType DstTy);
304
305 /// Emit a check that a conversion from a floating-point type does not
306 /// overflow.
307 void EmitFloatConversionCheck(Value *OrigSrc, QualType OrigSrcType,
308 Value *Src, QualType SrcType, QualType DstType,
309 llvm::Type *DstTy, SourceLocation Loc);
310
311 /// Known implicit conversion check kinds.
312 /// Keep in sync with the enum of the same name in ubsan_handlers.h
313 enum ImplicitConversionCheckKind : unsigned char {
314 ICCK_IntegerTruncation = 0, // Legacy, was only used by clang 7.
315 ICCK_UnsignedIntegerTruncation = 1,
316 ICCK_SignedIntegerTruncation = 2,
317 ICCK_IntegerSignChange = 3,
318 ICCK_SignedIntegerTruncationOrSignChange = 4,
319 };
320
321 /// Emit a check that an [implicit] truncation of an integer does not
322 /// discard any bits. It is not UB, so we use the value after truncation.
323 void EmitIntegerTruncationCheck(Value *Src, QualType SrcType, Value *Dst,
324 QualType DstType, SourceLocation Loc);
325
326 /// Emit a check that an [implicit] conversion of an integer does not change
327 /// the sign of the value. It is not UB, so we use the value after conversion.
328 /// NOTE: Src and Dst may be the exact same value! (point to the same thing)
329 void EmitIntegerSignChangeCheck(Value *Src, QualType SrcType, Value *Dst,
330 QualType DstType, SourceLocation Loc);
331
332 /// Emit a conversion from the specified type to the specified destination
333 /// type, both of which are LLVM scalar types.
334 struct ScalarConversionOpts {
335 bool TreatBooleanAsSigned;
336 bool EmitImplicitIntegerTruncationChecks;
337 bool EmitImplicitIntegerSignChangeChecks;
338
ScalarConversionOpts__anon75d0f0ad0111::ScalarExprEmitter::ScalarConversionOpts339 ScalarConversionOpts()
340 : TreatBooleanAsSigned(false),
341 EmitImplicitIntegerTruncationChecks(false),
342 EmitImplicitIntegerSignChangeChecks(false) {}
343
ScalarConversionOpts__anon75d0f0ad0111::ScalarExprEmitter::ScalarConversionOpts344 ScalarConversionOpts(clang::SanitizerSet SanOpts)
345 : TreatBooleanAsSigned(false),
346 EmitImplicitIntegerTruncationChecks(
347 SanOpts.hasOneOf(SanitizerKind::ImplicitIntegerTruncation)),
348 EmitImplicitIntegerSignChangeChecks(
349 SanOpts.has(SanitizerKind::ImplicitIntegerSignChange)) {}
350 };
351 Value *
352 EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy,
353 SourceLocation Loc,
354 ScalarConversionOpts Opts = ScalarConversionOpts());
355
356 /// Convert between either a fixed point and other fixed point or fixed point
357 /// and an integer.
358 Value *EmitFixedPointConversion(Value *Src, QualType SrcTy, QualType DstTy,
359 SourceLocation Loc);
360
361 /// Emit a conversion from the specified complex type to the specified
362 /// destination type, where the destination type is an LLVM scalar type.
363 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
364 QualType SrcTy, QualType DstTy,
365 SourceLocation Loc);
366
367 /// EmitNullValue - Emit a value that corresponds to null for the given type.
368 Value *EmitNullValue(QualType Ty);
369
370 /// EmitFloatToBoolConversion - Perform an FP to boolean conversion.
EmitFloatToBoolConversion(Value * V)371 Value *EmitFloatToBoolConversion(Value *V) {
372 // Compare against 0.0 for fp scalars.
373 llvm::Value *Zero = llvm::Constant::getNullValue(V->getType());
374 return Builder.CreateFCmpUNE(V, Zero, "tobool");
375 }
376
377 /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion.
EmitPointerToBoolConversion(Value * V,QualType QT)378 Value *EmitPointerToBoolConversion(Value *V, QualType QT) {
379 Value *Zero = CGF.CGM.getNullPointer(cast<llvm::PointerType>(V->getType()), QT);
380
381 return Builder.CreateICmpNE(V, Zero, "tobool");
382 }
383
EmitIntToBoolConversion(Value * V)384 Value *EmitIntToBoolConversion(Value *V) {
385 // Because of the type rules of C, we often end up computing a
386 // logical value, then zero extending it to int, then wanting it
387 // as a logical value again. Optimize this common case.
388 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) {
389 if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) {
390 Value *Result = ZI->getOperand(0);
391 // If there aren't any more uses, zap the instruction to save space.
392 // Note that there can be more uses, for example if this
393 // is the result of an assignment.
394 if (ZI->use_empty())
395 ZI->eraseFromParent();
396 return Result;
397 }
398 }
399
400 return Builder.CreateIsNotNull(V, "tobool");
401 }
402
403 //===--------------------------------------------------------------------===//
404 // Visitor Methods
405 //===--------------------------------------------------------------------===//
406
Visit(Expr * E)407 Value *Visit(Expr *E) {
408 ApplyDebugLocation DL(CGF, E);
409 return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
410 }
411
VisitStmt(Stmt * S)412 Value *VisitStmt(Stmt *S) {
413 S->dump(llvm::errs(), CGF.getContext());
414 llvm_unreachable("Stmt can't have complex result type!");
415 }
416 Value *VisitExpr(Expr *S);
417
VisitConstantExpr(ConstantExpr * E)418 Value *VisitConstantExpr(ConstantExpr *E) {
419 if (Value *Result = ConstantEmitter(CGF).tryEmitConstantExpr(E)) {
420 if (E->isGLValue())
421 return CGF.Builder.CreateLoad(Address(
422 Result, CGF.getContext().getTypeAlignInChars(E->getType())));
423 return Result;
424 }
425 return Visit(E->getSubExpr());
426 }
VisitParenExpr(ParenExpr * PE)427 Value *VisitParenExpr(ParenExpr *PE) {
428 return Visit(PE->getSubExpr());
429 }
VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr * E)430 Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
431 return Visit(E->getReplacement());
432 }
VisitGenericSelectionExpr(GenericSelectionExpr * GE)433 Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
434 return Visit(GE->getResultExpr());
435 }
VisitCoawaitExpr(CoawaitExpr * S)436 Value *VisitCoawaitExpr(CoawaitExpr *S) {
437 return CGF.EmitCoawaitExpr(*S).getScalarVal();
438 }
VisitCoyieldExpr(CoyieldExpr * S)439 Value *VisitCoyieldExpr(CoyieldExpr *S) {
440 return CGF.EmitCoyieldExpr(*S).getScalarVal();
441 }
VisitUnaryCoawait(const UnaryOperator * E)442 Value *VisitUnaryCoawait(const UnaryOperator *E) {
443 return Visit(E->getSubExpr());
444 }
445
446 // Leaves.
VisitIntegerLiteral(const IntegerLiteral * E)447 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
448 return Builder.getInt(E->getValue());
449 }
VisitFixedPointLiteral(const FixedPointLiteral * E)450 Value *VisitFixedPointLiteral(const FixedPointLiteral *E) {
451 return Builder.getInt(E->getValue());
452 }
VisitFloatingLiteral(const FloatingLiteral * E)453 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
454 return llvm::ConstantFP::get(VMContext, E->getValue());
455 }
VisitCharacterLiteral(const CharacterLiteral * E)456 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
457 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
458 }
VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr * E)459 Value *VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
460 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
461 }
VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr * E)462 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
463 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
464 }
VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr * E)465 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
466 return EmitNullValue(E->getType());
467 }
VisitGNUNullExpr(const GNUNullExpr * E)468 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
469 return EmitNullValue(E->getType());
470 }
471 Value *VisitOffsetOfExpr(OffsetOfExpr *E);
472 Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
VisitAddrLabelExpr(const AddrLabelExpr * E)473 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
474 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
475 return Builder.CreateBitCast(V, ConvertType(E->getType()));
476 }
477
VisitSizeOfPackExpr(SizeOfPackExpr * E)478 Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
479 return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength());
480 }
481
VisitPseudoObjectExpr(PseudoObjectExpr * E)482 Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) {
483 return CGF.EmitPseudoObjectRValue(E).getScalarVal();
484 }
485
VisitOpaqueValueExpr(OpaqueValueExpr * E)486 Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
487 if (E->isGLValue())
488 return EmitLoadOfLValue(CGF.getOrCreateOpaqueLValueMapping(E),
489 E->getExprLoc());
490
491 // Otherwise, assume the mapping is the scalar directly.
492 return CGF.getOrCreateOpaqueRValueMapping(E).getScalarVal();
493 }
494
495 // l-values.
VisitDeclRefExpr(DeclRefExpr * E)496 Value *VisitDeclRefExpr(DeclRefExpr *E) {
497 if (CodeGenFunction::ConstantEmission Constant = CGF.tryEmitAsConstant(E))
498 return CGF.emitScalarConstant(Constant, E);
499 return EmitLoadOfLValue(E);
500 }
501
VisitObjCSelectorExpr(ObjCSelectorExpr * E)502 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
503 return CGF.EmitObjCSelectorExpr(E);
504 }
VisitObjCProtocolExpr(ObjCProtocolExpr * E)505 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
506 return CGF.EmitObjCProtocolExpr(E);
507 }
VisitObjCIvarRefExpr(ObjCIvarRefExpr * E)508 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
509 return EmitLoadOfLValue(E);
510 }
VisitObjCMessageExpr(ObjCMessageExpr * E)511 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
512 if (E->getMethodDecl() &&
513 E->getMethodDecl()->getReturnType()->isReferenceType())
514 return EmitLoadOfLValue(E);
515 return CGF.EmitObjCMessageExpr(E).getScalarVal();
516 }
517
VisitObjCIsaExpr(ObjCIsaExpr * E)518 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
519 LValue LV = CGF.EmitObjCIsaExpr(E);
520 Value *V = CGF.EmitLoadOfLValue(LV, E->getExprLoc()).getScalarVal();
521 return V;
522 }
523
VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr * E)524 Value *VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *E) {
525 VersionTuple Version = E->getVersion();
526
527 // If we're checking for a platform older than our minimum deployment
528 // target, we can fold the check away.
529 if (Version <= CGF.CGM.getTarget().getPlatformMinVersion())
530 return llvm::ConstantInt::get(Builder.getInt1Ty(), 1);
531
532 return CGF.EmitBuiltinAvailable(Version);
533 }
534
535 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
536 Value *VisitMatrixSubscriptExpr(MatrixSubscriptExpr *E);
537 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
538 Value *VisitConvertVectorExpr(ConvertVectorExpr *E);
539 Value *VisitMemberExpr(MemberExpr *E);
VisitExtVectorElementExpr(Expr * E)540 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
VisitCompoundLiteralExpr(CompoundLiteralExpr * E)541 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
542 // Strictly speaking, we shouldn't be calling EmitLoadOfLValue, which
543 // transitively calls EmitCompoundLiteralLValue, here in C++ since compound
544 // literals aren't l-values in C++. We do so simply because that's the
545 // cleanest way to handle compound literals in C++.
546 // See the discussion here: https://reviews.llvm.org/D64464
547 return EmitLoadOfLValue(E);
548 }
549
550 Value *VisitInitListExpr(InitListExpr *E);
551
VisitArrayInitIndexExpr(ArrayInitIndexExpr * E)552 Value *VisitArrayInitIndexExpr(ArrayInitIndexExpr *E) {
553 assert(CGF.getArrayInitIndex() &&
554 "ArrayInitIndexExpr not inside an ArrayInitLoopExpr?");
555 return CGF.getArrayInitIndex();
556 }
557
VisitImplicitValueInitExpr(const ImplicitValueInitExpr * E)558 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
559 return EmitNullValue(E->getType());
560 }
VisitExplicitCastExpr(ExplicitCastExpr * E)561 Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
562 CGF.CGM.EmitExplicitCastExprType(E, &CGF);
563 return VisitCastExpr(E);
564 }
565 Value *VisitCastExpr(CastExpr *E);
566
VisitCallExpr(const CallExpr * E)567 Value *VisitCallExpr(const CallExpr *E) {
568 if (E->getCallReturnType(CGF.getContext())->isReferenceType())
569 return EmitLoadOfLValue(E);
570
571 Value *V = CGF.EmitCallExpr(E).getScalarVal();
572
573 EmitLValueAlignmentAssumption(E, V);
574 return V;
575 }
576
577 Value *VisitStmtExpr(const StmtExpr *E);
578
579 // Unary Operators.
VisitUnaryPostDec(const UnaryOperator * E)580 Value *VisitUnaryPostDec(const UnaryOperator *E) {
581 LValue LV = EmitLValue(E->getSubExpr());
582 return EmitScalarPrePostIncDec(E, LV, false, false);
583 }
VisitUnaryPostInc(const UnaryOperator * E)584 Value *VisitUnaryPostInc(const UnaryOperator *E) {
585 LValue LV = EmitLValue(E->getSubExpr());
586 return EmitScalarPrePostIncDec(E, LV, true, false);
587 }
VisitUnaryPreDec(const UnaryOperator * E)588 Value *VisitUnaryPreDec(const UnaryOperator *E) {
589 LValue LV = EmitLValue(E->getSubExpr());
590 return EmitScalarPrePostIncDec(E, LV, false, true);
591 }
VisitUnaryPreInc(const UnaryOperator * E)592 Value *VisitUnaryPreInc(const UnaryOperator *E) {
593 LValue LV = EmitLValue(E->getSubExpr());
594 return EmitScalarPrePostIncDec(E, LV, true, true);
595 }
596
597 llvm::Value *EmitIncDecConsiderOverflowBehavior(const UnaryOperator *E,
598 llvm::Value *InVal,
599 bool IsInc);
600
601 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
602 bool isInc, bool isPre);
603
604
VisitUnaryAddrOf(const UnaryOperator * E)605 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
606 if (isa<MemberPointerType>(E->getType())) // never sugared
607 return CGF.CGM.getMemberPointerConstant(E);
608
609 return EmitLValue(E->getSubExpr()).getPointer(CGF);
610 }
VisitUnaryDeref(const UnaryOperator * E)611 Value *VisitUnaryDeref(const UnaryOperator *E) {
612 if (E->getType()->isVoidType())
613 return Visit(E->getSubExpr()); // the actual value should be unused
614 return EmitLoadOfLValue(E);
615 }
VisitUnaryPlus(const UnaryOperator * E)616 Value *VisitUnaryPlus(const UnaryOperator *E) {
617 // This differs from gcc, though, most likely due to a bug in gcc.
618 TestAndClearIgnoreResultAssign();
619 return Visit(E->getSubExpr());
620 }
621 Value *VisitUnaryMinus (const UnaryOperator *E);
622 Value *VisitUnaryNot (const UnaryOperator *E);
623 Value *VisitUnaryLNot (const UnaryOperator *E);
624 Value *VisitUnaryReal (const UnaryOperator *E);
625 Value *VisitUnaryImag (const UnaryOperator *E);
VisitUnaryExtension(const UnaryOperator * E)626 Value *VisitUnaryExtension(const UnaryOperator *E) {
627 return Visit(E->getSubExpr());
628 }
629
630 // C++
VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr * E)631 Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) {
632 return EmitLoadOfLValue(E);
633 }
VisitSourceLocExpr(SourceLocExpr * SLE)634 Value *VisitSourceLocExpr(SourceLocExpr *SLE) {
635 auto &Ctx = CGF.getContext();
636 APValue Evaluated =
637 SLE->EvaluateInContext(Ctx, CGF.CurSourceLocExprScope.getDefaultExpr());
638 return ConstantEmitter(CGF).emitAbstract(SLE->getLocation(), Evaluated,
639 SLE->getType());
640 }
641
VisitCXXDefaultArgExpr(CXXDefaultArgExpr * DAE)642 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
643 CodeGenFunction::CXXDefaultArgExprScope Scope(CGF, DAE);
644 return Visit(DAE->getExpr());
645 }
VisitCXXDefaultInitExpr(CXXDefaultInitExpr * DIE)646 Value *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
647 CodeGenFunction::CXXDefaultInitExprScope Scope(CGF, DIE);
648 return Visit(DIE->getExpr());
649 }
VisitCXXThisExpr(CXXThisExpr * TE)650 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
651 return CGF.LoadCXXThis();
652 }
653
654 Value *VisitExprWithCleanups(ExprWithCleanups *E);
VisitCXXNewExpr(const CXXNewExpr * E)655 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
656 return CGF.EmitCXXNewExpr(E);
657 }
VisitCXXDeleteExpr(const CXXDeleteExpr * E)658 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
659 CGF.EmitCXXDeleteExpr(E);
660 return nullptr;
661 }
662
VisitTypeTraitExpr(const TypeTraitExpr * E)663 Value *VisitTypeTraitExpr(const TypeTraitExpr *E) {
664 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
665 }
666
VisitConceptSpecializationExpr(const ConceptSpecializationExpr * E)667 Value *VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E) {
668 return Builder.getInt1(E->isSatisfied());
669 }
670
VisitRequiresExpr(const RequiresExpr * E)671 Value *VisitRequiresExpr(const RequiresExpr *E) {
672 return Builder.getInt1(E->isSatisfied());
673 }
674
VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr * E)675 Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
676 return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue());
677 }
678
VisitExpressionTraitExpr(const ExpressionTraitExpr * E)679 Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
680 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
681 }
682
VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr * E)683 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
684 // C++ [expr.pseudo]p1:
685 // The result shall only be used as the operand for the function call
686 // operator (), and the result of such a call has type void. The only
687 // effect is the evaluation of the postfix-expression before the dot or
688 // arrow.
689 CGF.EmitScalarExpr(E->getBase());
690 return nullptr;
691 }
692
VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr * E)693 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
694 return EmitNullValue(E->getType());
695 }
696
VisitCXXThrowExpr(const CXXThrowExpr * E)697 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
698 CGF.EmitCXXThrowExpr(E);
699 return nullptr;
700 }
701
VisitCXXNoexceptExpr(const CXXNoexceptExpr * E)702 Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
703 return Builder.getInt1(E->getValue());
704 }
705
706 // Binary Operators.
EmitMul(const BinOpInfo & Ops)707 Value *EmitMul(const BinOpInfo &Ops) {
708 if (Ops.Ty->isSignedIntegerOrEnumerationType()) {
709 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
710 case LangOptions::SOB_Defined:
711 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
712 case LangOptions::SOB_Undefined:
713 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
714 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
715 LLVM_FALLTHROUGH;
716 case LangOptions::SOB_Trapping:
717 if (CanElideOverflowCheck(CGF.getContext(), Ops))
718 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
719 return EmitOverflowCheckedBinOp(Ops);
720 }
721 }
722
723 if (Ops.Ty->isConstantMatrixType()) {
724 llvm::MatrixBuilder<CGBuilderTy> MB(Builder);
725 // We need to check the types of the operands of the operator to get the
726 // correct matrix dimensions.
727 auto *BO = cast<BinaryOperator>(Ops.E);
728 auto *LHSMatTy = dyn_cast<ConstantMatrixType>(
729 BO->getLHS()->getType().getCanonicalType());
730 auto *RHSMatTy = dyn_cast<ConstantMatrixType>(
731 BO->getRHS()->getType().getCanonicalType());
732 if (LHSMatTy && RHSMatTy)
733 return MB.CreateMatrixMultiply(Ops.LHS, Ops.RHS, LHSMatTy->getNumRows(),
734 LHSMatTy->getNumColumns(),
735 RHSMatTy->getNumColumns());
736 return MB.CreateScalarMultiply(Ops.LHS, Ops.RHS);
737 }
738
739 if (Ops.Ty->isUnsignedIntegerType() &&
740 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
741 !CanElideOverflowCheck(CGF.getContext(), Ops))
742 return EmitOverflowCheckedBinOp(Ops);
743
744 if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
745 // Preserve the old values
746 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Ops.FPFeatures);
747 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
748 }
749 if (Ops.isFixedPointOp())
750 return EmitFixedPointBinOp(Ops);
751 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
752 }
753 /// Create a binary op that checks for overflow.
754 /// Currently only supports +, - and *.
755 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
756
757 // Check for undefined division and modulus behaviors.
758 void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
759 llvm::Value *Zero,bool isDiv);
760 // Common helper for getting how wide LHS of shift is.
761 static Value *GetWidthMinusOneValue(Value* LHS,Value* RHS);
762
763 // Used for shifting constraints for OpenCL, do mask for powers of 2, URem for
764 // non powers of two.
765 Value *ConstrainShiftValue(Value *LHS, Value *RHS, const Twine &Name);
766
767 Value *EmitDiv(const BinOpInfo &Ops);
768 Value *EmitRem(const BinOpInfo &Ops);
769 Value *EmitAdd(const BinOpInfo &Ops);
770 Value *EmitSub(const BinOpInfo &Ops);
771 Value *EmitShl(const BinOpInfo &Ops);
772 Value *EmitShr(const BinOpInfo &Ops);
EmitAnd(const BinOpInfo & Ops)773 Value *EmitAnd(const BinOpInfo &Ops) {
774 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
775 }
EmitXor(const BinOpInfo & Ops)776 Value *EmitXor(const BinOpInfo &Ops) {
777 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
778 }
EmitOr(const BinOpInfo & Ops)779 Value *EmitOr (const BinOpInfo &Ops) {
780 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
781 }
782
783 // Helper functions for fixed point binary operations.
784 Value *EmitFixedPointBinOp(const BinOpInfo &Ops);
785
786 BinOpInfo EmitBinOps(const BinaryOperator *E);
787 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
788 Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
789 Value *&Result);
790
791 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
792 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
793
794 // Binary operators and binary compound assignment operators.
795 #define HANDLEBINOP(OP) \
796 Value *VisitBin ## OP(const BinaryOperator *E) { \
797 return Emit ## OP(EmitBinOps(E)); \
798 } \
799 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
800 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
801 }
802 HANDLEBINOP(Mul)
803 HANDLEBINOP(Div)
804 HANDLEBINOP(Rem)
805 HANDLEBINOP(Add)
806 HANDLEBINOP(Sub)
807 HANDLEBINOP(Shl)
808 HANDLEBINOP(Shr)
809 HANDLEBINOP(And)
810 HANDLEBINOP(Xor)
811 HANDLEBINOP(Or)
812 #undef HANDLEBINOP
813
814 // Comparisons.
815 Value *EmitCompare(const BinaryOperator *E, llvm::CmpInst::Predicate UICmpOpc,
816 llvm::CmpInst::Predicate SICmpOpc,
817 llvm::CmpInst::Predicate FCmpOpc, bool IsSignaling);
818 #define VISITCOMP(CODE, UI, SI, FP, SIG) \
819 Value *VisitBin##CODE(const BinaryOperator *E) { \
820 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
821 llvm::FCmpInst::FP, SIG); }
822 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT, true)
823 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT, true)
824 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE, true)
825 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE, true)
826 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ, false)
827 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE, false)
828 #undef VISITCOMP
829
830 Value *VisitBinAssign (const BinaryOperator *E);
831
832 Value *VisitBinLAnd (const BinaryOperator *E);
833 Value *VisitBinLOr (const BinaryOperator *E);
834 Value *VisitBinComma (const BinaryOperator *E);
835
VisitBinPtrMemD(const Expr * E)836 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
VisitBinPtrMemI(const Expr * E)837 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
838
VisitCXXRewrittenBinaryOperator(CXXRewrittenBinaryOperator * E)839 Value *VisitCXXRewrittenBinaryOperator(CXXRewrittenBinaryOperator *E) {
840 return Visit(E->getSemanticForm());
841 }
842
843 // Other Operators.
844 Value *VisitBlockExpr(const BlockExpr *BE);
845 Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
846 Value *VisitChooseExpr(ChooseExpr *CE);
847 Value *VisitVAArgExpr(VAArgExpr *VE);
VisitObjCStringLiteral(const ObjCStringLiteral * E)848 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
849 return CGF.EmitObjCStringLiteral(E);
850 }
VisitObjCBoxedExpr(ObjCBoxedExpr * E)851 Value *VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
852 return CGF.EmitObjCBoxedExpr(E);
853 }
VisitObjCArrayLiteral(ObjCArrayLiteral * E)854 Value *VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
855 return CGF.EmitObjCArrayLiteral(E);
856 }
VisitObjCDictionaryLiteral(ObjCDictionaryLiteral * E)857 Value *VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
858 return CGF.EmitObjCDictionaryLiteral(E);
859 }
860 Value *VisitAsTypeExpr(AsTypeExpr *CE);
861 Value *VisitAtomicExpr(AtomicExpr *AE);
862 };
863 } // end anonymous namespace.
864
865 //===----------------------------------------------------------------------===//
866 // Utilities
867 //===----------------------------------------------------------------------===//
868
869 /// EmitConversionToBool - Convert the specified expression value to a
870 /// boolean (i1) truth value. This is equivalent to "Val != 0".
EmitConversionToBool(Value * Src,QualType SrcType)871 Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
872 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
873
874 if (SrcType->isRealFloatingType())
875 return EmitFloatToBoolConversion(Src);
876
877 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
878 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
879
880 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
881 "Unknown scalar type to convert");
882
883 if (isa<llvm::IntegerType>(Src->getType()))
884 return EmitIntToBoolConversion(Src);
885
886 assert(isa<llvm::PointerType>(Src->getType()));
887 return EmitPointerToBoolConversion(Src, SrcType);
888 }
889
EmitFloatConversionCheck(Value * OrigSrc,QualType OrigSrcType,Value * Src,QualType SrcType,QualType DstType,llvm::Type * DstTy,SourceLocation Loc)890 void ScalarExprEmitter::EmitFloatConversionCheck(
891 Value *OrigSrc, QualType OrigSrcType, Value *Src, QualType SrcType,
892 QualType DstType, llvm::Type *DstTy, SourceLocation Loc) {
893 assert(SrcType->isFloatingType() && "not a conversion from floating point");
894 if (!isa<llvm::IntegerType>(DstTy))
895 return;
896
897 CodeGenFunction::SanitizerScope SanScope(&CGF);
898 using llvm::APFloat;
899 using llvm::APSInt;
900
901 llvm::Value *Check = nullptr;
902 const llvm::fltSemantics &SrcSema =
903 CGF.getContext().getFloatTypeSemantics(OrigSrcType);
904
905 // Floating-point to integer. This has undefined behavior if the source is
906 // +-Inf, NaN, or doesn't fit into the destination type (after truncation
907 // to an integer).
908 unsigned Width = CGF.getContext().getIntWidth(DstType);
909 bool Unsigned = DstType->isUnsignedIntegerOrEnumerationType();
910
911 APSInt Min = APSInt::getMinValue(Width, Unsigned);
912 APFloat MinSrc(SrcSema, APFloat::uninitialized);
913 if (MinSrc.convertFromAPInt(Min, !Unsigned, APFloat::rmTowardZero) &
914 APFloat::opOverflow)
915 // Don't need an overflow check for lower bound. Just check for
916 // -Inf/NaN.
917 MinSrc = APFloat::getInf(SrcSema, true);
918 else
919 // Find the largest value which is too small to represent (before
920 // truncation toward zero).
921 MinSrc.subtract(APFloat(SrcSema, 1), APFloat::rmTowardNegative);
922
923 APSInt Max = APSInt::getMaxValue(Width, Unsigned);
924 APFloat MaxSrc(SrcSema, APFloat::uninitialized);
925 if (MaxSrc.convertFromAPInt(Max, !Unsigned, APFloat::rmTowardZero) &
926 APFloat::opOverflow)
927 // Don't need an overflow check for upper bound. Just check for
928 // +Inf/NaN.
929 MaxSrc = APFloat::getInf(SrcSema, false);
930 else
931 // Find the smallest value which is too large to represent (before
932 // truncation toward zero).
933 MaxSrc.add(APFloat(SrcSema, 1), APFloat::rmTowardPositive);
934
935 // If we're converting from __half, convert the range to float to match
936 // the type of src.
937 if (OrigSrcType->isHalfType()) {
938 const llvm::fltSemantics &Sema =
939 CGF.getContext().getFloatTypeSemantics(SrcType);
940 bool IsInexact;
941 MinSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
942 MaxSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
943 }
944
945 llvm::Value *GE =
946 Builder.CreateFCmpOGT(Src, llvm::ConstantFP::get(VMContext, MinSrc));
947 llvm::Value *LE =
948 Builder.CreateFCmpOLT(Src, llvm::ConstantFP::get(VMContext, MaxSrc));
949 Check = Builder.CreateAnd(GE, LE);
950
951 llvm::Constant *StaticArgs[] = {CGF.EmitCheckSourceLocation(Loc),
952 CGF.EmitCheckTypeDescriptor(OrigSrcType),
953 CGF.EmitCheckTypeDescriptor(DstType)};
954 CGF.EmitCheck(std::make_pair(Check, SanitizerKind::FloatCastOverflow),
955 SanitizerHandler::FloatCastOverflow, StaticArgs, OrigSrc);
956 }
957
958 // Should be called within CodeGenFunction::SanitizerScope RAII scope.
959 // Returns 'i1 false' when the truncation Src -> Dst was lossy.
960 static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
961 std::pair<llvm::Value *, SanitizerMask>>
EmitIntegerTruncationCheckHelper(Value * Src,QualType SrcType,Value * Dst,QualType DstType,CGBuilderTy & Builder)962 EmitIntegerTruncationCheckHelper(Value *Src, QualType SrcType, Value *Dst,
963 QualType DstType, CGBuilderTy &Builder) {
964 llvm::Type *SrcTy = Src->getType();
965 llvm::Type *DstTy = Dst->getType();
966 (void)DstTy; // Only used in assert()
967
968 // This should be truncation of integral types.
969 assert(Src != Dst);
970 assert(SrcTy->getScalarSizeInBits() > Dst->getType()->getScalarSizeInBits());
971 assert(isa<llvm::IntegerType>(SrcTy) && isa<llvm::IntegerType>(DstTy) &&
972 "non-integer llvm type");
973
974 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
975 bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
976
977 // If both (src and dst) types are unsigned, then it's an unsigned truncation.
978 // Else, it is a signed truncation.
979 ScalarExprEmitter::ImplicitConversionCheckKind Kind;
980 SanitizerMask Mask;
981 if (!SrcSigned && !DstSigned) {
982 Kind = ScalarExprEmitter::ICCK_UnsignedIntegerTruncation;
983 Mask = SanitizerKind::ImplicitUnsignedIntegerTruncation;
984 } else {
985 Kind = ScalarExprEmitter::ICCK_SignedIntegerTruncation;
986 Mask = SanitizerKind::ImplicitSignedIntegerTruncation;
987 }
988
989 llvm::Value *Check = nullptr;
990 // 1. Extend the truncated value back to the same width as the Src.
991 Check = Builder.CreateIntCast(Dst, SrcTy, DstSigned, "anyext");
992 // 2. Equality-compare with the original source value
993 Check = Builder.CreateICmpEQ(Check, Src, "truncheck");
994 // If the comparison result is 'i1 false', then the truncation was lossy.
995 return std::make_pair(Kind, std::make_pair(Check, Mask));
996 }
997
PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(QualType SrcType,QualType DstType)998 static bool PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(
999 QualType SrcType, QualType DstType) {
1000 return SrcType->isIntegerType() && DstType->isIntegerType();
1001 }
1002
EmitIntegerTruncationCheck(Value * Src,QualType SrcType,Value * Dst,QualType DstType,SourceLocation Loc)1003 void ScalarExprEmitter::EmitIntegerTruncationCheck(Value *Src, QualType SrcType,
1004 Value *Dst, QualType DstType,
1005 SourceLocation Loc) {
1006 if (!CGF.SanOpts.hasOneOf(SanitizerKind::ImplicitIntegerTruncation))
1007 return;
1008
1009 // We only care about int->int conversions here.
1010 // We ignore conversions to/from pointer and/or bool.
1011 if (!PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(SrcType,
1012 DstType))
1013 return;
1014
1015 unsigned SrcBits = Src->getType()->getScalarSizeInBits();
1016 unsigned DstBits = Dst->getType()->getScalarSizeInBits();
1017 // This must be truncation. Else we do not care.
1018 if (SrcBits <= DstBits)
1019 return;
1020
1021 assert(!DstType->isBooleanType() && "we should not get here with booleans.");
1022
1023 // If the integer sign change sanitizer is enabled,
1024 // and we are truncating from larger unsigned type to smaller signed type,
1025 // let that next sanitizer deal with it.
1026 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1027 bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
1028 if (CGF.SanOpts.has(SanitizerKind::ImplicitIntegerSignChange) &&
1029 (!SrcSigned && DstSigned))
1030 return;
1031
1032 CodeGenFunction::SanitizerScope SanScope(&CGF);
1033
1034 std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1035 std::pair<llvm::Value *, SanitizerMask>>
1036 Check =
1037 EmitIntegerTruncationCheckHelper(Src, SrcType, Dst, DstType, Builder);
1038 // If the comparison result is 'i1 false', then the truncation was lossy.
1039
1040 // Do we care about this type of truncation?
1041 if (!CGF.SanOpts.has(Check.second.second))
1042 return;
1043
1044 llvm::Constant *StaticArgs[] = {
1045 CGF.EmitCheckSourceLocation(Loc), CGF.EmitCheckTypeDescriptor(SrcType),
1046 CGF.EmitCheckTypeDescriptor(DstType),
1047 llvm::ConstantInt::get(Builder.getInt8Ty(), Check.first)};
1048 CGF.EmitCheck(Check.second, SanitizerHandler::ImplicitConversion, StaticArgs,
1049 {Src, Dst});
1050 }
1051
1052 // Should be called within CodeGenFunction::SanitizerScope RAII scope.
1053 // Returns 'i1 false' when the conversion Src -> Dst changed the sign.
1054 static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1055 std::pair<llvm::Value *, SanitizerMask>>
EmitIntegerSignChangeCheckHelper(Value * Src,QualType SrcType,Value * Dst,QualType DstType,CGBuilderTy & Builder)1056 EmitIntegerSignChangeCheckHelper(Value *Src, QualType SrcType, Value *Dst,
1057 QualType DstType, CGBuilderTy &Builder) {
1058 llvm::Type *SrcTy = Src->getType();
1059 llvm::Type *DstTy = Dst->getType();
1060
1061 assert(isa<llvm::IntegerType>(SrcTy) && isa<llvm::IntegerType>(DstTy) &&
1062 "non-integer llvm type");
1063
1064 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1065 bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
1066 (void)SrcSigned; // Only used in assert()
1067 (void)DstSigned; // Only used in assert()
1068 unsigned SrcBits = SrcTy->getScalarSizeInBits();
1069 unsigned DstBits = DstTy->getScalarSizeInBits();
1070 (void)SrcBits; // Only used in assert()
1071 (void)DstBits; // Only used in assert()
1072
1073 assert(((SrcBits != DstBits) || (SrcSigned != DstSigned)) &&
1074 "either the widths should be different, or the signednesses.");
1075
1076 // NOTE: zero value is considered to be non-negative.
1077 auto EmitIsNegativeTest = [&Builder](Value *V, QualType VType,
1078 const char *Name) -> Value * {
1079 // Is this value a signed type?
1080 bool VSigned = VType->isSignedIntegerOrEnumerationType();
1081 llvm::Type *VTy = V->getType();
1082 if (!VSigned) {
1083 // If the value is unsigned, then it is never negative.
1084 // FIXME: can we encounter non-scalar VTy here?
1085 return llvm::ConstantInt::getFalse(VTy->getContext());
1086 }
1087 // Get the zero of the same type with which we will be comparing.
1088 llvm::Constant *Zero = llvm::ConstantInt::get(VTy, 0);
1089 // %V.isnegative = icmp slt %V, 0
1090 // I.e is %V *strictly* less than zero, does it have negative value?
1091 return Builder.CreateICmp(llvm::ICmpInst::ICMP_SLT, V, Zero,
1092 llvm::Twine(Name) + "." + V->getName() +
1093 ".negativitycheck");
1094 };
1095
1096 // 1. Was the old Value negative?
1097 llvm::Value *SrcIsNegative = EmitIsNegativeTest(Src, SrcType, "src");
1098 // 2. Is the new Value negative?
1099 llvm::Value *DstIsNegative = EmitIsNegativeTest(Dst, DstType, "dst");
1100 // 3. Now, was the 'negativity status' preserved during the conversion?
1101 // NOTE: conversion from negative to zero is considered to change the sign.
1102 // (We want to get 'false' when the conversion changed the sign)
1103 // So we should just equality-compare the negativity statuses.
1104 llvm::Value *Check = nullptr;
1105 Check = Builder.CreateICmpEQ(SrcIsNegative, DstIsNegative, "signchangecheck");
1106 // If the comparison result is 'false', then the conversion changed the sign.
1107 return std::make_pair(
1108 ScalarExprEmitter::ICCK_IntegerSignChange,
1109 std::make_pair(Check, SanitizerKind::ImplicitIntegerSignChange));
1110 }
1111
EmitIntegerSignChangeCheck(Value * Src,QualType SrcType,Value * Dst,QualType DstType,SourceLocation Loc)1112 void ScalarExprEmitter::EmitIntegerSignChangeCheck(Value *Src, QualType SrcType,
1113 Value *Dst, QualType DstType,
1114 SourceLocation Loc) {
1115 if (!CGF.SanOpts.has(SanitizerKind::ImplicitIntegerSignChange))
1116 return;
1117
1118 llvm::Type *SrcTy = Src->getType();
1119 llvm::Type *DstTy = Dst->getType();
1120
1121 // We only care about int->int conversions here.
1122 // We ignore conversions to/from pointer and/or bool.
1123 if (!PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(SrcType,
1124 DstType))
1125 return;
1126
1127 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1128 bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
1129 unsigned SrcBits = SrcTy->getScalarSizeInBits();
1130 unsigned DstBits = DstTy->getScalarSizeInBits();
1131
1132 // Now, we do not need to emit the check in *all* of the cases.
1133 // We can avoid emitting it in some obvious cases where it would have been
1134 // dropped by the opt passes (instcombine) always anyways.
1135 // If it's a cast between effectively the same type, no check.
1136 // NOTE: this is *not* equivalent to checking the canonical types.
1137 if (SrcSigned == DstSigned && SrcBits == DstBits)
1138 return;
1139 // At least one of the values needs to have signed type.
1140 // If both are unsigned, then obviously, neither of them can be negative.
1141 if (!SrcSigned && !DstSigned)
1142 return;
1143 // If the conversion is to *larger* *signed* type, then no check is needed.
1144 // Because either sign-extension happens (so the sign will remain),
1145 // or zero-extension will happen (the sign bit will be zero.)
1146 if ((DstBits > SrcBits) && DstSigned)
1147 return;
1148 if (CGF.SanOpts.has(SanitizerKind::ImplicitSignedIntegerTruncation) &&
1149 (SrcBits > DstBits) && SrcSigned) {
1150 // If the signed integer truncation sanitizer is enabled,
1151 // and this is a truncation from signed type, then no check is needed.
1152 // Because here sign change check is interchangeable with truncation check.
1153 return;
1154 }
1155 // That's it. We can't rule out any more cases with the data we have.
1156
1157 CodeGenFunction::SanitizerScope SanScope(&CGF);
1158
1159 std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1160 std::pair<llvm::Value *, SanitizerMask>>
1161 Check;
1162
1163 // Each of these checks needs to return 'false' when an issue was detected.
1164 ImplicitConversionCheckKind CheckKind;
1165 llvm::SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks;
1166 // So we can 'and' all the checks together, and still get 'false',
1167 // if at least one of the checks detected an issue.
1168
1169 Check = EmitIntegerSignChangeCheckHelper(Src, SrcType, Dst, DstType, Builder);
1170 CheckKind = Check.first;
1171 Checks.emplace_back(Check.second);
1172
1173 if (CGF.SanOpts.has(SanitizerKind::ImplicitSignedIntegerTruncation) &&
1174 (SrcBits > DstBits) && !SrcSigned && DstSigned) {
1175 // If the signed integer truncation sanitizer was enabled,
1176 // and we are truncating from larger unsigned type to smaller signed type,
1177 // let's handle the case we skipped in that check.
1178 Check =
1179 EmitIntegerTruncationCheckHelper(Src, SrcType, Dst, DstType, Builder);
1180 CheckKind = ICCK_SignedIntegerTruncationOrSignChange;
1181 Checks.emplace_back(Check.second);
1182 // If the comparison result is 'i1 false', then the truncation was lossy.
1183 }
1184
1185 llvm::Constant *StaticArgs[] = {
1186 CGF.EmitCheckSourceLocation(Loc), CGF.EmitCheckTypeDescriptor(SrcType),
1187 CGF.EmitCheckTypeDescriptor(DstType),
1188 llvm::ConstantInt::get(Builder.getInt8Ty(), CheckKind)};
1189 // EmitCheck() will 'and' all the checks together.
1190 CGF.EmitCheck(Checks, SanitizerHandler::ImplicitConversion, StaticArgs,
1191 {Src, Dst});
1192 }
1193
1194 /// Emit a conversion from the specified type to the specified destination type,
1195 /// both of which are LLVM scalar types.
EmitScalarConversion(Value * Src,QualType SrcType,QualType DstType,SourceLocation Loc,ScalarConversionOpts Opts)1196 Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
1197 QualType DstType,
1198 SourceLocation Loc,
1199 ScalarConversionOpts Opts) {
1200 // All conversions involving fixed point types should be handled by the
1201 // EmitFixedPoint family functions. This is done to prevent bloating up this
1202 // function more, and although fixed point numbers are represented by
1203 // integers, we do not want to follow any logic that assumes they should be
1204 // treated as integers.
1205 // TODO(leonardchan): When necessary, add another if statement checking for
1206 // conversions to fixed point types from other types.
1207 if (SrcType->isFixedPointType()) {
1208 if (DstType->isBooleanType())
1209 // It is important that we check this before checking if the dest type is
1210 // an integer because booleans are technically integer types.
1211 // We do not need to check the padding bit on unsigned types if unsigned
1212 // padding is enabled because overflow into this bit is undefined
1213 // behavior.
1214 return Builder.CreateIsNotNull(Src, "tobool");
1215 if (DstType->isFixedPointType() || DstType->isIntegerType())
1216 return EmitFixedPointConversion(Src, SrcType, DstType, Loc);
1217
1218 llvm_unreachable(
1219 "Unhandled scalar conversion from a fixed point type to another type.");
1220 } else if (DstType->isFixedPointType()) {
1221 if (SrcType->isIntegerType())
1222 // This also includes converting booleans and enums to fixed point types.
1223 return EmitFixedPointConversion(Src, SrcType, DstType, Loc);
1224
1225 llvm_unreachable(
1226 "Unhandled scalar conversion to a fixed point type from another type.");
1227 }
1228
1229 QualType NoncanonicalSrcType = SrcType;
1230 QualType NoncanonicalDstType = DstType;
1231
1232 SrcType = CGF.getContext().getCanonicalType(SrcType);
1233 DstType = CGF.getContext().getCanonicalType(DstType);
1234 if (SrcType == DstType) return Src;
1235
1236 if (DstType->isVoidType()) return nullptr;
1237
1238 llvm::Value *OrigSrc = Src;
1239 QualType OrigSrcType = SrcType;
1240 llvm::Type *SrcTy = Src->getType();
1241
1242 // Handle conversions to bool first, they are special: comparisons against 0.
1243 if (DstType->isBooleanType())
1244 return EmitConversionToBool(Src, SrcType);
1245
1246 llvm::Type *DstTy = ConvertType(DstType);
1247
1248 // Cast from half through float if half isn't a native type.
1249 if (SrcType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
1250 // Cast to FP using the intrinsic if the half type itself isn't supported.
1251 if (DstTy->isFloatingPointTy()) {
1252 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics())
1253 return Builder.CreateCall(
1254 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16, DstTy),
1255 Src);
1256 } else {
1257 // Cast to other types through float, using either the intrinsic or FPExt,
1258 // depending on whether the half type itself is supported
1259 // (as opposed to operations on half, available with NativeHalfType).
1260 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
1261 Src = Builder.CreateCall(
1262 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16,
1263 CGF.CGM.FloatTy),
1264 Src);
1265 } else {
1266 Src = Builder.CreateFPExt(Src, CGF.CGM.FloatTy, "conv");
1267 }
1268 SrcType = CGF.getContext().FloatTy;
1269 SrcTy = CGF.FloatTy;
1270 }
1271 }
1272
1273 // Ignore conversions like int -> uint.
1274 if (SrcTy == DstTy) {
1275 if (Opts.EmitImplicitIntegerSignChangeChecks)
1276 EmitIntegerSignChangeCheck(Src, NoncanonicalSrcType, Src,
1277 NoncanonicalDstType, Loc);
1278
1279 return Src;
1280 }
1281
1282 // Handle pointer conversions next: pointers can only be converted to/from
1283 // other pointers and integers. Check for pointer types in terms of LLVM, as
1284 // some native types (like Obj-C id) may map to a pointer type.
1285 if (auto DstPT = dyn_cast<llvm::PointerType>(DstTy)) {
1286 // The source value may be an integer, or a pointer.
1287 if (isa<llvm::PointerType>(SrcTy))
1288 return Builder.CreateBitCast(Src, DstTy, "conv");
1289
1290 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
1291 // First, convert to the correct width so that we control the kind of
1292 // extension.
1293 llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DstPT);
1294 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
1295 llvm::Value* IntResult =
1296 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
1297 // Then, cast to pointer.
1298 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
1299 }
1300
1301 if (isa<llvm::PointerType>(SrcTy)) {
1302 // Must be an ptr to int cast.
1303 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
1304 return Builder.CreatePtrToInt(Src, DstTy, "conv");
1305 }
1306
1307 // A scalar can be splatted to an extended vector of the same element type
1308 if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
1309 // Sema should add casts to make sure that the source expression's type is
1310 // the same as the vector's element type (sans qualifiers)
1311 assert(DstType->castAs<ExtVectorType>()->getElementType().getTypePtr() ==
1312 SrcType.getTypePtr() &&
1313 "Splatted expr doesn't match with vector element type?");
1314
1315 // Splat the element across to all elements
1316 unsigned NumElements = cast<llvm::FixedVectorType>(DstTy)->getNumElements();
1317 return Builder.CreateVectorSplat(NumElements, Src, "splat");
1318 }
1319
1320 if (isa<llvm::VectorType>(SrcTy) || isa<llvm::VectorType>(DstTy)) {
1321 // Allow bitcast from vector to integer/fp of the same size.
1322 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1323 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1324 if (SrcSize == DstSize)
1325 return Builder.CreateBitCast(Src, DstTy, "conv");
1326
1327 // Conversions between vectors of different sizes are not allowed except
1328 // when vectors of half are involved. Operations on storage-only half
1329 // vectors require promoting half vector operands to float vectors and
1330 // truncating the result, which is either an int or float vector, to a
1331 // short or half vector.
1332
1333 // Source and destination are both expected to be vectors.
1334 llvm::Type *SrcElementTy = cast<llvm::VectorType>(SrcTy)->getElementType();
1335 llvm::Type *DstElementTy = cast<llvm::VectorType>(DstTy)->getElementType();
1336 (void)DstElementTy;
1337
1338 assert(((SrcElementTy->isIntegerTy() &&
1339 DstElementTy->isIntegerTy()) ||
1340 (SrcElementTy->isFloatingPointTy() &&
1341 DstElementTy->isFloatingPointTy())) &&
1342 "unexpected conversion between a floating-point vector and an "
1343 "integer vector");
1344
1345 // Truncate an i32 vector to an i16 vector.
1346 if (SrcElementTy->isIntegerTy())
1347 return Builder.CreateIntCast(Src, DstTy, false, "conv");
1348
1349 // Truncate a float vector to a half vector.
1350 if (SrcSize > DstSize)
1351 return Builder.CreateFPTrunc(Src, DstTy, "conv");
1352
1353 // Promote a half vector to a float vector.
1354 return Builder.CreateFPExt(Src, DstTy, "conv");
1355 }
1356
1357 // Finally, we have the arithmetic types: real int/float.
1358 Value *Res = nullptr;
1359 llvm::Type *ResTy = DstTy;
1360
1361 // An overflowing conversion has undefined behavior if either the source type
1362 // or the destination type is a floating-point type. However, we consider the
1363 // range of representable values for all floating-point types to be
1364 // [-inf,+inf], so no overflow can ever happen when the destination type is a
1365 // floating-point type.
1366 if (CGF.SanOpts.has(SanitizerKind::FloatCastOverflow) &&
1367 OrigSrcType->isFloatingType())
1368 EmitFloatConversionCheck(OrigSrc, OrigSrcType, Src, SrcType, DstType, DstTy,
1369 Loc);
1370
1371 // Cast to half through float if half isn't a native type.
1372 if (DstType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
1373 // Make sure we cast in a single step if from another FP type.
1374 if (SrcTy->isFloatingPointTy()) {
1375 // Use the intrinsic if the half type itself isn't supported
1376 // (as opposed to operations on half, available with NativeHalfType).
1377 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics())
1378 return Builder.CreateCall(
1379 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, SrcTy), Src);
1380 // If the half type is supported, just use an fptrunc.
1381 return Builder.CreateFPTrunc(Src, DstTy);
1382 }
1383 DstTy = CGF.FloatTy;
1384 }
1385
1386 if (isa<llvm::IntegerType>(SrcTy)) {
1387 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
1388 if (SrcType->isBooleanType() && Opts.TreatBooleanAsSigned) {
1389 InputSigned = true;
1390 }
1391 if (isa<llvm::IntegerType>(DstTy))
1392 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
1393 else if (InputSigned)
1394 Res = Builder.CreateSIToFP(Src, DstTy, "conv");
1395 else
1396 Res = Builder.CreateUIToFP(Src, DstTy, "conv");
1397 } else if (isa<llvm::IntegerType>(DstTy)) {
1398 assert(SrcTy->isFloatingPointTy() && "Unknown real conversion");
1399 if (DstType->isSignedIntegerOrEnumerationType())
1400 Res = Builder.CreateFPToSI(Src, DstTy, "conv");
1401 else
1402 Res = Builder.CreateFPToUI(Src, DstTy, "conv");
1403 } else {
1404 assert(SrcTy->isFloatingPointTy() && DstTy->isFloatingPointTy() &&
1405 "Unknown real conversion");
1406 if (DstTy->getTypeID() < SrcTy->getTypeID())
1407 Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
1408 else
1409 Res = Builder.CreateFPExt(Src, DstTy, "conv");
1410 }
1411
1412 if (DstTy != ResTy) {
1413 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
1414 assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion");
1415 Res = Builder.CreateCall(
1416 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, CGF.CGM.FloatTy),
1417 Res);
1418 } else {
1419 Res = Builder.CreateFPTrunc(Res, ResTy, "conv");
1420 }
1421 }
1422
1423 if (Opts.EmitImplicitIntegerTruncationChecks)
1424 EmitIntegerTruncationCheck(Src, NoncanonicalSrcType, Res,
1425 NoncanonicalDstType, Loc);
1426
1427 if (Opts.EmitImplicitIntegerSignChangeChecks)
1428 EmitIntegerSignChangeCheck(Src, NoncanonicalSrcType, Res,
1429 NoncanonicalDstType, Loc);
1430
1431 return Res;
1432 }
1433
EmitFixedPointConversion(Value * Src,QualType SrcTy,QualType DstTy,SourceLocation Loc)1434 Value *ScalarExprEmitter::EmitFixedPointConversion(Value *Src, QualType SrcTy,
1435 QualType DstTy,
1436 SourceLocation Loc) {
1437 auto SrcFPSema = CGF.getContext().getFixedPointSemantics(SrcTy);
1438 auto DstFPSema = CGF.getContext().getFixedPointSemantics(DstTy);
1439 llvm::FixedPointBuilder<CGBuilderTy> FPBuilder(Builder);
1440 llvm::Value *Result;
1441 if (DstTy->isIntegerType())
1442 Result = FPBuilder.CreateFixedToInteger(Src, SrcFPSema,
1443 DstFPSema.getWidth(),
1444 DstFPSema.isSigned());
1445 else if (SrcTy->isIntegerType())
1446 Result = FPBuilder.CreateIntegerToFixed(Src, SrcFPSema.isSigned(),
1447 DstFPSema);
1448 else
1449 Result = FPBuilder.CreateFixedToFixed(Src, SrcFPSema, DstFPSema);
1450 return Result;
1451 }
1452
1453 /// Emit a conversion from the specified complex type to the specified
1454 /// destination type, where the destination type is an LLVM scalar type.
EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,QualType SrcTy,QualType DstTy,SourceLocation Loc)1455 Value *ScalarExprEmitter::EmitComplexToScalarConversion(
1456 CodeGenFunction::ComplexPairTy Src, QualType SrcTy, QualType DstTy,
1457 SourceLocation Loc) {
1458 // Get the source element type.
1459 SrcTy = SrcTy->castAs<ComplexType>()->getElementType();
1460
1461 // Handle conversions to bool first, they are special: comparisons against 0.
1462 if (DstTy->isBooleanType()) {
1463 // Complex != 0 -> (Real != 0) | (Imag != 0)
1464 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy, Loc);
1465 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy, Loc);
1466 return Builder.CreateOr(Src.first, Src.second, "tobool");
1467 }
1468
1469 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
1470 // the imaginary part of the complex value is discarded and the value of the
1471 // real part is converted according to the conversion rules for the
1472 // corresponding real type.
1473 return EmitScalarConversion(Src.first, SrcTy, DstTy, Loc);
1474 }
1475
EmitNullValue(QualType Ty)1476 Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
1477 return CGF.EmitFromMemory(CGF.CGM.EmitNullConstant(Ty), Ty);
1478 }
1479
1480 /// Emit a sanitization check for the given "binary" operation (which
1481 /// might actually be a unary increment which has been lowered to a binary
1482 /// operation). The check passes if all values in \p Checks (which are \c i1),
1483 /// are \c true.
EmitBinOpCheck(ArrayRef<std::pair<Value *,SanitizerMask>> Checks,const BinOpInfo & Info)1484 void ScalarExprEmitter::EmitBinOpCheck(
1485 ArrayRef<std::pair<Value *, SanitizerMask>> Checks, const BinOpInfo &Info) {
1486 assert(CGF.IsSanitizerScope);
1487 SanitizerHandler Check;
1488 SmallVector<llvm::Constant *, 4> StaticData;
1489 SmallVector<llvm::Value *, 2> DynamicData;
1490
1491 BinaryOperatorKind Opcode = Info.Opcode;
1492 if (BinaryOperator::isCompoundAssignmentOp(Opcode))
1493 Opcode = BinaryOperator::getOpForCompoundAssignment(Opcode);
1494
1495 StaticData.push_back(CGF.EmitCheckSourceLocation(Info.E->getExprLoc()));
1496 const UnaryOperator *UO = dyn_cast<UnaryOperator>(Info.E);
1497 if (UO && UO->getOpcode() == UO_Minus) {
1498 Check = SanitizerHandler::NegateOverflow;
1499 StaticData.push_back(CGF.EmitCheckTypeDescriptor(UO->getType()));
1500 DynamicData.push_back(Info.RHS);
1501 } else {
1502 if (BinaryOperator::isShiftOp(Opcode)) {
1503 // Shift LHS negative or too large, or RHS out of bounds.
1504 Check = SanitizerHandler::ShiftOutOfBounds;
1505 const BinaryOperator *BO = cast<BinaryOperator>(Info.E);
1506 StaticData.push_back(
1507 CGF.EmitCheckTypeDescriptor(BO->getLHS()->getType()));
1508 StaticData.push_back(
1509 CGF.EmitCheckTypeDescriptor(BO->getRHS()->getType()));
1510 } else if (Opcode == BO_Div || Opcode == BO_Rem) {
1511 // Divide or modulo by zero, or signed overflow (eg INT_MAX / -1).
1512 Check = SanitizerHandler::DivremOverflow;
1513 StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
1514 } else {
1515 // Arithmetic overflow (+, -, *).
1516 switch (Opcode) {
1517 case BO_Add: Check = SanitizerHandler::AddOverflow; break;
1518 case BO_Sub: Check = SanitizerHandler::SubOverflow; break;
1519 case BO_Mul: Check = SanitizerHandler::MulOverflow; break;
1520 default: llvm_unreachable("unexpected opcode for bin op check");
1521 }
1522 StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
1523 }
1524 DynamicData.push_back(Info.LHS);
1525 DynamicData.push_back(Info.RHS);
1526 }
1527
1528 CGF.EmitCheck(Checks, Check, StaticData, DynamicData);
1529 }
1530
1531 //===----------------------------------------------------------------------===//
1532 // Visitor Methods
1533 //===----------------------------------------------------------------------===//
1534
VisitExpr(Expr * E)1535 Value *ScalarExprEmitter::VisitExpr(Expr *E) {
1536 CGF.ErrorUnsupported(E, "scalar expression");
1537 if (E->getType()->isVoidType())
1538 return nullptr;
1539 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
1540 }
1541
VisitShuffleVectorExpr(ShuffleVectorExpr * E)1542 Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
1543 // Vector Mask Case
1544 if (E->getNumSubExprs() == 2) {
1545 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
1546 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
1547 Value *Mask;
1548
1549 auto *LTy = cast<llvm::FixedVectorType>(LHS->getType());
1550 unsigned LHSElts = LTy->getNumElements();
1551
1552 Mask = RHS;
1553
1554 auto *MTy = cast<llvm::FixedVectorType>(Mask->getType());
1555
1556 // Mask off the high bits of each shuffle index.
1557 Value *MaskBits =
1558 llvm::ConstantInt::get(MTy, llvm::NextPowerOf2(LHSElts - 1) - 1);
1559 Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
1560
1561 // newv = undef
1562 // mask = mask & maskbits
1563 // for each elt
1564 // n = extract mask i
1565 // x = extract val n
1566 // newv = insert newv, x, i
1567 auto *RTy = llvm::FixedVectorType::get(LTy->getElementType(),
1568 MTy->getNumElements());
1569 Value* NewV = llvm::UndefValue::get(RTy);
1570 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
1571 Value *IIndx = llvm::ConstantInt::get(CGF.SizeTy, i);
1572 Value *Indx = Builder.CreateExtractElement(Mask, IIndx, "shuf_idx");
1573
1574 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
1575 NewV = Builder.CreateInsertElement(NewV, VExt, IIndx, "shuf_ins");
1576 }
1577 return NewV;
1578 }
1579
1580 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
1581 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
1582
1583 SmallVector<int, 32> Indices;
1584 for (unsigned i = 2; i < E->getNumSubExprs(); ++i) {
1585 llvm::APSInt Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2);
1586 // Check for -1 and output it as undef in the IR.
1587 if (Idx.isSigned() && Idx.isAllOnesValue())
1588 Indices.push_back(-1);
1589 else
1590 Indices.push_back(Idx.getZExtValue());
1591 }
1592
1593 return Builder.CreateShuffleVector(V1, V2, Indices, "shuffle");
1594 }
1595
VisitConvertVectorExpr(ConvertVectorExpr * E)1596 Value *ScalarExprEmitter::VisitConvertVectorExpr(ConvertVectorExpr *E) {
1597 QualType SrcType = E->getSrcExpr()->getType(),
1598 DstType = E->getType();
1599
1600 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
1601
1602 SrcType = CGF.getContext().getCanonicalType(SrcType);
1603 DstType = CGF.getContext().getCanonicalType(DstType);
1604 if (SrcType == DstType) return Src;
1605
1606 assert(SrcType->isVectorType() &&
1607 "ConvertVector source type must be a vector");
1608 assert(DstType->isVectorType() &&
1609 "ConvertVector destination type must be a vector");
1610
1611 llvm::Type *SrcTy = Src->getType();
1612 llvm::Type *DstTy = ConvertType(DstType);
1613
1614 // Ignore conversions like int -> uint.
1615 if (SrcTy == DstTy)
1616 return Src;
1617
1618 QualType SrcEltType = SrcType->castAs<VectorType>()->getElementType(),
1619 DstEltType = DstType->castAs<VectorType>()->getElementType();
1620
1621 assert(SrcTy->isVectorTy() &&
1622 "ConvertVector source IR type must be a vector");
1623 assert(DstTy->isVectorTy() &&
1624 "ConvertVector destination IR type must be a vector");
1625
1626 llvm::Type *SrcEltTy = cast<llvm::VectorType>(SrcTy)->getElementType(),
1627 *DstEltTy = cast<llvm::VectorType>(DstTy)->getElementType();
1628
1629 if (DstEltType->isBooleanType()) {
1630 assert((SrcEltTy->isFloatingPointTy() ||
1631 isa<llvm::IntegerType>(SrcEltTy)) && "Unknown boolean conversion");
1632
1633 llvm::Value *Zero = llvm::Constant::getNullValue(SrcTy);
1634 if (SrcEltTy->isFloatingPointTy()) {
1635 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
1636 } else {
1637 return Builder.CreateICmpNE(Src, Zero, "tobool");
1638 }
1639 }
1640
1641 // We have the arithmetic types: real int/float.
1642 Value *Res = nullptr;
1643
1644 if (isa<llvm::IntegerType>(SrcEltTy)) {
1645 bool InputSigned = SrcEltType->isSignedIntegerOrEnumerationType();
1646 if (isa<llvm::IntegerType>(DstEltTy))
1647 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
1648 else if (InputSigned)
1649 Res = Builder.CreateSIToFP(Src, DstTy, "conv");
1650 else
1651 Res = Builder.CreateUIToFP(Src, DstTy, "conv");
1652 } else if (isa<llvm::IntegerType>(DstEltTy)) {
1653 assert(SrcEltTy->isFloatingPointTy() && "Unknown real conversion");
1654 if (DstEltType->isSignedIntegerOrEnumerationType())
1655 Res = Builder.CreateFPToSI(Src, DstTy, "conv");
1656 else
1657 Res = Builder.CreateFPToUI(Src, DstTy, "conv");
1658 } else {
1659 assert(SrcEltTy->isFloatingPointTy() && DstEltTy->isFloatingPointTy() &&
1660 "Unknown real conversion");
1661 if (DstEltTy->getTypeID() < SrcEltTy->getTypeID())
1662 Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
1663 else
1664 Res = Builder.CreateFPExt(Src, DstTy, "conv");
1665 }
1666
1667 return Res;
1668 }
1669
VisitMemberExpr(MemberExpr * E)1670 Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
1671 if (CodeGenFunction::ConstantEmission Constant = CGF.tryEmitAsConstant(E)) {
1672 CGF.EmitIgnoredExpr(E->getBase());
1673 return CGF.emitScalarConstant(Constant, E);
1674 } else {
1675 Expr::EvalResult Result;
1676 if (E->EvaluateAsInt(Result, CGF.getContext(), Expr::SE_AllowSideEffects)) {
1677 llvm::APSInt Value = Result.Val.getInt();
1678 CGF.EmitIgnoredExpr(E->getBase());
1679 return Builder.getInt(Value);
1680 }
1681 }
1682
1683 return EmitLoadOfLValue(E);
1684 }
1685
VisitArraySubscriptExpr(ArraySubscriptExpr * E)1686 Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
1687 TestAndClearIgnoreResultAssign();
1688
1689 // Emit subscript expressions in rvalue context's. For most cases, this just
1690 // loads the lvalue formed by the subscript expr. However, we have to be
1691 // careful, because the base of a vector subscript is occasionally an rvalue,
1692 // so we can't get it as an lvalue.
1693 if (!E->getBase()->getType()->isVectorType())
1694 return EmitLoadOfLValue(E);
1695
1696 // Handle the vector case. The base must be a vector, the index must be an
1697 // integer value.
1698 Value *Base = Visit(E->getBase());
1699 Value *Idx = Visit(E->getIdx());
1700 QualType IdxTy = E->getIdx()->getType();
1701
1702 if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
1703 CGF.EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, /*Accessed*/true);
1704
1705 return Builder.CreateExtractElement(Base, Idx, "vecext");
1706 }
1707
VisitMatrixSubscriptExpr(MatrixSubscriptExpr * E)1708 Value *ScalarExprEmitter::VisitMatrixSubscriptExpr(MatrixSubscriptExpr *E) {
1709 TestAndClearIgnoreResultAssign();
1710
1711 // Handle the vector case. The base must be a vector, the index must be an
1712 // integer value.
1713 Value *RowIdx = Visit(E->getRowIdx());
1714 Value *ColumnIdx = Visit(E->getColumnIdx());
1715 Value *Matrix = Visit(E->getBase());
1716
1717 // TODO: Should we emit bounds checks with SanitizerKind::ArrayBounds?
1718 llvm::MatrixBuilder<CGBuilderTy> MB(Builder);
1719 return MB.CreateExtractElement(
1720 Matrix, RowIdx, ColumnIdx,
1721 E->getBase()->getType()->getAs<ConstantMatrixType>()->getNumRows());
1722 }
1723
getMaskElt(llvm::ShuffleVectorInst * SVI,unsigned Idx,unsigned Off)1724 static int getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
1725 unsigned Off) {
1726 int MV = SVI->getMaskValue(Idx);
1727 if (MV == -1)
1728 return -1;
1729 return Off + MV;
1730 }
1731
getAsInt32(llvm::ConstantInt * C,llvm::Type * I32Ty)1732 static int getAsInt32(llvm::ConstantInt *C, llvm::Type *I32Ty) {
1733 assert(llvm::ConstantInt::isValueValidForType(I32Ty, C->getZExtValue()) &&
1734 "Index operand too large for shufflevector mask!");
1735 return C->getZExtValue();
1736 }
1737
VisitInitListExpr(InitListExpr * E)1738 Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
1739 bool Ignore = TestAndClearIgnoreResultAssign();
1740 (void)Ignore;
1741 assert (Ignore == false && "init list ignored");
1742 unsigned NumInitElements = E->getNumInits();
1743
1744 if (E->hadArrayRangeDesignator())
1745 CGF.ErrorUnsupported(E, "GNU array range designator extension");
1746
1747 llvm::VectorType *VType =
1748 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
1749
1750 if (!VType) {
1751 if (NumInitElements == 0) {
1752 // C++11 value-initialization for the scalar.
1753 return EmitNullValue(E->getType());
1754 }
1755 // We have a scalar in braces. Just use the first element.
1756 return Visit(E->getInit(0));
1757 }
1758
1759 unsigned ResElts = cast<llvm::FixedVectorType>(VType)->getNumElements();
1760
1761 // Loop over initializers collecting the Value for each, and remembering
1762 // whether the source was swizzle (ExtVectorElementExpr). This will allow
1763 // us to fold the shuffle for the swizzle into the shuffle for the vector
1764 // initializer, since LLVM optimizers generally do not want to touch
1765 // shuffles.
1766 unsigned CurIdx = 0;
1767 bool VIsUndefShuffle = false;
1768 llvm::Value *V = llvm::UndefValue::get(VType);
1769 for (unsigned i = 0; i != NumInitElements; ++i) {
1770 Expr *IE = E->getInit(i);
1771 Value *Init = Visit(IE);
1772 SmallVector<int, 16> Args;
1773
1774 llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
1775
1776 // Handle scalar elements. If the scalar initializer is actually one
1777 // element of a different vector of the same width, use shuffle instead of
1778 // extract+insert.
1779 if (!VVT) {
1780 if (isa<ExtVectorElementExpr>(IE)) {
1781 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
1782
1783 if (cast<llvm::FixedVectorType>(EI->getVectorOperandType())
1784 ->getNumElements() == ResElts) {
1785 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
1786 Value *LHS = nullptr, *RHS = nullptr;
1787 if (CurIdx == 0) {
1788 // insert into undef -> shuffle (src, undef)
1789 // shufflemask must use an i32
1790 Args.push_back(getAsInt32(C, CGF.Int32Ty));
1791 Args.resize(ResElts, -1);
1792
1793 LHS = EI->getVectorOperand();
1794 RHS = V;
1795 VIsUndefShuffle = true;
1796 } else if (VIsUndefShuffle) {
1797 // insert into undefshuffle && size match -> shuffle (v, src)
1798 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
1799 for (unsigned j = 0; j != CurIdx; ++j)
1800 Args.push_back(getMaskElt(SVV, j, 0));
1801 Args.push_back(ResElts + C->getZExtValue());
1802 Args.resize(ResElts, -1);
1803
1804 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1805 RHS = EI->getVectorOperand();
1806 VIsUndefShuffle = false;
1807 }
1808 if (!Args.empty()) {
1809 V = Builder.CreateShuffleVector(LHS, RHS, Args);
1810 ++CurIdx;
1811 continue;
1812 }
1813 }
1814 }
1815 V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx),
1816 "vecinit");
1817 VIsUndefShuffle = false;
1818 ++CurIdx;
1819 continue;
1820 }
1821
1822 unsigned InitElts = cast<llvm::FixedVectorType>(VVT)->getNumElements();
1823
1824 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
1825 // input is the same width as the vector being constructed, generate an
1826 // optimized shuffle of the swizzle input into the result.
1827 unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
1828 if (isa<ExtVectorElementExpr>(IE)) {
1829 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
1830 Value *SVOp = SVI->getOperand(0);
1831 auto *OpTy = cast<llvm::FixedVectorType>(SVOp->getType());
1832
1833 if (OpTy->getNumElements() == ResElts) {
1834 for (unsigned j = 0; j != CurIdx; ++j) {
1835 // If the current vector initializer is a shuffle with undef, merge
1836 // this shuffle directly into it.
1837 if (VIsUndefShuffle) {
1838 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0));
1839 } else {
1840 Args.push_back(j);
1841 }
1842 }
1843 for (unsigned j = 0, je = InitElts; j != je; ++j)
1844 Args.push_back(getMaskElt(SVI, j, Offset));
1845 Args.resize(ResElts, -1);
1846
1847 if (VIsUndefShuffle)
1848 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1849
1850 Init = SVOp;
1851 }
1852 }
1853
1854 // Extend init to result vector length, and then shuffle its contribution
1855 // to the vector initializer into V.
1856 if (Args.empty()) {
1857 for (unsigned j = 0; j != InitElts; ++j)
1858 Args.push_back(j);
1859 Args.resize(ResElts, -1);
1860 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT), Args,
1861 "vext");
1862
1863 Args.clear();
1864 for (unsigned j = 0; j != CurIdx; ++j)
1865 Args.push_back(j);
1866 for (unsigned j = 0; j != InitElts; ++j)
1867 Args.push_back(j + Offset);
1868 Args.resize(ResElts, -1);
1869 }
1870
1871 // If V is undef, make sure it ends up on the RHS of the shuffle to aid
1872 // merging subsequent shuffles into this one.
1873 if (CurIdx == 0)
1874 std::swap(V, Init);
1875 V = Builder.CreateShuffleVector(V, Init, Args, "vecinit");
1876 VIsUndefShuffle = isa<llvm::UndefValue>(Init);
1877 CurIdx += InitElts;
1878 }
1879
1880 // FIXME: evaluate codegen vs. shuffling against constant null vector.
1881 // Emit remaining default initializers.
1882 llvm::Type *EltTy = VType->getElementType();
1883
1884 // Emit remaining default initializers
1885 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
1886 Value *Idx = Builder.getInt32(CurIdx);
1887 llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
1888 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
1889 }
1890 return V;
1891 }
1892
ShouldNullCheckClassCastValue(const CastExpr * CE)1893 bool CodeGenFunction::ShouldNullCheckClassCastValue(const CastExpr *CE) {
1894 const Expr *E = CE->getSubExpr();
1895
1896 if (CE->getCastKind() == CK_UncheckedDerivedToBase)
1897 return false;
1898
1899 if (isa<CXXThisExpr>(E->IgnoreParens())) {
1900 // We always assume that 'this' is never null.
1901 return false;
1902 }
1903
1904 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
1905 // And that glvalue casts are never null.
1906 if (ICE->getValueKind() != VK_RValue)
1907 return false;
1908 }
1909
1910 return true;
1911 }
1912
1913 // VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
1914 // have to handle a more broad range of conversions than explicit casts, as they
1915 // handle things like function to ptr-to-function decay etc.
VisitCastExpr(CastExpr * CE)1916 Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
1917 Expr *E = CE->getSubExpr();
1918 QualType DestTy = CE->getType();
1919 CastKind Kind = CE->getCastKind();
1920
1921 // These cases are generally not written to ignore the result of
1922 // evaluating their sub-expressions, so we clear this now.
1923 bool Ignored = TestAndClearIgnoreResultAssign();
1924
1925 // Since almost all cast kinds apply to scalars, this switch doesn't have
1926 // a default case, so the compiler will warn on a missing case. The cases
1927 // are in the same order as in the CastKind enum.
1928 switch (Kind) {
1929 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
1930 case CK_BuiltinFnToFnPtr:
1931 llvm_unreachable("builtin functions are handled elsewhere");
1932
1933 case CK_LValueBitCast:
1934 case CK_ObjCObjectLValueCast: {
1935 Address Addr = EmitLValue(E).getAddress(CGF);
1936 Addr = Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(DestTy));
1937 LValue LV = CGF.MakeAddrLValue(Addr, DestTy);
1938 return EmitLoadOfLValue(LV, CE->getExprLoc());
1939 }
1940
1941 case CK_LValueToRValueBitCast: {
1942 LValue SourceLVal = CGF.EmitLValue(E);
1943 Address Addr = Builder.CreateElementBitCast(SourceLVal.getAddress(CGF),
1944 CGF.ConvertTypeForMem(DestTy));
1945 LValue DestLV = CGF.MakeAddrLValue(Addr, DestTy);
1946 DestLV.setTBAAInfo(TBAAAccessInfo::getMayAliasInfo());
1947 return EmitLoadOfLValue(DestLV, CE->getExprLoc());
1948 }
1949
1950 case CK_CPointerToObjCPointerCast:
1951 case CK_BlockPointerToObjCPointerCast:
1952 case CK_AnyPointerToBlockPointerCast:
1953 case CK_BitCast: {
1954 Value *Src = Visit(const_cast<Expr*>(E));
1955 llvm::Type *SrcTy = Src->getType();
1956 llvm::Type *DstTy = ConvertType(DestTy);
1957 if (SrcTy->isPtrOrPtrVectorTy() && DstTy->isPtrOrPtrVectorTy() &&
1958 SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()) {
1959 llvm_unreachable("wrong cast for pointers in different address spaces"
1960 "(must be an address space cast)!");
1961 }
1962
1963 if (CGF.SanOpts.has(SanitizerKind::CFIUnrelatedCast)) {
1964 if (auto PT = DestTy->getAs<PointerType>())
1965 CGF.EmitVTablePtrCheckForCast(PT->getPointeeType(), Src,
1966 /*MayBeNull=*/true,
1967 CodeGenFunction::CFITCK_UnrelatedCast,
1968 CE->getBeginLoc());
1969 }
1970
1971 if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
1972 const QualType SrcType = E->getType();
1973
1974 if (SrcType.mayBeNotDynamicClass() && DestTy.mayBeDynamicClass()) {
1975 // Casting to pointer that could carry dynamic information (provided by
1976 // invariant.group) requires launder.
1977 Src = Builder.CreateLaunderInvariantGroup(Src);
1978 } else if (SrcType.mayBeDynamicClass() && DestTy.mayBeNotDynamicClass()) {
1979 // Casting to pointer that does not carry dynamic information (provided
1980 // by invariant.group) requires stripping it. Note that we don't do it
1981 // if the source could not be dynamic type and destination could be
1982 // dynamic because dynamic information is already laundered. It is
1983 // because launder(strip(src)) == launder(src), so there is no need to
1984 // add extra strip before launder.
1985 Src = Builder.CreateStripInvariantGroup(Src);
1986 }
1987 }
1988
1989 // Update heapallocsite metadata when there is an explicit pointer cast.
1990 if (auto *CI = dyn_cast<llvm::CallBase>(Src)) {
1991 if (CI->getMetadata("heapallocsite") && isa<ExplicitCastExpr>(CE)) {
1992 QualType PointeeType = DestTy->getPointeeType();
1993 if (!PointeeType.isNull())
1994 CGF.getDebugInfo()->addHeapAllocSiteMetadata(CI, PointeeType,
1995 CE->getExprLoc());
1996 }
1997 }
1998
1999 // Perform VLAT <-> VLST bitcast through memory.
2000 if ((isa<llvm::FixedVectorType>(SrcTy) &&
2001 isa<llvm::ScalableVectorType>(DstTy)) ||
2002 (isa<llvm::ScalableVectorType>(SrcTy) &&
2003 isa<llvm::FixedVectorType>(DstTy))) {
2004 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
2005 // Call expressions can't have a scalar return unless the return type
2006 // is a reference type so an lvalue can't be emitted. Create a temp
2007 // alloca to store the call, bitcast the address then load.
2008 QualType RetTy = CE->getCallReturnType(CGF.getContext());
2009 Address Addr =
2010 CGF.CreateDefaultAlignTempAlloca(SrcTy, "saved-call-rvalue");
2011 LValue LV = CGF.MakeAddrLValue(Addr, RetTy);
2012 CGF.EmitStoreOfScalar(Src, LV);
2013 Addr = Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(DestTy),
2014 "castFixedSve");
2015 LValue DestLV = CGF.MakeAddrLValue(Addr, DestTy);
2016 DestLV.setTBAAInfo(TBAAAccessInfo::getMayAliasInfo());
2017 return EmitLoadOfLValue(DestLV, CE->getExprLoc());
2018 }
2019
2020 Address Addr = EmitLValue(E).getAddress(CGF);
2021 Addr = Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(DestTy));
2022 LValue DestLV = CGF.MakeAddrLValue(Addr, DestTy);
2023 DestLV.setTBAAInfo(TBAAAccessInfo::getMayAliasInfo());
2024 return EmitLoadOfLValue(DestLV, CE->getExprLoc());
2025 }
2026
2027 return Builder.CreateBitCast(Src, DstTy);
2028 }
2029 case CK_AddressSpaceConversion: {
2030 Expr::EvalResult Result;
2031 if (E->EvaluateAsRValue(Result, CGF.getContext()) &&
2032 Result.Val.isNullPointer()) {
2033 // If E has side effect, it is emitted even if its final result is a
2034 // null pointer. In that case, a DCE pass should be able to
2035 // eliminate the useless instructions emitted during translating E.
2036 if (Result.HasSideEffects)
2037 Visit(E);
2038 return CGF.CGM.getNullPointer(cast<llvm::PointerType>(
2039 ConvertType(DestTy)), DestTy);
2040 }
2041 // Since target may map different address spaces in AST to the same address
2042 // space, an address space conversion may end up as a bitcast.
2043 return CGF.CGM.getTargetCodeGenInfo().performAddrSpaceCast(
2044 CGF, Visit(E), E->getType()->getPointeeType().getAddressSpace(),
2045 DestTy->getPointeeType().getAddressSpace(), ConvertType(DestTy));
2046 }
2047 case CK_AtomicToNonAtomic:
2048 case CK_NonAtomicToAtomic:
2049 case CK_NoOp:
2050 case CK_UserDefinedConversion:
2051 return Visit(const_cast<Expr*>(E));
2052
2053 case CK_BaseToDerived: {
2054 const CXXRecordDecl *DerivedClassDecl = DestTy->getPointeeCXXRecordDecl();
2055 assert(DerivedClassDecl && "BaseToDerived arg isn't a C++ object pointer!");
2056
2057 Address Base = CGF.EmitPointerWithAlignment(E);
2058 Address Derived =
2059 CGF.GetAddressOfDerivedClass(Base, DerivedClassDecl,
2060 CE->path_begin(), CE->path_end(),
2061 CGF.ShouldNullCheckClassCastValue(CE));
2062
2063 // C++11 [expr.static.cast]p11: Behavior is undefined if a downcast is
2064 // performed and the object is not of the derived type.
2065 if (CGF.sanitizePerformTypeCheck())
2066 CGF.EmitTypeCheck(CodeGenFunction::TCK_DowncastPointer, CE->getExprLoc(),
2067 Derived.getPointer(), DestTy->getPointeeType());
2068
2069 if (CGF.SanOpts.has(SanitizerKind::CFIDerivedCast))
2070 CGF.EmitVTablePtrCheckForCast(
2071 DestTy->getPointeeType(), Derived.getPointer(),
2072 /*MayBeNull=*/true, CodeGenFunction::CFITCK_DerivedCast,
2073 CE->getBeginLoc());
2074
2075 return Derived.getPointer();
2076 }
2077 case CK_UncheckedDerivedToBase:
2078 case CK_DerivedToBase: {
2079 // The EmitPointerWithAlignment path does this fine; just discard
2080 // the alignment.
2081 return CGF.EmitPointerWithAlignment(CE).getPointer();
2082 }
2083
2084 case CK_Dynamic: {
2085 Address V = CGF.EmitPointerWithAlignment(E);
2086 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
2087 return CGF.EmitDynamicCast(V, DCE);
2088 }
2089
2090 case CK_ArrayToPointerDecay:
2091 return CGF.EmitArrayToPointerDecay(E).getPointer();
2092 case CK_FunctionToPointerDecay:
2093 return EmitLValue(E).getPointer(CGF);
2094
2095 case CK_NullToPointer:
2096 if (MustVisitNullValue(E))
2097 CGF.EmitIgnoredExpr(E);
2098
2099 return CGF.CGM.getNullPointer(cast<llvm::PointerType>(ConvertType(DestTy)),
2100 DestTy);
2101
2102 case CK_NullToMemberPointer: {
2103 if (MustVisitNullValue(E))
2104 CGF.EmitIgnoredExpr(E);
2105
2106 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
2107 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
2108 }
2109
2110 case CK_ReinterpretMemberPointer:
2111 case CK_BaseToDerivedMemberPointer:
2112 case CK_DerivedToBaseMemberPointer: {
2113 Value *Src = Visit(E);
2114
2115 // Note that the AST doesn't distinguish between checked and
2116 // unchecked member pointer conversions, so we always have to
2117 // implement checked conversions here. This is inefficient when
2118 // actual control flow may be required in order to perform the
2119 // check, which it is for data member pointers (but not member
2120 // function pointers on Itanium and ARM).
2121 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
2122 }
2123
2124 case CK_ARCProduceObject:
2125 return CGF.EmitARCRetainScalarExpr(E);
2126 case CK_ARCConsumeObject:
2127 return CGF.EmitObjCConsumeObject(E->getType(), Visit(E));
2128 case CK_ARCReclaimReturnedObject:
2129 return CGF.EmitARCReclaimReturnedObject(E, /*allowUnsafe*/ Ignored);
2130 case CK_ARCExtendBlockObject:
2131 return CGF.EmitARCExtendBlockObject(E);
2132
2133 case CK_CopyAndAutoreleaseBlockObject:
2134 return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType());
2135
2136 case CK_FloatingRealToComplex:
2137 case CK_FloatingComplexCast:
2138 case CK_IntegralRealToComplex:
2139 case CK_IntegralComplexCast:
2140 case CK_IntegralComplexToFloatingComplex:
2141 case CK_FloatingComplexToIntegralComplex:
2142 case CK_ConstructorConversion:
2143 case CK_ToUnion:
2144 llvm_unreachable("scalar cast to non-scalar value");
2145
2146 case CK_LValueToRValue:
2147 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
2148 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
2149 return Visit(const_cast<Expr*>(E));
2150
2151 case CK_IntegralToPointer: {
2152 Value *Src = Visit(const_cast<Expr*>(E));
2153
2154 // First, convert to the correct width so that we control the kind of
2155 // extension.
2156 auto DestLLVMTy = ConvertType(DestTy);
2157 llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DestLLVMTy);
2158 bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
2159 llvm::Value* IntResult =
2160 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
2161
2162 auto *IntToPtr = Builder.CreateIntToPtr(IntResult, DestLLVMTy);
2163
2164 if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
2165 // Going from integer to pointer that could be dynamic requires reloading
2166 // dynamic information from invariant.group.
2167 if (DestTy.mayBeDynamicClass())
2168 IntToPtr = Builder.CreateLaunderInvariantGroup(IntToPtr);
2169 }
2170 return IntToPtr;
2171 }
2172 case CK_PointerToIntegral: {
2173 assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
2174 auto *PtrExpr = Visit(E);
2175
2176 if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
2177 const QualType SrcType = E->getType();
2178
2179 // Casting to integer requires stripping dynamic information as it does
2180 // not carries it.
2181 if (SrcType.mayBeDynamicClass())
2182 PtrExpr = Builder.CreateStripInvariantGroup(PtrExpr);
2183 }
2184
2185 return Builder.CreatePtrToInt(PtrExpr, ConvertType(DestTy));
2186 }
2187 case CK_ToVoid: {
2188 CGF.EmitIgnoredExpr(E);
2189 return nullptr;
2190 }
2191 case CK_VectorSplat: {
2192 llvm::Type *DstTy = ConvertType(DestTy);
2193 Value *Elt = Visit(const_cast<Expr*>(E));
2194 // Splat the element across to all elements
2195 unsigned NumElements = cast<llvm::FixedVectorType>(DstTy)->getNumElements();
2196 return Builder.CreateVectorSplat(NumElements, Elt, "splat");
2197 }
2198
2199 case CK_FixedPointCast:
2200 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2201 CE->getExprLoc());
2202
2203 case CK_FixedPointToBoolean:
2204 assert(E->getType()->isFixedPointType() &&
2205 "Expected src type to be fixed point type");
2206 assert(DestTy->isBooleanType() && "Expected dest type to be boolean type");
2207 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2208 CE->getExprLoc());
2209
2210 case CK_FixedPointToIntegral:
2211 assert(E->getType()->isFixedPointType() &&
2212 "Expected src type to be fixed point type");
2213 assert(DestTy->isIntegerType() && "Expected dest type to be an integer");
2214 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2215 CE->getExprLoc());
2216
2217 case CK_IntegralToFixedPoint:
2218 assert(E->getType()->isIntegerType() &&
2219 "Expected src type to be an integer");
2220 assert(DestTy->isFixedPointType() &&
2221 "Expected dest type to be fixed point type");
2222 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2223 CE->getExprLoc());
2224
2225 case CK_IntegralCast: {
2226 ScalarConversionOpts Opts;
2227 if (auto *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
2228 if (!ICE->isPartOfExplicitCast())
2229 Opts = ScalarConversionOpts(CGF.SanOpts);
2230 }
2231 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2232 CE->getExprLoc(), Opts);
2233 }
2234 case CK_IntegralToFloating:
2235 case CK_FloatingToIntegral:
2236 case CK_FloatingCast:
2237 case CK_FixedPointToFloating:
2238 case CK_FloatingToFixedPoint: {
2239 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, CE);
2240 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2241 CE->getExprLoc());
2242 }
2243 case CK_BooleanToSignedIntegral: {
2244 ScalarConversionOpts Opts;
2245 Opts.TreatBooleanAsSigned = true;
2246 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2247 CE->getExprLoc(), Opts);
2248 }
2249 case CK_IntegralToBoolean:
2250 return EmitIntToBoolConversion(Visit(E));
2251 case CK_PointerToBoolean:
2252 return EmitPointerToBoolConversion(Visit(E), E->getType());
2253 case CK_FloatingToBoolean: {
2254 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, CE);
2255 return EmitFloatToBoolConversion(Visit(E));
2256 }
2257 case CK_MemberPointerToBoolean: {
2258 llvm::Value *MemPtr = Visit(E);
2259 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
2260 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
2261 }
2262
2263 case CK_FloatingComplexToReal:
2264 case CK_IntegralComplexToReal:
2265 return CGF.EmitComplexExpr(E, false, true).first;
2266
2267 case CK_FloatingComplexToBoolean:
2268 case CK_IntegralComplexToBoolean: {
2269 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
2270
2271 // TODO: kill this function off, inline appropriate case here
2272 return EmitComplexToScalarConversion(V, E->getType(), DestTy,
2273 CE->getExprLoc());
2274 }
2275
2276 case CK_ZeroToOCLOpaqueType: {
2277 assert((DestTy->isEventT() || DestTy->isQueueT() ||
2278 DestTy->isOCLIntelSubgroupAVCType()) &&
2279 "CK_ZeroToOCLEvent cast on non-event type");
2280 return llvm::Constant::getNullValue(ConvertType(DestTy));
2281 }
2282
2283 case CK_IntToOCLSampler:
2284 return CGF.CGM.createOpenCLIntToSamplerConversion(E, CGF);
2285
2286 } // end of switch
2287
2288 llvm_unreachable("unknown scalar cast");
2289 }
2290
VisitStmtExpr(const StmtExpr * E)2291 Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
2292 CodeGenFunction::StmtExprEvaluation eval(CGF);
2293 Address RetAlloca = CGF.EmitCompoundStmt(*E->getSubStmt(),
2294 !E->getType()->isVoidType());
2295 if (!RetAlloca.isValid())
2296 return nullptr;
2297 return CGF.EmitLoadOfScalar(CGF.MakeAddrLValue(RetAlloca, E->getType()),
2298 E->getExprLoc());
2299 }
2300
VisitExprWithCleanups(ExprWithCleanups * E)2301 Value *ScalarExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
2302 CodeGenFunction::RunCleanupsScope Scope(CGF);
2303 Value *V = Visit(E->getSubExpr());
2304 // Defend against dominance problems caused by jumps out of expression
2305 // evaluation through the shared cleanup block.
2306 Scope.ForceCleanup({&V});
2307 return V;
2308 }
2309
2310 //===----------------------------------------------------------------------===//
2311 // Unary Operators
2312 //===----------------------------------------------------------------------===//
2313
createBinOpInfoFromIncDec(const UnaryOperator * E,llvm::Value * InVal,bool IsInc,FPOptions FPFeatures)2314 static BinOpInfo createBinOpInfoFromIncDec(const UnaryOperator *E,
2315 llvm::Value *InVal, bool IsInc,
2316 FPOptions FPFeatures) {
2317 BinOpInfo BinOp;
2318 BinOp.LHS = InVal;
2319 BinOp.RHS = llvm::ConstantInt::get(InVal->getType(), 1, false);
2320 BinOp.Ty = E->getType();
2321 BinOp.Opcode = IsInc ? BO_Add : BO_Sub;
2322 BinOp.FPFeatures = FPFeatures;
2323 BinOp.E = E;
2324 return BinOp;
2325 }
2326
EmitIncDecConsiderOverflowBehavior(const UnaryOperator * E,llvm::Value * InVal,bool IsInc)2327 llvm::Value *ScalarExprEmitter::EmitIncDecConsiderOverflowBehavior(
2328 const UnaryOperator *E, llvm::Value *InVal, bool IsInc) {
2329 llvm::Value *Amount =
2330 llvm::ConstantInt::get(InVal->getType(), IsInc ? 1 : -1, true);
2331 StringRef Name = IsInc ? "inc" : "dec";
2332 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
2333 case LangOptions::SOB_Defined:
2334 return Builder.CreateAdd(InVal, Amount, Name);
2335 case LangOptions::SOB_Undefined:
2336 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
2337 return Builder.CreateNSWAdd(InVal, Amount, Name);
2338 LLVM_FALLTHROUGH;
2339 case LangOptions::SOB_Trapping:
2340 if (!E->canOverflow())
2341 return Builder.CreateNSWAdd(InVal, Amount, Name);
2342 return EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec(
2343 E, InVal, IsInc, E->getFPFeaturesInEffect(CGF.getLangOpts())));
2344 }
2345 llvm_unreachable("Unknown SignedOverflowBehaviorTy");
2346 }
2347
2348 namespace {
2349 /// Handles check and update for lastprivate conditional variables.
2350 class OMPLastprivateConditionalUpdateRAII {
2351 private:
2352 CodeGenFunction &CGF;
2353 const UnaryOperator *E;
2354
2355 public:
OMPLastprivateConditionalUpdateRAII(CodeGenFunction & CGF,const UnaryOperator * E)2356 OMPLastprivateConditionalUpdateRAII(CodeGenFunction &CGF,
2357 const UnaryOperator *E)
2358 : CGF(CGF), E(E) {}
~OMPLastprivateConditionalUpdateRAII()2359 ~OMPLastprivateConditionalUpdateRAII() {
2360 if (CGF.getLangOpts().OpenMP)
2361 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(
2362 CGF, E->getSubExpr());
2363 }
2364 };
2365 } // namespace
2366
2367 llvm::Value *
EmitScalarPrePostIncDec(const UnaryOperator * E,LValue LV,bool isInc,bool isPre)2368 ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2369 bool isInc, bool isPre) {
2370 OMPLastprivateConditionalUpdateRAII OMPRegion(CGF, E);
2371 QualType type = E->getSubExpr()->getType();
2372 llvm::PHINode *atomicPHI = nullptr;
2373 llvm::Value *value;
2374 llvm::Value *input;
2375
2376 int amount = (isInc ? 1 : -1);
2377 bool isSubtraction = !isInc;
2378
2379 if (const AtomicType *atomicTy = type->getAs<AtomicType>()) {
2380 type = atomicTy->getValueType();
2381 if (isInc && type->isBooleanType()) {
2382 llvm::Value *True = CGF.EmitToMemory(Builder.getTrue(), type);
2383 if (isPre) {
2384 Builder.CreateStore(True, LV.getAddress(CGF), LV.isVolatileQualified())
2385 ->setAtomic(llvm::AtomicOrdering::SequentiallyConsistent);
2386 return Builder.getTrue();
2387 }
2388 // For atomic bool increment, we just store true and return it for
2389 // preincrement, do an atomic swap with true for postincrement
2390 return Builder.CreateAtomicRMW(
2391 llvm::AtomicRMWInst::Xchg, LV.getPointer(CGF), True,
2392 llvm::AtomicOrdering::SequentiallyConsistent);
2393 }
2394 // Special case for atomic increment / decrement on integers, emit
2395 // atomicrmw instructions. We skip this if we want to be doing overflow
2396 // checking, and fall into the slow path with the atomic cmpxchg loop.
2397 if (!type->isBooleanType() && type->isIntegerType() &&
2398 !(type->isUnsignedIntegerType() &&
2399 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
2400 CGF.getLangOpts().getSignedOverflowBehavior() !=
2401 LangOptions::SOB_Trapping) {
2402 llvm::AtomicRMWInst::BinOp aop = isInc ? llvm::AtomicRMWInst::Add :
2403 llvm::AtomicRMWInst::Sub;
2404 llvm::Instruction::BinaryOps op = isInc ? llvm::Instruction::Add :
2405 llvm::Instruction::Sub;
2406 llvm::Value *amt = CGF.EmitToMemory(
2407 llvm::ConstantInt::get(ConvertType(type), 1, true), type);
2408 llvm::Value *old =
2409 Builder.CreateAtomicRMW(aop, LV.getPointer(CGF), amt,
2410 llvm::AtomicOrdering::SequentiallyConsistent);
2411 return isPre ? Builder.CreateBinOp(op, old, amt) : old;
2412 }
2413 value = EmitLoadOfLValue(LV, E->getExprLoc());
2414 input = value;
2415 // For every other atomic operation, we need to emit a load-op-cmpxchg loop
2416 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
2417 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
2418 value = CGF.EmitToMemory(value, type);
2419 Builder.CreateBr(opBB);
2420 Builder.SetInsertPoint(opBB);
2421 atomicPHI = Builder.CreatePHI(value->getType(), 2);
2422 atomicPHI->addIncoming(value, startBB);
2423 value = atomicPHI;
2424 } else {
2425 value = EmitLoadOfLValue(LV, E->getExprLoc());
2426 input = value;
2427 }
2428
2429 // Special case of integer increment that we have to check first: bool++.
2430 // Due to promotion rules, we get:
2431 // bool++ -> bool = bool + 1
2432 // -> bool = (int)bool + 1
2433 // -> bool = ((int)bool + 1 != 0)
2434 // An interesting aspect of this is that increment is always true.
2435 // Decrement does not have this property.
2436 if (isInc && type->isBooleanType()) {
2437 value = Builder.getTrue();
2438
2439 // Most common case by far: integer increment.
2440 } else if (type->isIntegerType()) {
2441 QualType promotedType;
2442 bool canPerformLossyDemotionCheck = false;
2443 if (type->isPromotableIntegerType()) {
2444 promotedType = CGF.getContext().getPromotedIntegerType(type);
2445 assert(promotedType != type && "Shouldn't promote to the same type.");
2446 canPerformLossyDemotionCheck = true;
2447 canPerformLossyDemotionCheck &=
2448 CGF.getContext().getCanonicalType(type) !=
2449 CGF.getContext().getCanonicalType(promotedType);
2450 canPerformLossyDemotionCheck &=
2451 PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(
2452 type, promotedType);
2453 assert((!canPerformLossyDemotionCheck ||
2454 type->isSignedIntegerOrEnumerationType() ||
2455 promotedType->isSignedIntegerOrEnumerationType() ||
2456 ConvertType(type)->getScalarSizeInBits() ==
2457 ConvertType(promotedType)->getScalarSizeInBits()) &&
2458 "The following check expects that if we do promotion to different "
2459 "underlying canonical type, at least one of the types (either "
2460 "base or promoted) will be signed, or the bitwidths will match.");
2461 }
2462 if (CGF.SanOpts.hasOneOf(
2463 SanitizerKind::ImplicitIntegerArithmeticValueChange) &&
2464 canPerformLossyDemotionCheck) {
2465 // While `x += 1` (for `x` with width less than int) is modeled as
2466 // promotion+arithmetics+demotion, and we can catch lossy demotion with
2467 // ease; inc/dec with width less than int can't overflow because of
2468 // promotion rules, so we omit promotion+demotion, which means that we can
2469 // not catch lossy "demotion". Because we still want to catch these cases
2470 // when the sanitizer is enabled, we perform the promotion, then perform
2471 // the increment/decrement in the wider type, and finally
2472 // perform the demotion. This will catch lossy demotions.
2473
2474 value = EmitScalarConversion(value, type, promotedType, E->getExprLoc());
2475 Value *amt = llvm::ConstantInt::get(value->getType(), amount, true);
2476 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
2477 // Do pass non-default ScalarConversionOpts so that sanitizer check is
2478 // emitted.
2479 value = EmitScalarConversion(value, promotedType, type, E->getExprLoc(),
2480 ScalarConversionOpts(CGF.SanOpts));
2481
2482 // Note that signed integer inc/dec with width less than int can't
2483 // overflow because of promotion rules; we're just eliding a few steps
2484 // here.
2485 } else if (E->canOverflow() && type->isSignedIntegerOrEnumerationType()) {
2486 value = EmitIncDecConsiderOverflowBehavior(E, value, isInc);
2487 } else if (E->canOverflow() && type->isUnsignedIntegerType() &&
2488 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) {
2489 value = EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec(
2490 E, value, isInc, E->getFPFeaturesInEffect(CGF.getLangOpts())));
2491 } else {
2492 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount, true);
2493 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
2494 }
2495
2496 // Next most common: pointer increment.
2497 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
2498 QualType type = ptr->getPointeeType();
2499
2500 // VLA types don't have constant size.
2501 if (const VariableArrayType *vla
2502 = CGF.getContext().getAsVariableArrayType(type)) {
2503 llvm::Value *numElts = CGF.getVLASize(vla).NumElts;
2504 if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize");
2505 if (CGF.getLangOpts().isSignedOverflowDefined())
2506 value = Builder.CreateGEP(value, numElts, "vla.inc");
2507 else
2508 value = CGF.EmitCheckedInBoundsGEP(
2509 value, numElts, /*SignedIndices=*/false, isSubtraction,
2510 E->getExprLoc(), "vla.inc");
2511
2512 // Arithmetic on function pointers (!) is just +-1.
2513 } else if (type->isFunctionType()) {
2514 llvm::Value *amt = Builder.getInt32(amount);
2515
2516 value = CGF.EmitCastToVoidPtr(value);
2517 if (CGF.getLangOpts().isSignedOverflowDefined())
2518 value = Builder.CreateGEP(value, amt, "incdec.funcptr");
2519 else
2520 value = CGF.EmitCheckedInBoundsGEP(value, amt, /*SignedIndices=*/false,
2521 isSubtraction, E->getExprLoc(),
2522 "incdec.funcptr");
2523 value = Builder.CreateBitCast(value, input->getType());
2524
2525 // For everything else, we can just do a simple increment.
2526 } else {
2527 llvm::Value *amt = Builder.getInt32(amount);
2528 if (CGF.getLangOpts().isSignedOverflowDefined())
2529 value = Builder.CreateGEP(value, amt, "incdec.ptr");
2530 else
2531 value = CGF.EmitCheckedInBoundsGEP(value, amt, /*SignedIndices=*/false,
2532 isSubtraction, E->getExprLoc(),
2533 "incdec.ptr");
2534 }
2535
2536 // Vector increment/decrement.
2537 } else if (type->isVectorType()) {
2538 if (type->hasIntegerRepresentation()) {
2539 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
2540
2541 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
2542 } else {
2543 value = Builder.CreateFAdd(
2544 value,
2545 llvm::ConstantFP::get(value->getType(), amount),
2546 isInc ? "inc" : "dec");
2547 }
2548
2549 // Floating point.
2550 } else if (type->isRealFloatingType()) {
2551 // Add the inc/dec to the real part.
2552 llvm::Value *amt;
2553 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
2554
2555 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
2556 // Another special case: half FP increment should be done via float
2557 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
2558 value = Builder.CreateCall(
2559 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16,
2560 CGF.CGM.FloatTy),
2561 input, "incdec.conv");
2562 } else {
2563 value = Builder.CreateFPExt(input, CGF.CGM.FloatTy, "incdec.conv");
2564 }
2565 }
2566
2567 if (value->getType()->isFloatTy())
2568 amt = llvm::ConstantFP::get(VMContext,
2569 llvm::APFloat(static_cast<float>(amount)));
2570 else if (value->getType()->isDoubleTy())
2571 amt = llvm::ConstantFP::get(VMContext,
2572 llvm::APFloat(static_cast<double>(amount)));
2573 else {
2574 // Remaining types are Half, LongDouble or __float128. Convert from float.
2575 llvm::APFloat F(static_cast<float>(amount));
2576 bool ignored;
2577 const llvm::fltSemantics *FS;
2578 // Don't use getFloatTypeSemantics because Half isn't
2579 // necessarily represented using the "half" LLVM type.
2580 if (value->getType()->isFP128Ty())
2581 FS = &CGF.getTarget().getFloat128Format();
2582 else if (value->getType()->isHalfTy())
2583 FS = &CGF.getTarget().getHalfFormat();
2584 else
2585 FS = &CGF.getTarget().getLongDoubleFormat();
2586 F.convert(*FS, llvm::APFloat::rmTowardZero, &ignored);
2587 amt = llvm::ConstantFP::get(VMContext, F);
2588 }
2589 value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
2590
2591 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
2592 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
2593 value = Builder.CreateCall(
2594 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16,
2595 CGF.CGM.FloatTy),
2596 value, "incdec.conv");
2597 } else {
2598 value = Builder.CreateFPTrunc(value, input->getType(), "incdec.conv");
2599 }
2600 }
2601
2602 // Fixed-point types.
2603 } else if (type->isFixedPointType()) {
2604 // Fixed-point types are tricky. In some cases, it isn't possible to
2605 // represent a 1 or a -1 in the type at all. Piggyback off of
2606 // EmitFixedPointBinOp to avoid having to reimplement saturation.
2607 BinOpInfo Info;
2608 Info.E = E;
2609 Info.Ty = E->getType();
2610 Info.Opcode = isInc ? BO_Add : BO_Sub;
2611 Info.LHS = value;
2612 Info.RHS = llvm::ConstantInt::get(value->getType(), 1, false);
2613 // If the type is signed, it's better to represent this as +(-1) or -(-1),
2614 // since -1 is guaranteed to be representable.
2615 if (type->isSignedFixedPointType()) {
2616 Info.Opcode = isInc ? BO_Sub : BO_Add;
2617 Info.RHS = Builder.CreateNeg(Info.RHS);
2618 }
2619 // Now, convert from our invented integer literal to the type of the unary
2620 // op. This will upscale and saturate if necessary. This value can become
2621 // undef in some cases.
2622 llvm::FixedPointBuilder<CGBuilderTy> FPBuilder(Builder);
2623 auto DstSema = CGF.getContext().getFixedPointSemantics(Info.Ty);
2624 Info.RHS = FPBuilder.CreateIntegerToFixed(Info.RHS, true, DstSema);
2625 value = EmitFixedPointBinOp(Info);
2626
2627 // Objective-C pointer types.
2628 } else {
2629 const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
2630 value = CGF.EmitCastToVoidPtr(value);
2631
2632 CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
2633 if (!isInc) size = -size;
2634 llvm::Value *sizeValue =
2635 llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
2636
2637 if (CGF.getLangOpts().isSignedOverflowDefined())
2638 value = Builder.CreateGEP(value, sizeValue, "incdec.objptr");
2639 else
2640 value = CGF.EmitCheckedInBoundsGEP(value, sizeValue,
2641 /*SignedIndices=*/false, isSubtraction,
2642 E->getExprLoc(), "incdec.objptr");
2643 value = Builder.CreateBitCast(value, input->getType());
2644 }
2645
2646 if (atomicPHI) {
2647 llvm::BasicBlock *curBlock = Builder.GetInsertBlock();
2648 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
2649 auto Pair = CGF.EmitAtomicCompareExchange(
2650 LV, RValue::get(atomicPHI), RValue::get(value), E->getExprLoc());
2651 llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), type);
2652 llvm::Value *success = Pair.second;
2653 atomicPHI->addIncoming(old, curBlock);
2654 Builder.CreateCondBr(success, contBB, atomicPHI->getParent());
2655 Builder.SetInsertPoint(contBB);
2656 return isPre ? value : input;
2657 }
2658
2659 // Store the updated result through the lvalue.
2660 if (LV.isBitField())
2661 CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
2662 else
2663 CGF.EmitStoreThroughLValue(RValue::get(value), LV);
2664
2665 // If this is a postinc, return the value read from memory, otherwise use the
2666 // updated value.
2667 return isPre ? value : input;
2668 }
2669
2670
2671
VisitUnaryMinus(const UnaryOperator * E)2672 Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
2673 TestAndClearIgnoreResultAssign();
2674 Value *Op = Visit(E->getSubExpr());
2675
2676 // Generate a unary FNeg for FP ops.
2677 if (Op->getType()->isFPOrFPVectorTy())
2678 return Builder.CreateFNeg(Op, "fneg");
2679
2680 // Emit unary minus with EmitSub so we handle overflow cases etc.
2681 BinOpInfo BinOp;
2682 BinOp.RHS = Op;
2683 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
2684 BinOp.Ty = E->getType();
2685 BinOp.Opcode = BO_Sub;
2686 BinOp.FPFeatures = E->getFPFeaturesInEffect(CGF.getLangOpts());
2687 BinOp.E = E;
2688 return EmitSub(BinOp);
2689 }
2690
VisitUnaryNot(const UnaryOperator * E)2691 Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
2692 TestAndClearIgnoreResultAssign();
2693 Value *Op = Visit(E->getSubExpr());
2694 return Builder.CreateNot(Op, "neg");
2695 }
2696
VisitUnaryLNot(const UnaryOperator * E)2697 Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
2698 // Perform vector logical not on comparison with zero vector.
2699 if (E->getType()->isVectorType() &&
2700 E->getType()->castAs<VectorType>()->getVectorKind() ==
2701 VectorType::GenericVector) {
2702 Value *Oper = Visit(E->getSubExpr());
2703 Value *Zero = llvm::Constant::getNullValue(Oper->getType());
2704 Value *Result;
2705 if (Oper->getType()->isFPOrFPVectorTy()) {
2706 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(
2707 CGF, E->getFPFeaturesInEffect(CGF.getLangOpts()));
2708 Result = Builder.CreateFCmp(llvm::CmpInst::FCMP_OEQ, Oper, Zero, "cmp");
2709 } else
2710 Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp");
2711 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
2712 }
2713
2714 // Compare operand to zero.
2715 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
2716
2717 // Invert value.
2718 // TODO: Could dynamically modify easy computations here. For example, if
2719 // the operand is an icmp ne, turn into icmp eq.
2720 BoolVal = Builder.CreateNot(BoolVal, "lnot");
2721
2722 // ZExt result to the expr type.
2723 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
2724 }
2725
VisitOffsetOfExpr(OffsetOfExpr * E)2726 Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
2727 // Try folding the offsetof to a constant.
2728 Expr::EvalResult EVResult;
2729 if (E->EvaluateAsInt(EVResult, CGF.getContext())) {
2730 llvm::APSInt Value = EVResult.Val.getInt();
2731 return Builder.getInt(Value);
2732 }
2733
2734 // Loop over the components of the offsetof to compute the value.
2735 unsigned n = E->getNumComponents();
2736 llvm::Type* ResultType = ConvertType(E->getType());
2737 llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
2738 QualType CurrentType = E->getTypeSourceInfo()->getType();
2739 for (unsigned i = 0; i != n; ++i) {
2740 OffsetOfNode ON = E->getComponent(i);
2741 llvm::Value *Offset = nullptr;
2742 switch (ON.getKind()) {
2743 case OffsetOfNode::Array: {
2744 // Compute the index
2745 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
2746 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
2747 bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
2748 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
2749
2750 // Save the element type
2751 CurrentType =
2752 CGF.getContext().getAsArrayType(CurrentType)->getElementType();
2753
2754 // Compute the element size
2755 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
2756 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
2757
2758 // Multiply out to compute the result
2759 Offset = Builder.CreateMul(Idx, ElemSize);
2760 break;
2761 }
2762
2763 case OffsetOfNode::Field: {
2764 FieldDecl *MemberDecl = ON.getField();
2765 RecordDecl *RD = CurrentType->castAs<RecordType>()->getDecl();
2766 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
2767
2768 // Compute the index of the field in its parent.
2769 unsigned i = 0;
2770 // FIXME: It would be nice if we didn't have to loop here!
2771 for (RecordDecl::field_iterator Field = RD->field_begin(),
2772 FieldEnd = RD->field_end();
2773 Field != FieldEnd; ++Field, ++i) {
2774 if (*Field == MemberDecl)
2775 break;
2776 }
2777 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
2778
2779 // Compute the offset to the field
2780 int64_t OffsetInt = RL.getFieldOffset(i) /
2781 CGF.getContext().getCharWidth();
2782 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
2783
2784 // Save the element type.
2785 CurrentType = MemberDecl->getType();
2786 break;
2787 }
2788
2789 case OffsetOfNode::Identifier:
2790 llvm_unreachable("dependent __builtin_offsetof");
2791
2792 case OffsetOfNode::Base: {
2793 if (ON.getBase()->isVirtual()) {
2794 CGF.ErrorUnsupported(E, "virtual base in offsetof");
2795 continue;
2796 }
2797
2798 RecordDecl *RD = CurrentType->castAs<RecordType>()->getDecl();
2799 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
2800
2801 // Save the element type.
2802 CurrentType = ON.getBase()->getType();
2803
2804 // Compute the offset to the base.
2805 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
2806 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
2807 CharUnits OffsetInt = RL.getBaseClassOffset(BaseRD);
2808 Offset = llvm::ConstantInt::get(ResultType, OffsetInt.getQuantity());
2809 break;
2810 }
2811 }
2812 Result = Builder.CreateAdd(Result, Offset);
2813 }
2814 return Result;
2815 }
2816
2817 /// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
2818 /// argument of the sizeof expression as an integer.
2819 Value *
VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr * E)2820 ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
2821 const UnaryExprOrTypeTraitExpr *E) {
2822 QualType TypeToSize = E->getTypeOfArgument();
2823 if (E->getKind() == UETT_SizeOf) {
2824 if (const VariableArrayType *VAT =
2825 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
2826 if (E->isArgumentType()) {
2827 // sizeof(type) - make sure to emit the VLA size.
2828 CGF.EmitVariablyModifiedType(TypeToSize);
2829 } else {
2830 // C99 6.5.3.4p2: If the argument is an expression of type
2831 // VLA, it is evaluated.
2832 CGF.EmitIgnoredExpr(E->getArgumentExpr());
2833 }
2834
2835 auto VlaSize = CGF.getVLASize(VAT);
2836 llvm::Value *size = VlaSize.NumElts;
2837
2838 // Scale the number of non-VLA elements by the non-VLA element size.
2839 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(VlaSize.Type);
2840 if (!eltSize.isOne())
2841 size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), size);
2842
2843 return size;
2844 }
2845 } else if (E->getKind() == UETT_OpenMPRequiredSimdAlign) {
2846 auto Alignment =
2847 CGF.getContext()
2848 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
2849 E->getTypeOfArgument()->getPointeeType()))
2850 .getQuantity();
2851 return llvm::ConstantInt::get(CGF.SizeTy, Alignment);
2852 }
2853
2854 // If this isn't sizeof(vla), the result must be constant; use the constant
2855 // folding logic so we don't have to duplicate it here.
2856 return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext()));
2857 }
2858
VisitUnaryReal(const UnaryOperator * E)2859 Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
2860 Expr *Op = E->getSubExpr();
2861 if (Op->getType()->isAnyComplexType()) {
2862 // If it's an l-value, load through the appropriate subobject l-value.
2863 // Note that we have to ask E because Op might be an l-value that
2864 // this won't work for, e.g. an Obj-C property.
2865 if (E->isGLValue())
2866 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
2867 E->getExprLoc()).getScalarVal();
2868
2869 // Otherwise, calculate and project.
2870 return CGF.EmitComplexExpr(Op, false, true).first;
2871 }
2872
2873 return Visit(Op);
2874 }
2875
VisitUnaryImag(const UnaryOperator * E)2876 Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
2877 Expr *Op = E->getSubExpr();
2878 if (Op->getType()->isAnyComplexType()) {
2879 // If it's an l-value, load through the appropriate subobject l-value.
2880 // Note that we have to ask E because Op might be an l-value that
2881 // this won't work for, e.g. an Obj-C property.
2882 if (Op->isGLValue())
2883 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
2884 E->getExprLoc()).getScalarVal();
2885
2886 // Otherwise, calculate and project.
2887 return CGF.EmitComplexExpr(Op, true, false).second;
2888 }
2889
2890 // __imag on a scalar returns zero. Emit the subexpr to ensure side
2891 // effects are evaluated, but not the actual value.
2892 if (Op->isGLValue())
2893 CGF.EmitLValue(Op);
2894 else
2895 CGF.EmitScalarExpr(Op, true);
2896 return llvm::Constant::getNullValue(ConvertType(E->getType()));
2897 }
2898
2899 //===----------------------------------------------------------------------===//
2900 // Binary Operators
2901 //===----------------------------------------------------------------------===//
2902
EmitBinOps(const BinaryOperator * E)2903 BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
2904 TestAndClearIgnoreResultAssign();
2905 BinOpInfo Result;
2906 Result.LHS = Visit(E->getLHS());
2907 Result.RHS = Visit(E->getRHS());
2908 Result.Ty = E->getType();
2909 Result.Opcode = E->getOpcode();
2910 Result.FPFeatures = E->getFPFeaturesInEffect(CGF.getLangOpts());
2911 Result.E = E;
2912 return Result;
2913 }
2914
EmitCompoundAssignLValue(const CompoundAssignOperator * E,Value * (ScalarExprEmitter::* Func)(const BinOpInfo &),Value * & Result)2915 LValue ScalarExprEmitter::EmitCompoundAssignLValue(
2916 const CompoundAssignOperator *E,
2917 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
2918 Value *&Result) {
2919 QualType LHSTy = E->getLHS()->getType();
2920 BinOpInfo OpInfo;
2921
2922 if (E->getComputationResultType()->isAnyComplexType())
2923 return CGF.EmitScalarCompoundAssignWithComplex(E, Result);
2924
2925 // Emit the RHS first. __block variables need to have the rhs evaluated
2926 // first, plus this should improve codegen a little.
2927 OpInfo.RHS = Visit(E->getRHS());
2928 OpInfo.Ty = E->getComputationResultType();
2929 OpInfo.Opcode = E->getOpcode();
2930 OpInfo.FPFeatures = E->getFPFeaturesInEffect(CGF.getLangOpts());
2931 OpInfo.E = E;
2932 // Load/convert the LHS.
2933 LValue LHSLV = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
2934
2935 llvm::PHINode *atomicPHI = nullptr;
2936 if (const AtomicType *atomicTy = LHSTy->getAs<AtomicType>()) {
2937 QualType type = atomicTy->getValueType();
2938 if (!type->isBooleanType() && type->isIntegerType() &&
2939 !(type->isUnsignedIntegerType() &&
2940 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
2941 CGF.getLangOpts().getSignedOverflowBehavior() !=
2942 LangOptions::SOB_Trapping) {
2943 llvm::AtomicRMWInst::BinOp AtomicOp = llvm::AtomicRMWInst::BAD_BINOP;
2944 llvm::Instruction::BinaryOps Op;
2945 switch (OpInfo.Opcode) {
2946 // We don't have atomicrmw operands for *, %, /, <<, >>
2947 case BO_MulAssign: case BO_DivAssign:
2948 case BO_RemAssign:
2949 case BO_ShlAssign:
2950 case BO_ShrAssign:
2951 break;
2952 case BO_AddAssign:
2953 AtomicOp = llvm::AtomicRMWInst::Add;
2954 Op = llvm::Instruction::Add;
2955 break;
2956 case BO_SubAssign:
2957 AtomicOp = llvm::AtomicRMWInst::Sub;
2958 Op = llvm::Instruction::Sub;
2959 break;
2960 case BO_AndAssign:
2961 AtomicOp = llvm::AtomicRMWInst::And;
2962 Op = llvm::Instruction::And;
2963 break;
2964 case BO_XorAssign:
2965 AtomicOp = llvm::AtomicRMWInst::Xor;
2966 Op = llvm::Instruction::Xor;
2967 break;
2968 case BO_OrAssign:
2969 AtomicOp = llvm::AtomicRMWInst::Or;
2970 Op = llvm::Instruction::Or;
2971 break;
2972 default:
2973 llvm_unreachable("Invalid compound assignment type");
2974 }
2975 if (AtomicOp != llvm::AtomicRMWInst::BAD_BINOP) {
2976 llvm::Value *Amt = CGF.EmitToMemory(
2977 EmitScalarConversion(OpInfo.RHS, E->getRHS()->getType(), LHSTy,
2978 E->getExprLoc()),
2979 LHSTy);
2980 Value *OldVal = Builder.CreateAtomicRMW(
2981 AtomicOp, LHSLV.getPointer(CGF), Amt,
2982 llvm::AtomicOrdering::SequentiallyConsistent);
2983
2984 // Since operation is atomic, the result type is guaranteed to be the
2985 // same as the input in LLVM terms.
2986 Result = Builder.CreateBinOp(Op, OldVal, Amt);
2987 return LHSLV;
2988 }
2989 }
2990 // FIXME: For floating point types, we should be saving and restoring the
2991 // floating point environment in the loop.
2992 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
2993 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
2994 OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
2995 OpInfo.LHS = CGF.EmitToMemory(OpInfo.LHS, type);
2996 Builder.CreateBr(opBB);
2997 Builder.SetInsertPoint(opBB);
2998 atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2);
2999 atomicPHI->addIncoming(OpInfo.LHS, startBB);
3000 OpInfo.LHS = atomicPHI;
3001 }
3002 else
3003 OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
3004
3005 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, OpInfo.FPFeatures);
3006 SourceLocation Loc = E->getExprLoc();
3007 OpInfo.LHS =
3008 EmitScalarConversion(OpInfo.LHS, LHSTy, E->getComputationLHSType(), Loc);
3009
3010 // Expand the binary operator.
3011 Result = (this->*Func)(OpInfo);
3012
3013 // Convert the result back to the LHS type,
3014 // potentially with Implicit Conversion sanitizer check.
3015 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy,
3016 Loc, ScalarConversionOpts(CGF.SanOpts));
3017
3018 if (atomicPHI) {
3019 llvm::BasicBlock *curBlock = Builder.GetInsertBlock();
3020 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
3021 auto Pair = CGF.EmitAtomicCompareExchange(
3022 LHSLV, RValue::get(atomicPHI), RValue::get(Result), E->getExprLoc());
3023 llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), LHSTy);
3024 llvm::Value *success = Pair.second;
3025 atomicPHI->addIncoming(old, curBlock);
3026 Builder.CreateCondBr(success, contBB, atomicPHI->getParent());
3027 Builder.SetInsertPoint(contBB);
3028 return LHSLV;
3029 }
3030
3031 // Store the result value into the LHS lvalue. Bit-fields are handled
3032 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
3033 // 'An assignment expression has the value of the left operand after the
3034 // assignment...'.
3035 if (LHSLV.isBitField())
3036 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
3037 else
3038 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
3039
3040 if (CGF.getLangOpts().OpenMP)
3041 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF,
3042 E->getLHS());
3043 return LHSLV;
3044 }
3045
EmitCompoundAssign(const CompoundAssignOperator * E,Value * (ScalarExprEmitter::* Func)(const BinOpInfo &))3046 Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
3047 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
3048 bool Ignore = TestAndClearIgnoreResultAssign();
3049 Value *RHS = nullptr;
3050 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
3051
3052 // If the result is clearly ignored, return now.
3053 if (Ignore)
3054 return nullptr;
3055
3056 // The result of an assignment in C is the assigned r-value.
3057 if (!CGF.getLangOpts().CPlusPlus)
3058 return RHS;
3059
3060 // If the lvalue is non-volatile, return the computed value of the assignment.
3061 if (!LHS.isVolatileQualified())
3062 return RHS;
3063
3064 // Otherwise, reload the value.
3065 return EmitLoadOfLValue(LHS, E->getExprLoc());
3066 }
3067
EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo & Ops,llvm::Value * Zero,bool isDiv)3068 void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
3069 const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) {
3070 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks;
3071
3072 if (CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero)) {
3073 Checks.push_back(std::make_pair(Builder.CreateICmpNE(Ops.RHS, Zero),
3074 SanitizerKind::IntegerDivideByZero));
3075 }
3076
3077 const auto *BO = cast<BinaryOperator>(Ops.E);
3078 if (CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow) &&
3079 Ops.Ty->hasSignedIntegerRepresentation() &&
3080 !IsWidenedIntegerOp(CGF.getContext(), BO->getLHS()) &&
3081 Ops.mayHaveIntegerOverflow()) {
3082 llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
3083
3084 llvm::Value *IntMin =
3085 Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
3086 llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
3087
3088 llvm::Value *LHSCmp = Builder.CreateICmpNE(Ops.LHS, IntMin);
3089 llvm::Value *RHSCmp = Builder.CreateICmpNE(Ops.RHS, NegOne);
3090 llvm::Value *NotOverflow = Builder.CreateOr(LHSCmp, RHSCmp, "or");
3091 Checks.push_back(
3092 std::make_pair(NotOverflow, SanitizerKind::SignedIntegerOverflow));
3093 }
3094
3095 if (Checks.size() > 0)
3096 EmitBinOpCheck(Checks, Ops);
3097 }
3098
EmitDiv(const BinOpInfo & Ops)3099 Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
3100 {
3101 CodeGenFunction::SanitizerScope SanScope(&CGF);
3102 if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) ||
3103 CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) &&
3104 Ops.Ty->isIntegerType() &&
3105 (Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) {
3106 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
3107 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
3108 } else if (CGF.SanOpts.has(SanitizerKind::FloatDivideByZero) &&
3109 Ops.Ty->isRealFloatingType() &&
3110 Ops.mayHaveFloatDivisionByZero()) {
3111 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
3112 llvm::Value *NonZero = Builder.CreateFCmpUNE(Ops.RHS, Zero);
3113 EmitBinOpCheck(std::make_pair(NonZero, SanitizerKind::FloatDivideByZero),
3114 Ops);
3115 }
3116 }
3117
3118 if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
3119 llvm::Value *Val;
3120 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Ops.FPFeatures);
3121 Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
3122 if (CGF.getLangOpts().OpenCL &&
3123 !CGF.CGM.getCodeGenOpts().CorrectlyRoundedDivSqrt) {
3124 // OpenCL v1.1 s7.4: minimum accuracy of single precision / is 2.5ulp
3125 // OpenCL v1.2 s5.6.4.2: The -cl-fp32-correctly-rounded-divide-sqrt
3126 // build option allows an application to specify that single precision
3127 // floating-point divide (x/y and 1/x) and sqrt used in the program
3128 // source are correctly rounded.
3129 llvm::Type *ValTy = Val->getType();
3130 if (ValTy->isFloatTy() ||
3131 (isa<llvm::VectorType>(ValTy) &&
3132 cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy()))
3133 CGF.SetFPAccuracy(Val, 2.5);
3134 }
3135 return Val;
3136 }
3137 else if (Ops.isFixedPointOp())
3138 return EmitFixedPointBinOp(Ops);
3139 else if (Ops.Ty->hasUnsignedIntegerRepresentation())
3140 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
3141 else
3142 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
3143 }
3144
EmitRem(const BinOpInfo & Ops)3145 Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
3146 // Rem in C can't be a floating point type: C99 6.5.5p2.
3147 if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) ||
3148 CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) &&
3149 Ops.Ty->isIntegerType() &&
3150 (Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) {
3151 CodeGenFunction::SanitizerScope SanScope(&CGF);
3152 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
3153 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
3154 }
3155
3156 if (Ops.Ty->hasUnsignedIntegerRepresentation())
3157 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
3158 else
3159 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
3160 }
3161
EmitOverflowCheckedBinOp(const BinOpInfo & Ops)3162 Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
3163 unsigned IID;
3164 unsigned OpID = 0;
3165 SanitizerHandler OverflowKind;
3166
3167 bool isSigned = Ops.Ty->isSignedIntegerOrEnumerationType();
3168 switch (Ops.Opcode) {
3169 case BO_Add:
3170 case BO_AddAssign:
3171 OpID = 1;
3172 IID = isSigned ? llvm::Intrinsic::sadd_with_overflow :
3173 llvm::Intrinsic::uadd_with_overflow;
3174 OverflowKind = SanitizerHandler::AddOverflow;
3175 break;
3176 case BO_Sub:
3177 case BO_SubAssign:
3178 OpID = 2;
3179 IID = isSigned ? llvm::Intrinsic::ssub_with_overflow :
3180 llvm::Intrinsic::usub_with_overflow;
3181 OverflowKind = SanitizerHandler::SubOverflow;
3182 break;
3183 case BO_Mul:
3184 case BO_MulAssign:
3185 OpID = 3;
3186 IID = isSigned ? llvm::Intrinsic::smul_with_overflow :
3187 llvm::Intrinsic::umul_with_overflow;
3188 OverflowKind = SanitizerHandler::MulOverflow;
3189 break;
3190 default:
3191 llvm_unreachable("Unsupported operation for overflow detection");
3192 }
3193 OpID <<= 1;
3194 if (isSigned)
3195 OpID |= 1;
3196
3197 CodeGenFunction::SanitizerScope SanScope(&CGF);
3198 llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
3199
3200 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
3201
3202 Value *resultAndOverflow = Builder.CreateCall(intrinsic, {Ops.LHS, Ops.RHS});
3203 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
3204 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
3205
3206 // Handle overflow with llvm.trap if no custom handler has been specified.
3207 const std::string *handlerName =
3208 &CGF.getLangOpts().OverflowHandler;
3209 if (handlerName->empty()) {
3210 // If the signed-integer-overflow sanitizer is enabled, emit a call to its
3211 // runtime. Otherwise, this is a -ftrapv check, so just emit a trap.
3212 if (!isSigned || CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) {
3213 llvm::Value *NotOverflow = Builder.CreateNot(overflow);
3214 SanitizerMask Kind = isSigned ? SanitizerKind::SignedIntegerOverflow
3215 : SanitizerKind::UnsignedIntegerOverflow;
3216 EmitBinOpCheck(std::make_pair(NotOverflow, Kind), Ops);
3217 } else
3218 CGF.EmitTrapCheck(Builder.CreateNot(overflow), OverflowKind);
3219 return result;
3220 }
3221
3222 // Branch in case of overflow.
3223 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
3224 llvm::BasicBlock *continueBB =
3225 CGF.createBasicBlock("nooverflow", CGF.CurFn, initialBB->getNextNode());
3226 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
3227
3228 Builder.CreateCondBr(overflow, overflowBB, continueBB);
3229
3230 // If an overflow handler is set, then we want to call it and then use its
3231 // result, if it returns.
3232 Builder.SetInsertPoint(overflowBB);
3233
3234 // Get the overflow handler.
3235 llvm::Type *Int8Ty = CGF.Int8Ty;
3236 llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
3237 llvm::FunctionType *handlerTy =
3238 llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
3239 llvm::FunctionCallee handler =
3240 CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
3241
3242 // Sign extend the args to 64-bit, so that we can use the same handler for
3243 // all types of overflow.
3244 llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
3245 llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
3246
3247 // Call the handler with the two arguments, the operation, and the size of
3248 // the result.
3249 llvm::Value *handlerArgs[] = {
3250 lhs,
3251 rhs,
3252 Builder.getInt8(OpID),
3253 Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth())
3254 };
3255 llvm::Value *handlerResult =
3256 CGF.EmitNounwindRuntimeCall(handler, handlerArgs);
3257
3258 // Truncate the result back to the desired size.
3259 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
3260 Builder.CreateBr(continueBB);
3261
3262 Builder.SetInsertPoint(continueBB);
3263 llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
3264 phi->addIncoming(result, initialBB);
3265 phi->addIncoming(handlerResult, overflowBB);
3266
3267 return phi;
3268 }
3269
3270 /// Emit pointer + index arithmetic.
emitPointerArithmetic(CodeGenFunction & CGF,const BinOpInfo & op,bool isSubtraction)3271 static Value *emitPointerArithmetic(CodeGenFunction &CGF,
3272 const BinOpInfo &op,
3273 bool isSubtraction) {
3274 // Must have binary (not unary) expr here. Unary pointer
3275 // increment/decrement doesn't use this path.
3276 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
3277
3278 Value *pointer = op.LHS;
3279 Expr *pointerOperand = expr->getLHS();
3280 Value *index = op.RHS;
3281 Expr *indexOperand = expr->getRHS();
3282
3283 // In a subtraction, the LHS is always the pointer.
3284 if (!isSubtraction && !pointer->getType()->isPointerTy()) {
3285 std::swap(pointer, index);
3286 std::swap(pointerOperand, indexOperand);
3287 }
3288
3289 bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
3290
3291 unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
3292 auto &DL = CGF.CGM.getDataLayout();
3293 auto PtrTy = cast<llvm::PointerType>(pointer->getType());
3294
3295 // Some versions of glibc and gcc use idioms (particularly in their malloc
3296 // routines) that add a pointer-sized integer (known to be a pointer value)
3297 // to a null pointer in order to cast the value back to an integer or as
3298 // part of a pointer alignment algorithm. This is undefined behavior, but
3299 // we'd like to be able to compile programs that use it.
3300 //
3301 // Normally, we'd generate a GEP with a null-pointer base here in response
3302 // to that code, but it's also UB to dereference a pointer created that
3303 // way. Instead (as an acknowledged hack to tolerate the idiom) we will
3304 // generate a direct cast of the integer value to a pointer.
3305 //
3306 // The idiom (p = nullptr + N) is not met if any of the following are true:
3307 //
3308 // The operation is subtraction.
3309 // The index is not pointer-sized.
3310 // The pointer type is not byte-sized.
3311 //
3312 if (BinaryOperator::isNullPointerArithmeticExtension(CGF.getContext(),
3313 op.Opcode,
3314 expr->getLHS(),
3315 expr->getRHS()))
3316 return CGF.Builder.CreateIntToPtr(index, pointer->getType());
3317
3318 if (width != DL.getIndexTypeSizeInBits(PtrTy)) {
3319 // Zero-extend or sign-extend the pointer value according to
3320 // whether the index is signed or not.
3321 index = CGF.Builder.CreateIntCast(index, DL.getIndexType(PtrTy), isSigned,
3322 "idx.ext");
3323 }
3324
3325 // If this is subtraction, negate the index.
3326 if (isSubtraction)
3327 index = CGF.Builder.CreateNeg(index, "idx.neg");
3328
3329 if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
3330 CGF.EmitBoundsCheck(op.E, pointerOperand, index, indexOperand->getType(),
3331 /*Accessed*/ false);
3332
3333 const PointerType *pointerType
3334 = pointerOperand->getType()->getAs<PointerType>();
3335 if (!pointerType) {
3336 QualType objectType = pointerOperand->getType()
3337 ->castAs<ObjCObjectPointerType>()
3338 ->getPointeeType();
3339 llvm::Value *objectSize
3340 = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
3341
3342 index = CGF.Builder.CreateMul(index, objectSize);
3343
3344 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
3345 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
3346 return CGF.Builder.CreateBitCast(result, pointer->getType());
3347 }
3348
3349 QualType elementType = pointerType->getPointeeType();
3350 if (const VariableArrayType *vla
3351 = CGF.getContext().getAsVariableArrayType(elementType)) {
3352 // The element count here is the total number of non-VLA elements.
3353 llvm::Value *numElements = CGF.getVLASize(vla).NumElts;
3354
3355 // Effectively, the multiply by the VLA size is part of the GEP.
3356 // GEP indexes are signed, and scaling an index isn't permitted to
3357 // signed-overflow, so we use the same semantics for our explicit
3358 // multiply. We suppress this if overflow is not undefined behavior.
3359 if (CGF.getLangOpts().isSignedOverflowDefined()) {
3360 index = CGF.Builder.CreateMul(index, numElements, "vla.index");
3361 pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr");
3362 } else {
3363 index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
3364 pointer =
3365 CGF.EmitCheckedInBoundsGEP(pointer, index, isSigned, isSubtraction,
3366 op.E->getExprLoc(), "add.ptr");
3367 }
3368 return pointer;
3369 }
3370
3371 // Explicitly handle GNU void* and function pointer arithmetic extensions. The
3372 // GNU void* casts amount to no-ops since our void* type is i8*, but this is
3373 // future proof.
3374 if (elementType->isVoidType() || elementType->isFunctionType()) {
3375 Value *result = CGF.EmitCastToVoidPtr(pointer);
3376 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
3377 return CGF.Builder.CreateBitCast(result, pointer->getType());
3378 }
3379
3380 if (CGF.getLangOpts().isSignedOverflowDefined())
3381 return CGF.Builder.CreateGEP(pointer, index, "add.ptr");
3382
3383 return CGF.EmitCheckedInBoundsGEP(pointer, index, isSigned, isSubtraction,
3384 op.E->getExprLoc(), "add.ptr");
3385 }
3386
3387 // Construct an fmuladd intrinsic to represent a fused mul-add of MulOp and
3388 // Addend. Use negMul and negAdd to negate the first operand of the Mul or
3389 // the add operand respectively. This allows fmuladd to represent a*b-c, or
3390 // c-a*b. Patterns in LLVM should catch the negated forms and translate them to
3391 // efficient operations.
buildFMulAdd(llvm::Instruction * MulOp,Value * Addend,const CodeGenFunction & CGF,CGBuilderTy & Builder,bool negMul,bool negAdd)3392 static Value* buildFMulAdd(llvm::Instruction *MulOp, Value *Addend,
3393 const CodeGenFunction &CGF, CGBuilderTy &Builder,
3394 bool negMul, bool negAdd) {
3395 assert(!(negMul && negAdd) && "Only one of negMul and negAdd should be set.");
3396
3397 Value *MulOp0 = MulOp->getOperand(0);
3398 Value *MulOp1 = MulOp->getOperand(1);
3399 if (negMul)
3400 MulOp0 = Builder.CreateFNeg(MulOp0, "neg");
3401 if (negAdd)
3402 Addend = Builder.CreateFNeg(Addend, "neg");
3403
3404 Value *FMulAdd = nullptr;
3405 if (Builder.getIsFPConstrained()) {
3406 assert(isa<llvm::ConstrainedFPIntrinsic>(MulOp) &&
3407 "Only constrained operation should be created when Builder is in FP "
3408 "constrained mode");
3409 FMulAdd = Builder.CreateConstrainedFPCall(
3410 CGF.CGM.getIntrinsic(llvm::Intrinsic::experimental_constrained_fmuladd,
3411 Addend->getType()),
3412 {MulOp0, MulOp1, Addend});
3413 } else {
3414 FMulAdd = Builder.CreateCall(
3415 CGF.CGM.getIntrinsic(llvm::Intrinsic::fmuladd, Addend->getType()),
3416 {MulOp0, MulOp1, Addend});
3417 }
3418 MulOp->eraseFromParent();
3419
3420 return FMulAdd;
3421 }
3422
3423 // Check whether it would be legal to emit an fmuladd intrinsic call to
3424 // represent op and if so, build the fmuladd.
3425 //
3426 // Checks that (a) the operation is fusable, and (b) -ffp-contract=on.
3427 // Does NOT check the type of the operation - it's assumed that this function
3428 // will be called from contexts where it's known that the type is contractable.
tryEmitFMulAdd(const BinOpInfo & op,const CodeGenFunction & CGF,CGBuilderTy & Builder,bool isSub=false)3429 static Value* tryEmitFMulAdd(const BinOpInfo &op,
3430 const CodeGenFunction &CGF, CGBuilderTy &Builder,
3431 bool isSub=false) {
3432
3433 assert((op.Opcode == BO_Add || op.Opcode == BO_AddAssign ||
3434 op.Opcode == BO_Sub || op.Opcode == BO_SubAssign) &&
3435 "Only fadd/fsub can be the root of an fmuladd.");
3436
3437 // Check whether this op is marked as fusable.
3438 if (!op.FPFeatures.allowFPContractWithinStatement())
3439 return nullptr;
3440
3441 // We have a potentially fusable op. Look for a mul on one of the operands.
3442 // Also, make sure that the mul result isn't used directly. In that case,
3443 // there's no point creating a muladd operation.
3444 if (auto *LHSBinOp = dyn_cast<llvm::BinaryOperator>(op.LHS)) {
3445 if (LHSBinOp->getOpcode() == llvm::Instruction::FMul &&
3446 LHSBinOp->use_empty())
3447 return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub);
3448 }
3449 if (auto *RHSBinOp = dyn_cast<llvm::BinaryOperator>(op.RHS)) {
3450 if (RHSBinOp->getOpcode() == llvm::Instruction::FMul &&
3451 RHSBinOp->use_empty())
3452 return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false);
3453 }
3454
3455 if (auto *LHSBinOp = dyn_cast<llvm::CallBase>(op.LHS)) {
3456 if (LHSBinOp->getIntrinsicID() ==
3457 llvm::Intrinsic::experimental_constrained_fmul &&
3458 LHSBinOp->use_empty())
3459 return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub);
3460 }
3461 if (auto *RHSBinOp = dyn_cast<llvm::CallBase>(op.RHS)) {
3462 if (RHSBinOp->getIntrinsicID() ==
3463 llvm::Intrinsic::experimental_constrained_fmul &&
3464 RHSBinOp->use_empty())
3465 return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false);
3466 }
3467
3468 return nullptr;
3469 }
3470
EmitAdd(const BinOpInfo & op)3471 Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
3472 if (op.LHS->getType()->isPointerTy() ||
3473 op.RHS->getType()->isPointerTy())
3474 return emitPointerArithmetic(CGF, op, CodeGenFunction::NotSubtraction);
3475
3476 if (op.Ty->isSignedIntegerOrEnumerationType()) {
3477 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
3478 case LangOptions::SOB_Defined:
3479 return Builder.CreateAdd(op.LHS, op.RHS, "add");
3480 case LangOptions::SOB_Undefined:
3481 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
3482 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
3483 LLVM_FALLTHROUGH;
3484 case LangOptions::SOB_Trapping:
3485 if (CanElideOverflowCheck(CGF.getContext(), op))
3486 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
3487 return EmitOverflowCheckedBinOp(op);
3488 }
3489 }
3490
3491 if (op.Ty->isConstantMatrixType()) {
3492 llvm::MatrixBuilder<CGBuilderTy> MB(Builder);
3493 return MB.CreateAdd(op.LHS, op.RHS);
3494 }
3495
3496 if (op.Ty->isUnsignedIntegerType() &&
3497 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
3498 !CanElideOverflowCheck(CGF.getContext(), op))
3499 return EmitOverflowCheckedBinOp(op);
3500
3501 if (op.LHS->getType()->isFPOrFPVectorTy()) {
3502 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
3503 // Try to form an fmuladd.
3504 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder))
3505 return FMulAdd;
3506
3507 return Builder.CreateFAdd(op.LHS, op.RHS, "add");
3508 }
3509
3510 if (op.isFixedPointOp())
3511 return EmitFixedPointBinOp(op);
3512
3513 return Builder.CreateAdd(op.LHS, op.RHS, "add");
3514 }
3515
3516 /// The resulting value must be calculated with exact precision, so the operands
3517 /// may not be the same type.
EmitFixedPointBinOp(const BinOpInfo & op)3518 Value *ScalarExprEmitter::EmitFixedPointBinOp(const BinOpInfo &op) {
3519 using llvm::APSInt;
3520 using llvm::ConstantInt;
3521
3522 // This is either a binary operation where at least one of the operands is
3523 // a fixed-point type, or a unary operation where the operand is a fixed-point
3524 // type. The result type of a binary operation is determined by
3525 // Sema::handleFixedPointConversions().
3526 QualType ResultTy = op.Ty;
3527 QualType LHSTy, RHSTy;
3528 if (const auto *BinOp = dyn_cast<BinaryOperator>(op.E)) {
3529 RHSTy = BinOp->getRHS()->getType();
3530 if (const auto *CAO = dyn_cast<CompoundAssignOperator>(BinOp)) {
3531 // For compound assignment, the effective type of the LHS at this point
3532 // is the computation LHS type, not the actual LHS type, and the final
3533 // result type is not the type of the expression but rather the
3534 // computation result type.
3535 LHSTy = CAO->getComputationLHSType();
3536 ResultTy = CAO->getComputationResultType();
3537 } else
3538 LHSTy = BinOp->getLHS()->getType();
3539 } else if (const auto *UnOp = dyn_cast<UnaryOperator>(op.E)) {
3540 LHSTy = UnOp->getSubExpr()->getType();
3541 RHSTy = UnOp->getSubExpr()->getType();
3542 }
3543 ASTContext &Ctx = CGF.getContext();
3544 Value *LHS = op.LHS;
3545 Value *RHS = op.RHS;
3546
3547 auto LHSFixedSema = Ctx.getFixedPointSemantics(LHSTy);
3548 auto RHSFixedSema = Ctx.getFixedPointSemantics(RHSTy);
3549 auto ResultFixedSema = Ctx.getFixedPointSemantics(ResultTy);
3550 auto CommonFixedSema = LHSFixedSema.getCommonSemantics(RHSFixedSema);
3551
3552 // Perform the actual operation.
3553 Value *Result;
3554 llvm::FixedPointBuilder<CGBuilderTy> FPBuilder(Builder);
3555 switch (op.Opcode) {
3556 case BO_AddAssign:
3557 case BO_Add:
3558 Result = FPBuilder.CreateAdd(LHS, LHSFixedSema, RHS, RHSFixedSema);
3559 break;
3560 case BO_SubAssign:
3561 case BO_Sub:
3562 Result = FPBuilder.CreateSub(LHS, LHSFixedSema, RHS, RHSFixedSema);
3563 break;
3564 case BO_MulAssign:
3565 case BO_Mul:
3566 Result = FPBuilder.CreateMul(LHS, LHSFixedSema, RHS, RHSFixedSema);
3567 break;
3568 case BO_DivAssign:
3569 case BO_Div:
3570 Result = FPBuilder.CreateDiv(LHS, LHSFixedSema, RHS, RHSFixedSema);
3571 break;
3572 case BO_ShlAssign:
3573 case BO_Shl:
3574 Result = FPBuilder.CreateShl(LHS, LHSFixedSema, RHS);
3575 break;
3576 case BO_ShrAssign:
3577 case BO_Shr:
3578 Result = FPBuilder.CreateShr(LHS, LHSFixedSema, RHS);
3579 break;
3580 case BO_LT:
3581 return FPBuilder.CreateLT(LHS, LHSFixedSema, RHS, RHSFixedSema);
3582 case BO_GT:
3583 return FPBuilder.CreateGT(LHS, LHSFixedSema, RHS, RHSFixedSema);
3584 case BO_LE:
3585 return FPBuilder.CreateLE(LHS, LHSFixedSema, RHS, RHSFixedSema);
3586 case BO_GE:
3587 return FPBuilder.CreateGE(LHS, LHSFixedSema, RHS, RHSFixedSema);
3588 case BO_EQ:
3589 // For equality operations, we assume any padding bits on unsigned types are
3590 // zero'd out. They could be overwritten through non-saturating operations
3591 // that cause overflow, but this leads to undefined behavior.
3592 return FPBuilder.CreateEQ(LHS, LHSFixedSema, RHS, RHSFixedSema);
3593 case BO_NE:
3594 return FPBuilder.CreateNE(LHS, LHSFixedSema, RHS, RHSFixedSema);
3595 case BO_Cmp:
3596 case BO_LAnd:
3597 case BO_LOr:
3598 llvm_unreachable("Found unimplemented fixed point binary operation");
3599 case BO_PtrMemD:
3600 case BO_PtrMemI:
3601 case BO_Rem:
3602 case BO_Xor:
3603 case BO_And:
3604 case BO_Or:
3605 case BO_Assign:
3606 case BO_RemAssign:
3607 case BO_AndAssign:
3608 case BO_XorAssign:
3609 case BO_OrAssign:
3610 case BO_Comma:
3611 llvm_unreachable("Found unsupported binary operation for fixed point types.");
3612 }
3613
3614 bool IsShift = BinaryOperator::isShiftOp(op.Opcode) ||
3615 BinaryOperator::isShiftAssignOp(op.Opcode);
3616 // Convert to the result type.
3617 return FPBuilder.CreateFixedToFixed(Result, IsShift ? LHSFixedSema
3618 : CommonFixedSema,
3619 ResultFixedSema);
3620 }
3621
EmitSub(const BinOpInfo & op)3622 Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
3623 // The LHS is always a pointer if either side is.
3624 if (!op.LHS->getType()->isPointerTy()) {
3625 if (op.Ty->isSignedIntegerOrEnumerationType()) {
3626 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
3627 case LangOptions::SOB_Defined:
3628 return Builder.CreateSub(op.LHS, op.RHS, "sub");
3629 case LangOptions::SOB_Undefined:
3630 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
3631 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
3632 LLVM_FALLTHROUGH;
3633 case LangOptions::SOB_Trapping:
3634 if (CanElideOverflowCheck(CGF.getContext(), op))
3635 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
3636 return EmitOverflowCheckedBinOp(op);
3637 }
3638 }
3639
3640 if (op.Ty->isConstantMatrixType()) {
3641 llvm::MatrixBuilder<CGBuilderTy> MB(Builder);
3642 return MB.CreateSub(op.LHS, op.RHS);
3643 }
3644
3645 if (op.Ty->isUnsignedIntegerType() &&
3646 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
3647 !CanElideOverflowCheck(CGF.getContext(), op))
3648 return EmitOverflowCheckedBinOp(op);
3649
3650 if (op.LHS->getType()->isFPOrFPVectorTy()) {
3651 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
3652 // Try to form an fmuladd.
3653 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder, true))
3654 return FMulAdd;
3655 return Builder.CreateFSub(op.LHS, op.RHS, "sub");
3656 }
3657
3658 if (op.isFixedPointOp())
3659 return EmitFixedPointBinOp(op);
3660
3661 return Builder.CreateSub(op.LHS, op.RHS, "sub");
3662 }
3663
3664 // If the RHS is not a pointer, then we have normal pointer
3665 // arithmetic.
3666 if (!op.RHS->getType()->isPointerTy())
3667 return emitPointerArithmetic(CGF, op, CodeGenFunction::IsSubtraction);
3668
3669 // Otherwise, this is a pointer subtraction.
3670
3671 // Do the raw subtraction part.
3672 llvm::Value *LHS
3673 = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
3674 llvm::Value *RHS
3675 = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
3676 Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
3677
3678 // Okay, figure out the element size.
3679 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
3680 QualType elementType = expr->getLHS()->getType()->getPointeeType();
3681
3682 llvm::Value *divisor = nullptr;
3683
3684 // For a variable-length array, this is going to be non-constant.
3685 if (const VariableArrayType *vla
3686 = CGF.getContext().getAsVariableArrayType(elementType)) {
3687 auto VlaSize = CGF.getVLASize(vla);
3688 elementType = VlaSize.Type;
3689 divisor = VlaSize.NumElts;
3690
3691 // Scale the number of non-VLA elements by the non-VLA element size.
3692 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
3693 if (!eltSize.isOne())
3694 divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
3695
3696 // For everything elese, we can just compute it, safe in the
3697 // assumption that Sema won't let anything through that we can't
3698 // safely compute the size of.
3699 } else {
3700 CharUnits elementSize;
3701 // Handle GCC extension for pointer arithmetic on void* and
3702 // function pointer types.
3703 if (elementType->isVoidType() || elementType->isFunctionType())
3704 elementSize = CharUnits::One();
3705 else
3706 elementSize = CGF.getContext().getTypeSizeInChars(elementType);
3707
3708 // Don't even emit the divide for element size of 1.
3709 if (elementSize.isOne())
3710 return diffInChars;
3711
3712 divisor = CGF.CGM.getSize(elementSize);
3713 }
3714
3715 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
3716 // pointer difference in C is only defined in the case where both operands
3717 // are pointing to elements of an array.
3718 return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
3719 }
3720
GetWidthMinusOneValue(Value * LHS,Value * RHS)3721 Value *ScalarExprEmitter::GetWidthMinusOneValue(Value* LHS,Value* RHS) {
3722 llvm::IntegerType *Ty;
3723 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(LHS->getType()))
3724 Ty = cast<llvm::IntegerType>(VT->getElementType());
3725 else
3726 Ty = cast<llvm::IntegerType>(LHS->getType());
3727 return llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth() - 1);
3728 }
3729
ConstrainShiftValue(Value * LHS,Value * RHS,const Twine & Name)3730 Value *ScalarExprEmitter::ConstrainShiftValue(Value *LHS, Value *RHS,
3731 const Twine &Name) {
3732 llvm::IntegerType *Ty;
3733 if (auto *VT = dyn_cast<llvm::VectorType>(LHS->getType()))
3734 Ty = cast<llvm::IntegerType>(VT->getElementType());
3735 else
3736 Ty = cast<llvm::IntegerType>(LHS->getType());
3737
3738 if (llvm::isPowerOf2_64(Ty->getBitWidth()))
3739 return Builder.CreateAnd(RHS, GetWidthMinusOneValue(LHS, RHS), Name);
3740
3741 return Builder.CreateURem(
3742 RHS, llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth()), Name);
3743 }
3744
EmitShl(const BinOpInfo & Ops)3745 Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
3746 // TODO: This misses out on the sanitizer check below.
3747 if (Ops.isFixedPointOp())
3748 return EmitFixedPointBinOp(Ops);
3749
3750 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
3751 // RHS to the same size as the LHS.
3752 Value *RHS = Ops.RHS;
3753 if (Ops.LHS->getType() != RHS->getType())
3754 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
3755
3756 bool SanitizeSignedBase = CGF.SanOpts.has(SanitizerKind::ShiftBase) &&
3757 Ops.Ty->hasSignedIntegerRepresentation() &&
3758 !CGF.getLangOpts().isSignedOverflowDefined() &&
3759 !CGF.getLangOpts().CPlusPlus20;
3760 bool SanitizeUnsignedBase =
3761 CGF.SanOpts.has(SanitizerKind::UnsignedShiftBase) &&
3762 Ops.Ty->hasUnsignedIntegerRepresentation();
3763 bool SanitizeBase = SanitizeSignedBase || SanitizeUnsignedBase;
3764 bool SanitizeExponent = CGF.SanOpts.has(SanitizerKind::ShiftExponent);
3765 // OpenCL 6.3j: shift values are effectively % word size of LHS.
3766 if (CGF.getLangOpts().OpenCL)
3767 RHS = ConstrainShiftValue(Ops.LHS, RHS, "shl.mask");
3768 else if ((SanitizeBase || SanitizeExponent) &&
3769 isa<llvm::IntegerType>(Ops.LHS->getType())) {
3770 CodeGenFunction::SanitizerScope SanScope(&CGF);
3771 SmallVector<std::pair<Value *, SanitizerMask>, 2> Checks;
3772 llvm::Value *WidthMinusOne = GetWidthMinusOneValue(Ops.LHS, Ops.RHS);
3773 llvm::Value *ValidExponent = Builder.CreateICmpULE(Ops.RHS, WidthMinusOne);
3774
3775 if (SanitizeExponent) {
3776 Checks.push_back(
3777 std::make_pair(ValidExponent, SanitizerKind::ShiftExponent));
3778 }
3779
3780 if (SanitizeBase) {
3781 // Check whether we are shifting any non-zero bits off the top of the
3782 // integer. We only emit this check if exponent is valid - otherwise
3783 // instructions below will have undefined behavior themselves.
3784 llvm::BasicBlock *Orig = Builder.GetInsertBlock();
3785 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
3786 llvm::BasicBlock *CheckShiftBase = CGF.createBasicBlock("check");
3787 Builder.CreateCondBr(ValidExponent, CheckShiftBase, Cont);
3788 llvm::Value *PromotedWidthMinusOne =
3789 (RHS == Ops.RHS) ? WidthMinusOne
3790 : GetWidthMinusOneValue(Ops.LHS, RHS);
3791 CGF.EmitBlock(CheckShiftBase);
3792 llvm::Value *BitsShiftedOff = Builder.CreateLShr(
3793 Ops.LHS, Builder.CreateSub(PromotedWidthMinusOne, RHS, "shl.zeros",
3794 /*NUW*/ true, /*NSW*/ true),
3795 "shl.check");
3796 if (SanitizeUnsignedBase || CGF.getLangOpts().CPlusPlus) {
3797 // In C99, we are not permitted to shift a 1 bit into the sign bit.
3798 // Under C++11's rules, shifting a 1 bit into the sign bit is
3799 // OK, but shifting a 1 bit out of it is not. (C89 and C++03 don't
3800 // define signed left shifts, so we use the C99 and C++11 rules there).
3801 // Unsigned shifts can always shift into the top bit.
3802 llvm::Value *One = llvm::ConstantInt::get(BitsShiftedOff->getType(), 1);
3803 BitsShiftedOff = Builder.CreateLShr(BitsShiftedOff, One);
3804 }
3805 llvm::Value *Zero = llvm::ConstantInt::get(BitsShiftedOff->getType(), 0);
3806 llvm::Value *ValidBase = Builder.CreateICmpEQ(BitsShiftedOff, Zero);
3807 CGF.EmitBlock(Cont);
3808 llvm::PHINode *BaseCheck = Builder.CreatePHI(ValidBase->getType(), 2);
3809 BaseCheck->addIncoming(Builder.getTrue(), Orig);
3810 BaseCheck->addIncoming(ValidBase, CheckShiftBase);
3811 Checks.push_back(std::make_pair(
3812 BaseCheck, SanitizeSignedBase ? SanitizerKind::ShiftBase
3813 : SanitizerKind::UnsignedShiftBase));
3814 }
3815
3816 assert(!Checks.empty());
3817 EmitBinOpCheck(Checks, Ops);
3818 }
3819
3820 return Builder.CreateShl(Ops.LHS, RHS, "shl");
3821 }
3822
EmitShr(const BinOpInfo & Ops)3823 Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
3824 // TODO: This misses out on the sanitizer check below.
3825 if (Ops.isFixedPointOp())
3826 return EmitFixedPointBinOp(Ops);
3827
3828 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
3829 // RHS to the same size as the LHS.
3830 Value *RHS = Ops.RHS;
3831 if (Ops.LHS->getType() != RHS->getType())
3832 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
3833
3834 // OpenCL 6.3j: shift values are effectively % word size of LHS.
3835 if (CGF.getLangOpts().OpenCL)
3836 RHS = ConstrainShiftValue(Ops.LHS, RHS, "shr.mask");
3837 else if (CGF.SanOpts.has(SanitizerKind::ShiftExponent) &&
3838 isa<llvm::IntegerType>(Ops.LHS->getType())) {
3839 CodeGenFunction::SanitizerScope SanScope(&CGF);
3840 llvm::Value *Valid =
3841 Builder.CreateICmpULE(RHS, GetWidthMinusOneValue(Ops.LHS, RHS));
3842 EmitBinOpCheck(std::make_pair(Valid, SanitizerKind::ShiftExponent), Ops);
3843 }
3844
3845 if (Ops.Ty->hasUnsignedIntegerRepresentation())
3846 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
3847 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
3848 }
3849
3850 enum IntrinsicType { VCMPEQ, VCMPGT };
3851 // return corresponding comparison intrinsic for given vector type
GetIntrinsic(IntrinsicType IT,BuiltinType::Kind ElemKind)3852 static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
3853 BuiltinType::Kind ElemKind) {
3854 switch (ElemKind) {
3855 default: llvm_unreachable("unexpected element type");
3856 case BuiltinType::Char_U:
3857 case BuiltinType::UChar:
3858 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
3859 llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
3860 case BuiltinType::Char_S:
3861 case BuiltinType::SChar:
3862 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
3863 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
3864 case BuiltinType::UShort:
3865 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
3866 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
3867 case BuiltinType::Short:
3868 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
3869 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
3870 case BuiltinType::UInt:
3871 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
3872 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
3873 case BuiltinType::Int:
3874 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
3875 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
3876 case BuiltinType::ULong:
3877 case BuiltinType::ULongLong:
3878 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p :
3879 llvm::Intrinsic::ppc_altivec_vcmpgtud_p;
3880 case BuiltinType::Long:
3881 case BuiltinType::LongLong:
3882 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p :
3883 llvm::Intrinsic::ppc_altivec_vcmpgtsd_p;
3884 case BuiltinType::Float:
3885 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
3886 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
3887 case BuiltinType::Double:
3888 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_vsx_xvcmpeqdp_p :
3889 llvm::Intrinsic::ppc_vsx_xvcmpgtdp_p;
3890 case BuiltinType::UInt128:
3891 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequq_p
3892 : llvm::Intrinsic::ppc_altivec_vcmpgtuq_p;
3893 case BuiltinType::Int128:
3894 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequq_p
3895 : llvm::Intrinsic::ppc_altivec_vcmpgtsq_p;
3896 }
3897 }
3898
EmitCompare(const BinaryOperator * E,llvm::CmpInst::Predicate UICmpOpc,llvm::CmpInst::Predicate SICmpOpc,llvm::CmpInst::Predicate FCmpOpc,bool IsSignaling)3899 Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,
3900 llvm::CmpInst::Predicate UICmpOpc,
3901 llvm::CmpInst::Predicate SICmpOpc,
3902 llvm::CmpInst::Predicate FCmpOpc,
3903 bool IsSignaling) {
3904 TestAndClearIgnoreResultAssign();
3905 Value *Result;
3906 QualType LHSTy = E->getLHS()->getType();
3907 QualType RHSTy = E->getRHS()->getType();
3908 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
3909 assert(E->getOpcode() == BO_EQ ||
3910 E->getOpcode() == BO_NE);
3911 Value *LHS = CGF.EmitScalarExpr(E->getLHS());
3912 Value *RHS = CGF.EmitScalarExpr(E->getRHS());
3913 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
3914 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
3915 } else if (!LHSTy->isAnyComplexType() && !RHSTy->isAnyComplexType()) {
3916 BinOpInfo BOInfo = EmitBinOps(E);
3917 Value *LHS = BOInfo.LHS;
3918 Value *RHS = BOInfo.RHS;
3919
3920 // If AltiVec, the comparison results in a numeric type, so we use
3921 // intrinsics comparing vectors and giving 0 or 1 as a result
3922 if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
3923 // constants for mapping CR6 register bits to predicate result
3924 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
3925
3926 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
3927
3928 // in several cases vector arguments order will be reversed
3929 Value *FirstVecArg = LHS,
3930 *SecondVecArg = RHS;
3931
3932 QualType ElTy = LHSTy->castAs<VectorType>()->getElementType();
3933 BuiltinType::Kind ElementKind = ElTy->castAs<BuiltinType>()->getKind();
3934
3935 switch(E->getOpcode()) {
3936 default: llvm_unreachable("is not a comparison operation");
3937 case BO_EQ:
3938 CR6 = CR6_LT;
3939 ID = GetIntrinsic(VCMPEQ, ElementKind);
3940 break;
3941 case BO_NE:
3942 CR6 = CR6_EQ;
3943 ID = GetIntrinsic(VCMPEQ, ElementKind);
3944 break;
3945 case BO_LT:
3946 CR6 = CR6_LT;
3947 ID = GetIntrinsic(VCMPGT, ElementKind);
3948 std::swap(FirstVecArg, SecondVecArg);
3949 break;
3950 case BO_GT:
3951 CR6 = CR6_LT;
3952 ID = GetIntrinsic(VCMPGT, ElementKind);
3953 break;
3954 case BO_LE:
3955 if (ElementKind == BuiltinType::Float) {
3956 CR6 = CR6_LT;
3957 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
3958 std::swap(FirstVecArg, SecondVecArg);
3959 }
3960 else {
3961 CR6 = CR6_EQ;
3962 ID = GetIntrinsic(VCMPGT, ElementKind);
3963 }
3964 break;
3965 case BO_GE:
3966 if (ElementKind == BuiltinType::Float) {
3967 CR6 = CR6_LT;
3968 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
3969 }
3970 else {
3971 CR6 = CR6_EQ;
3972 ID = GetIntrinsic(VCMPGT, ElementKind);
3973 std::swap(FirstVecArg, SecondVecArg);
3974 }
3975 break;
3976 }
3977
3978 Value *CR6Param = Builder.getInt32(CR6);
3979 llvm::Function *F = CGF.CGM.getIntrinsic(ID);
3980 Result = Builder.CreateCall(F, {CR6Param, FirstVecArg, SecondVecArg});
3981
3982 // The result type of intrinsic may not be same as E->getType().
3983 // If E->getType() is not BoolTy, EmitScalarConversion will do the
3984 // conversion work. If E->getType() is BoolTy, EmitScalarConversion will
3985 // do nothing, if ResultTy is not i1 at the same time, it will cause
3986 // crash later.
3987 llvm::IntegerType *ResultTy = cast<llvm::IntegerType>(Result->getType());
3988 if (ResultTy->getBitWidth() > 1 &&
3989 E->getType() == CGF.getContext().BoolTy)
3990 Result = Builder.CreateTrunc(Result, Builder.getInt1Ty());
3991 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(),
3992 E->getExprLoc());
3993 }
3994
3995 if (BOInfo.isFixedPointOp()) {
3996 Result = EmitFixedPointBinOp(BOInfo);
3997 } else if (LHS->getType()->isFPOrFPVectorTy()) {
3998 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, BOInfo.FPFeatures);
3999 if (!IsSignaling)
4000 Result = Builder.CreateFCmp(FCmpOpc, LHS, RHS, "cmp");
4001 else
4002 Result = Builder.CreateFCmpS(FCmpOpc, LHS, RHS, "cmp");
4003 } else if (LHSTy->hasSignedIntegerRepresentation()) {
4004 Result = Builder.CreateICmp(SICmpOpc, LHS, RHS, "cmp");
4005 } else {
4006 // Unsigned integers and pointers.
4007
4008 if (CGF.CGM.getCodeGenOpts().StrictVTablePointers &&
4009 !isa<llvm::ConstantPointerNull>(LHS) &&
4010 !isa<llvm::ConstantPointerNull>(RHS)) {
4011
4012 // Dynamic information is required to be stripped for comparisons,
4013 // because it could leak the dynamic information. Based on comparisons
4014 // of pointers to dynamic objects, the optimizer can replace one pointer
4015 // with another, which might be incorrect in presence of invariant
4016 // groups. Comparison with null is safe because null does not carry any
4017 // dynamic information.
4018 if (LHSTy.mayBeDynamicClass())
4019 LHS = Builder.CreateStripInvariantGroup(LHS);
4020 if (RHSTy.mayBeDynamicClass())
4021 RHS = Builder.CreateStripInvariantGroup(RHS);
4022 }
4023
4024 Result = Builder.CreateICmp(UICmpOpc, LHS, RHS, "cmp");
4025 }
4026
4027 // If this is a vector comparison, sign extend the result to the appropriate
4028 // vector integer type and return it (don't convert to bool).
4029 if (LHSTy->isVectorType())
4030 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
4031
4032 } else {
4033 // Complex Comparison: can only be an equality comparison.
4034 CodeGenFunction::ComplexPairTy LHS, RHS;
4035 QualType CETy;
4036 if (auto *CTy = LHSTy->getAs<ComplexType>()) {
4037 LHS = CGF.EmitComplexExpr(E->getLHS());
4038 CETy = CTy->getElementType();
4039 } else {
4040 LHS.first = Visit(E->getLHS());
4041 LHS.second = llvm::Constant::getNullValue(LHS.first->getType());
4042 CETy = LHSTy;
4043 }
4044 if (auto *CTy = RHSTy->getAs<ComplexType>()) {
4045 RHS = CGF.EmitComplexExpr(E->getRHS());
4046 assert(CGF.getContext().hasSameUnqualifiedType(CETy,
4047 CTy->getElementType()) &&
4048 "The element types must always match.");
4049 (void)CTy;
4050 } else {
4051 RHS.first = Visit(E->getRHS());
4052 RHS.second = llvm::Constant::getNullValue(RHS.first->getType());
4053 assert(CGF.getContext().hasSameUnqualifiedType(CETy, RHSTy) &&
4054 "The element types must always match.");
4055 }
4056
4057 Value *ResultR, *ResultI;
4058 if (CETy->isRealFloatingType()) {
4059 // As complex comparisons can only be equality comparisons, they
4060 // are never signaling comparisons.
4061 ResultR = Builder.CreateFCmp(FCmpOpc, LHS.first, RHS.first, "cmp.r");
4062 ResultI = Builder.CreateFCmp(FCmpOpc, LHS.second, RHS.second, "cmp.i");
4063 } else {
4064 // Complex comparisons can only be equality comparisons. As such, signed
4065 // and unsigned opcodes are the same.
4066 ResultR = Builder.CreateICmp(UICmpOpc, LHS.first, RHS.first, "cmp.r");
4067 ResultI = Builder.CreateICmp(UICmpOpc, LHS.second, RHS.second, "cmp.i");
4068 }
4069
4070 if (E->getOpcode() == BO_EQ) {
4071 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
4072 } else {
4073 assert(E->getOpcode() == BO_NE &&
4074 "Complex comparison other than == or != ?");
4075 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
4076 }
4077 }
4078
4079 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(),
4080 E->getExprLoc());
4081 }
4082
VisitBinAssign(const BinaryOperator * E)4083 Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
4084 bool Ignore = TestAndClearIgnoreResultAssign();
4085
4086 Value *RHS;
4087 LValue LHS;
4088
4089 switch (E->getLHS()->getType().getObjCLifetime()) {
4090 case Qualifiers::OCL_Strong:
4091 std::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
4092 break;
4093
4094 case Qualifiers::OCL_Autoreleasing:
4095 std::tie(LHS, RHS) = CGF.EmitARCStoreAutoreleasing(E);
4096 break;
4097
4098 case Qualifiers::OCL_ExplicitNone:
4099 std::tie(LHS, RHS) = CGF.EmitARCStoreUnsafeUnretained(E, Ignore);
4100 break;
4101
4102 case Qualifiers::OCL_Weak:
4103 RHS = Visit(E->getRHS());
4104 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
4105 RHS = CGF.EmitARCStoreWeak(LHS.getAddress(CGF), RHS, Ignore);
4106 break;
4107
4108 case Qualifiers::OCL_None:
4109 // __block variables need to have the rhs evaluated first, plus
4110 // this should improve codegen just a little.
4111 RHS = Visit(E->getRHS());
4112 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
4113
4114 // Store the value into the LHS. Bit-fields are handled specially
4115 // because the result is altered by the store, i.e., [C99 6.5.16p1]
4116 // 'An assignment expression has the value of the left operand after
4117 // the assignment...'.
4118 if (LHS.isBitField()) {
4119 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
4120 } else {
4121 CGF.EmitNullabilityCheck(LHS, RHS, E->getExprLoc());
4122 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
4123 }
4124 }
4125
4126 // If the result is clearly ignored, return now.
4127 if (Ignore)
4128 return nullptr;
4129
4130 // The result of an assignment in C is the assigned r-value.
4131 if (!CGF.getLangOpts().CPlusPlus)
4132 return RHS;
4133
4134 // If the lvalue is non-volatile, return the computed value of the assignment.
4135 if (!LHS.isVolatileQualified())
4136 return RHS;
4137
4138 // Otherwise, reload the value.
4139 return EmitLoadOfLValue(LHS, E->getExprLoc());
4140 }
4141
VisitBinLAnd(const BinaryOperator * E)4142 Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
4143 // Perform vector logical and on comparisons with zero vectors.
4144 if (E->getType()->isVectorType()) {
4145 CGF.incrementProfileCounter(E);
4146
4147 Value *LHS = Visit(E->getLHS());
4148 Value *RHS = Visit(E->getRHS());
4149 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
4150 if (LHS->getType()->isFPOrFPVectorTy()) {
4151 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(
4152 CGF, E->getFPFeaturesInEffect(CGF.getLangOpts()));
4153 LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
4154 RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
4155 } else {
4156 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
4157 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
4158 }
4159 Value *And = Builder.CreateAnd(LHS, RHS);
4160 return Builder.CreateSExt(And, ConvertType(E->getType()), "sext");
4161 }
4162
4163 llvm::Type *ResTy = ConvertType(E->getType());
4164
4165 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
4166 // If we have 1 && X, just emit X without inserting the control flow.
4167 bool LHSCondVal;
4168 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
4169 if (LHSCondVal) { // If we have 1 && X, just emit X.
4170 CGF.incrementProfileCounter(E);
4171
4172 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
4173 // ZExt result to int or bool.
4174 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
4175 }
4176
4177 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
4178 if (!CGF.ContainsLabel(E->getRHS()))
4179 return llvm::Constant::getNullValue(ResTy);
4180 }
4181
4182 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
4183 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
4184
4185 CodeGenFunction::ConditionalEvaluation eval(CGF);
4186
4187 // Branch on the LHS first. If it is false, go to the failure (cont) block.
4188 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock,
4189 CGF.getProfileCount(E->getRHS()));
4190
4191 // Any edges into the ContBlock are now from an (indeterminate number of)
4192 // edges from this first condition. All of these values will be false. Start
4193 // setting up the PHI node in the Cont Block for this.
4194 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
4195 "", ContBlock);
4196 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
4197 PI != PE; ++PI)
4198 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
4199
4200 eval.begin(CGF);
4201 CGF.EmitBlock(RHSBlock);
4202 CGF.incrementProfileCounter(E);
4203 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
4204 eval.end(CGF);
4205
4206 // Reaquire the RHS block, as there may be subblocks inserted.
4207 RHSBlock = Builder.GetInsertBlock();
4208
4209 // Emit an unconditional branch from this block to ContBlock.
4210 {
4211 // There is no need to emit line number for unconditional branch.
4212 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
4213 CGF.EmitBlock(ContBlock);
4214 }
4215 // Insert an entry into the phi node for the edge with the value of RHSCond.
4216 PN->addIncoming(RHSCond, RHSBlock);
4217
4218 // Artificial location to preserve the scope information
4219 {
4220 auto NL = ApplyDebugLocation::CreateArtificial(CGF);
4221 PN->setDebugLoc(Builder.getCurrentDebugLocation());
4222 }
4223
4224 // ZExt result to int.
4225 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
4226 }
4227
VisitBinLOr(const BinaryOperator * E)4228 Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
4229 // Perform vector logical or on comparisons with zero vectors.
4230 if (E->getType()->isVectorType()) {
4231 CGF.incrementProfileCounter(E);
4232
4233 Value *LHS = Visit(E->getLHS());
4234 Value *RHS = Visit(E->getRHS());
4235 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
4236 if (LHS->getType()->isFPOrFPVectorTy()) {
4237 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(
4238 CGF, E->getFPFeaturesInEffect(CGF.getLangOpts()));
4239 LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
4240 RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
4241 } else {
4242 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
4243 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
4244 }
4245 Value *Or = Builder.CreateOr(LHS, RHS);
4246 return Builder.CreateSExt(Or, ConvertType(E->getType()), "sext");
4247 }
4248
4249 llvm::Type *ResTy = ConvertType(E->getType());
4250
4251 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
4252 // If we have 0 || X, just emit X without inserting the control flow.
4253 bool LHSCondVal;
4254 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
4255 if (!LHSCondVal) { // If we have 0 || X, just emit X.
4256 CGF.incrementProfileCounter(E);
4257
4258 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
4259 // ZExt result to int or bool.
4260 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
4261 }
4262
4263 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
4264 if (!CGF.ContainsLabel(E->getRHS()))
4265 return llvm::ConstantInt::get(ResTy, 1);
4266 }
4267
4268 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
4269 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
4270
4271 CodeGenFunction::ConditionalEvaluation eval(CGF);
4272
4273 // Branch on the LHS first. If it is true, go to the success (cont) block.
4274 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock,
4275 CGF.getCurrentProfileCount() -
4276 CGF.getProfileCount(E->getRHS()));
4277
4278 // Any edges into the ContBlock are now from an (indeterminate number of)
4279 // edges from this first condition. All of these values will be true. Start
4280 // setting up the PHI node in the Cont Block for this.
4281 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
4282 "", ContBlock);
4283 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
4284 PI != PE; ++PI)
4285 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
4286
4287 eval.begin(CGF);
4288
4289 // Emit the RHS condition as a bool value.
4290 CGF.EmitBlock(RHSBlock);
4291 CGF.incrementProfileCounter(E);
4292 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
4293
4294 eval.end(CGF);
4295
4296 // Reaquire the RHS block, as there may be subblocks inserted.
4297 RHSBlock = Builder.GetInsertBlock();
4298
4299 // Emit an unconditional branch from this block to ContBlock. Insert an entry
4300 // into the phi node for the edge with the value of RHSCond.
4301 CGF.EmitBlock(ContBlock);
4302 PN->addIncoming(RHSCond, RHSBlock);
4303
4304 // ZExt result to int.
4305 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
4306 }
4307
VisitBinComma(const BinaryOperator * E)4308 Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
4309 CGF.EmitIgnoredExpr(E->getLHS());
4310 CGF.EnsureInsertPoint();
4311 return Visit(E->getRHS());
4312 }
4313
4314 //===----------------------------------------------------------------------===//
4315 // Other Operators
4316 //===----------------------------------------------------------------------===//
4317
4318 /// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
4319 /// expression is cheap enough and side-effect-free enough to evaluate
4320 /// unconditionally instead of conditionally. This is used to convert control
4321 /// flow into selects in some cases.
isCheapEnoughToEvaluateUnconditionally(const Expr * E,CodeGenFunction & CGF)4322 static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
4323 CodeGenFunction &CGF) {
4324 // Anything that is an integer or floating point constant is fine.
4325 return E->IgnoreParens()->isEvaluatable(CGF.getContext());
4326
4327 // Even non-volatile automatic variables can't be evaluated unconditionally.
4328 // Referencing a thread_local may cause non-trivial initialization work to
4329 // occur. If we're inside a lambda and one of the variables is from the scope
4330 // outside the lambda, that function may have returned already. Reading its
4331 // locals is a bad idea. Also, these reads may introduce races there didn't
4332 // exist in the source-level program.
4333 }
4334
4335
4336 Value *ScalarExprEmitter::
VisitAbstractConditionalOperator(const AbstractConditionalOperator * E)4337 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
4338 TestAndClearIgnoreResultAssign();
4339
4340 // Bind the common expression if necessary.
4341 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
4342
4343 Expr *condExpr = E->getCond();
4344 Expr *lhsExpr = E->getTrueExpr();
4345 Expr *rhsExpr = E->getFalseExpr();
4346
4347 // If the condition constant folds and can be elided, try to avoid emitting
4348 // the condition and the dead arm.
4349 bool CondExprBool;
4350 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
4351 Expr *live = lhsExpr, *dead = rhsExpr;
4352 if (!CondExprBool) std::swap(live, dead);
4353
4354 // If the dead side doesn't have labels we need, just emit the Live part.
4355 if (!CGF.ContainsLabel(dead)) {
4356 if (CondExprBool)
4357 CGF.incrementProfileCounter(E);
4358 Value *Result = Visit(live);
4359
4360 // If the live part is a throw expression, it acts like it has a void
4361 // type, so evaluating it returns a null Value*. However, a conditional
4362 // with non-void type must return a non-null Value*.
4363 if (!Result && !E->getType()->isVoidType())
4364 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
4365
4366 return Result;
4367 }
4368 }
4369
4370 // OpenCL: If the condition is a vector, we can treat this condition like
4371 // the select function.
4372 if ((CGF.getLangOpts().OpenCL && condExpr->getType()->isVectorType()) ||
4373 condExpr->getType()->isExtVectorType()) {
4374 CGF.incrementProfileCounter(E);
4375
4376 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
4377 llvm::Value *LHS = Visit(lhsExpr);
4378 llvm::Value *RHS = Visit(rhsExpr);
4379
4380 llvm::Type *condType = ConvertType(condExpr->getType());
4381 auto *vecTy = cast<llvm::FixedVectorType>(condType);
4382
4383 unsigned numElem = vecTy->getNumElements();
4384 llvm::Type *elemType = vecTy->getElementType();
4385
4386 llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy);
4387 llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
4388 llvm::Value *tmp = Builder.CreateSExt(
4389 TestMSB, llvm::FixedVectorType::get(elemType, numElem), "sext");
4390 llvm::Value *tmp2 = Builder.CreateNot(tmp);
4391
4392 // Cast float to int to perform ANDs if necessary.
4393 llvm::Value *RHSTmp = RHS;
4394 llvm::Value *LHSTmp = LHS;
4395 bool wasCast = false;
4396 llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
4397 if (rhsVTy->getElementType()->isFloatingPointTy()) {
4398 RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
4399 LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
4400 wasCast = true;
4401 }
4402
4403 llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
4404 llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
4405 llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
4406 if (wasCast)
4407 tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
4408
4409 return tmp5;
4410 }
4411
4412 if (condExpr->getType()->isVectorType()) {
4413 CGF.incrementProfileCounter(E);
4414
4415 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
4416 llvm::Value *LHS = Visit(lhsExpr);
4417 llvm::Value *RHS = Visit(rhsExpr);
4418
4419 llvm::Type *CondType = ConvertType(condExpr->getType());
4420 auto *VecTy = cast<llvm::VectorType>(CondType);
4421 llvm::Value *ZeroVec = llvm::Constant::getNullValue(VecTy);
4422
4423 CondV = Builder.CreateICmpNE(CondV, ZeroVec, "vector_cond");
4424 return Builder.CreateSelect(CondV, LHS, RHS, "vector_select");
4425 }
4426
4427 // If this is a really simple expression (like x ? 4 : 5), emit this as a
4428 // select instead of as control flow. We can only do this if it is cheap and
4429 // safe to evaluate the LHS and RHS unconditionally.
4430 if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
4431 isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
4432 llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
4433 llvm::Value *StepV = Builder.CreateZExtOrBitCast(CondV, CGF.Int64Ty);
4434
4435 CGF.incrementProfileCounter(E, StepV);
4436
4437 llvm::Value *LHS = Visit(lhsExpr);
4438 llvm::Value *RHS = Visit(rhsExpr);
4439 if (!LHS) {
4440 // If the conditional has void type, make sure we return a null Value*.
4441 assert(!RHS && "LHS and RHS types must match");
4442 return nullptr;
4443 }
4444 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
4445 }
4446
4447 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
4448 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
4449 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
4450
4451 CodeGenFunction::ConditionalEvaluation eval(CGF);
4452 CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock,
4453 CGF.getProfileCount(lhsExpr));
4454
4455 CGF.EmitBlock(LHSBlock);
4456 CGF.incrementProfileCounter(E);
4457 eval.begin(CGF);
4458 Value *LHS = Visit(lhsExpr);
4459 eval.end(CGF);
4460
4461 LHSBlock = Builder.GetInsertBlock();
4462 Builder.CreateBr(ContBlock);
4463
4464 CGF.EmitBlock(RHSBlock);
4465 eval.begin(CGF);
4466 Value *RHS = Visit(rhsExpr);
4467 eval.end(CGF);
4468
4469 RHSBlock = Builder.GetInsertBlock();
4470 CGF.EmitBlock(ContBlock);
4471
4472 // If the LHS or RHS is a throw expression, it will be legitimately null.
4473 if (!LHS)
4474 return RHS;
4475 if (!RHS)
4476 return LHS;
4477
4478 // Create a PHI node for the real part.
4479 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
4480 PN->addIncoming(LHS, LHSBlock);
4481 PN->addIncoming(RHS, RHSBlock);
4482 return PN;
4483 }
4484
VisitChooseExpr(ChooseExpr * E)4485 Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
4486 return Visit(E->getChosenSubExpr());
4487 }
4488
VisitVAArgExpr(VAArgExpr * VE)4489 Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
4490 QualType Ty = VE->getType();
4491
4492 if (Ty->isVariablyModifiedType())
4493 CGF.EmitVariablyModifiedType(Ty);
4494
4495 Address ArgValue = Address::invalid();
4496 Address ArgPtr = CGF.EmitVAArg(VE, ArgValue);
4497
4498 llvm::Type *ArgTy = ConvertType(VE->getType());
4499
4500 // If EmitVAArg fails, emit an error.
4501 if (!ArgPtr.isValid()) {
4502 CGF.ErrorUnsupported(VE, "va_arg expression");
4503 return llvm::UndefValue::get(ArgTy);
4504 }
4505
4506 // FIXME Volatility.
4507 llvm::Value *Val = Builder.CreateLoad(ArgPtr);
4508
4509 // If EmitVAArg promoted the type, we must truncate it.
4510 if (ArgTy != Val->getType()) {
4511 if (ArgTy->isPointerTy() && !Val->getType()->isPointerTy())
4512 Val = Builder.CreateIntToPtr(Val, ArgTy);
4513 else
4514 Val = Builder.CreateTrunc(Val, ArgTy);
4515 }
4516
4517 return Val;
4518 }
4519
VisitBlockExpr(const BlockExpr * block)4520 Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
4521 return CGF.EmitBlockLiteral(block);
4522 }
4523
4524 // Convert a vec3 to vec4, or vice versa.
ConvertVec3AndVec4(CGBuilderTy & Builder,CodeGenFunction & CGF,Value * Src,unsigned NumElementsDst)4525 static Value *ConvertVec3AndVec4(CGBuilderTy &Builder, CodeGenFunction &CGF,
4526 Value *Src, unsigned NumElementsDst) {
4527 llvm::Value *UnV = llvm::UndefValue::get(Src->getType());
4528 static constexpr int Mask[] = {0, 1, 2, -1};
4529 return Builder.CreateShuffleVector(Src, UnV,
4530 llvm::makeArrayRef(Mask, NumElementsDst));
4531 }
4532
4533 // Create cast instructions for converting LLVM value \p Src to LLVM type \p
4534 // DstTy. \p Src has the same size as \p DstTy. Both are single value types
4535 // but could be scalar or vectors of different lengths, and either can be
4536 // pointer.
4537 // There are 4 cases:
4538 // 1. non-pointer -> non-pointer : needs 1 bitcast
4539 // 2. pointer -> pointer : needs 1 bitcast or addrspacecast
4540 // 3. pointer -> non-pointer
4541 // a) pointer -> intptr_t : needs 1 ptrtoint
4542 // b) pointer -> non-intptr_t : needs 1 ptrtoint then 1 bitcast
4543 // 4. non-pointer -> pointer
4544 // a) intptr_t -> pointer : needs 1 inttoptr
4545 // b) non-intptr_t -> pointer : needs 1 bitcast then 1 inttoptr
4546 // Note: for cases 3b and 4b two casts are required since LLVM casts do not
4547 // allow casting directly between pointer types and non-integer non-pointer
4548 // types.
createCastsForTypeOfSameSize(CGBuilderTy & Builder,const llvm::DataLayout & DL,Value * Src,llvm::Type * DstTy,StringRef Name="")4549 static Value *createCastsForTypeOfSameSize(CGBuilderTy &Builder,
4550 const llvm::DataLayout &DL,
4551 Value *Src, llvm::Type *DstTy,
4552 StringRef Name = "") {
4553 auto SrcTy = Src->getType();
4554
4555 // Case 1.
4556 if (!SrcTy->isPointerTy() && !DstTy->isPointerTy())
4557 return Builder.CreateBitCast(Src, DstTy, Name);
4558
4559 // Case 2.
4560 if (SrcTy->isPointerTy() && DstTy->isPointerTy())
4561 return Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DstTy, Name);
4562
4563 // Case 3.
4564 if (SrcTy->isPointerTy() && !DstTy->isPointerTy()) {
4565 // Case 3b.
4566 if (!DstTy->isIntegerTy())
4567 Src = Builder.CreatePtrToInt(Src, DL.getIntPtrType(SrcTy));
4568 // Cases 3a and 3b.
4569 return Builder.CreateBitOrPointerCast(Src, DstTy, Name);
4570 }
4571
4572 // Case 4b.
4573 if (!SrcTy->isIntegerTy())
4574 Src = Builder.CreateBitCast(Src, DL.getIntPtrType(DstTy));
4575 // Cases 4a and 4b.
4576 return Builder.CreateIntToPtr(Src, DstTy, Name);
4577 }
4578
VisitAsTypeExpr(AsTypeExpr * E)4579 Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
4580 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
4581 llvm::Type *DstTy = ConvertType(E->getType());
4582
4583 llvm::Type *SrcTy = Src->getType();
4584 unsigned NumElementsSrc =
4585 isa<llvm::VectorType>(SrcTy)
4586 ? cast<llvm::FixedVectorType>(SrcTy)->getNumElements()
4587 : 0;
4588 unsigned NumElementsDst =
4589 isa<llvm::VectorType>(DstTy)
4590 ? cast<llvm::FixedVectorType>(DstTy)->getNumElements()
4591 : 0;
4592
4593 // Going from vec3 to non-vec3 is a special case and requires a shuffle
4594 // vector to get a vec4, then a bitcast if the target type is different.
4595 if (NumElementsSrc == 3 && NumElementsDst != 3) {
4596 Src = ConvertVec3AndVec4(Builder, CGF, Src, 4);
4597
4598 if (!CGF.CGM.getCodeGenOpts().PreserveVec3Type) {
4599 Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src,
4600 DstTy);
4601 }
4602
4603 Src->setName("astype");
4604 return Src;
4605 }
4606
4607 // Going from non-vec3 to vec3 is a special case and requires a bitcast
4608 // to vec4 if the original type is not vec4, then a shuffle vector to
4609 // get a vec3.
4610 if (NumElementsSrc != 3 && NumElementsDst == 3) {
4611 if (!CGF.CGM.getCodeGenOpts().PreserveVec3Type) {
4612 auto *Vec4Ty = llvm::FixedVectorType::get(
4613 cast<llvm::VectorType>(DstTy)->getElementType(), 4);
4614 Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src,
4615 Vec4Ty);
4616 }
4617
4618 Src = ConvertVec3AndVec4(Builder, CGF, Src, 3);
4619 Src->setName("astype");
4620 return Src;
4621 }
4622
4623 return createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(),
4624 Src, DstTy, "astype");
4625 }
4626
VisitAtomicExpr(AtomicExpr * E)4627 Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
4628 return CGF.EmitAtomicExpr(E).getScalarVal();
4629 }
4630
4631 //===----------------------------------------------------------------------===//
4632 // Entry Point into this File
4633 //===----------------------------------------------------------------------===//
4634
4635 /// Emit the computation of the specified expression of scalar type, ignoring
4636 /// the result.
EmitScalarExpr(const Expr * E,bool IgnoreResultAssign)4637 Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
4638 assert(E && hasScalarEvaluationKind(E->getType()) &&
4639 "Invalid scalar expression to emit");
4640
4641 return ScalarExprEmitter(*this, IgnoreResultAssign)
4642 .Visit(const_cast<Expr *>(E));
4643 }
4644
4645 /// Emit a conversion from the specified type to the specified destination type,
4646 /// both of which are LLVM scalar types.
EmitScalarConversion(Value * Src,QualType SrcTy,QualType DstTy,SourceLocation Loc)4647 Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
4648 QualType DstTy,
4649 SourceLocation Loc) {
4650 assert(hasScalarEvaluationKind(SrcTy) && hasScalarEvaluationKind(DstTy) &&
4651 "Invalid scalar expression to emit");
4652 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy, Loc);
4653 }
4654
4655 /// Emit a conversion from the specified complex type to the specified
4656 /// destination type, where the destination type is an LLVM scalar type.
EmitComplexToScalarConversion(ComplexPairTy Src,QualType SrcTy,QualType DstTy,SourceLocation Loc)4657 Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
4658 QualType SrcTy,
4659 QualType DstTy,
4660 SourceLocation Loc) {
4661 assert(SrcTy->isAnyComplexType() && hasScalarEvaluationKind(DstTy) &&
4662 "Invalid complex -> scalar conversion");
4663 return ScalarExprEmitter(*this)
4664 .EmitComplexToScalarConversion(Src, SrcTy, DstTy, Loc);
4665 }
4666
4667
4668 llvm::Value *CodeGenFunction::
EmitScalarPrePostIncDec(const UnaryOperator * E,LValue LV,bool isInc,bool isPre)4669 EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
4670 bool isInc, bool isPre) {
4671 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
4672 }
4673
EmitObjCIsaExpr(const ObjCIsaExpr * E)4674 LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
4675 // object->isa or (*object).isa
4676 // Generate code as for: *(Class*)object
4677
4678 Expr *BaseExpr = E->getBase();
4679 Address Addr = Address::invalid();
4680 if (BaseExpr->isRValue()) {
4681 Addr = Address(EmitScalarExpr(BaseExpr), getPointerAlign());
4682 } else {
4683 Addr = EmitLValue(BaseExpr).getAddress(*this);
4684 }
4685
4686 // Cast the address to Class*.
4687 Addr = Builder.CreateElementBitCast(Addr, ConvertType(E->getType()));
4688 return MakeAddrLValue(Addr, E->getType());
4689 }
4690
4691
EmitCompoundAssignmentLValue(const CompoundAssignOperator * E)4692 LValue CodeGenFunction::EmitCompoundAssignmentLValue(
4693 const CompoundAssignOperator *E) {
4694 ScalarExprEmitter Scalar(*this);
4695 Value *Result = nullptr;
4696 switch (E->getOpcode()) {
4697 #define COMPOUND_OP(Op) \
4698 case BO_##Op##Assign: \
4699 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
4700 Result)
4701 COMPOUND_OP(Mul);
4702 COMPOUND_OP(Div);
4703 COMPOUND_OP(Rem);
4704 COMPOUND_OP(Add);
4705 COMPOUND_OP(Sub);
4706 COMPOUND_OP(Shl);
4707 COMPOUND_OP(Shr);
4708 COMPOUND_OP(And);
4709 COMPOUND_OP(Xor);
4710 COMPOUND_OP(Or);
4711 #undef COMPOUND_OP
4712
4713 case BO_PtrMemD:
4714 case BO_PtrMemI:
4715 case BO_Mul:
4716 case BO_Div:
4717 case BO_Rem:
4718 case BO_Add:
4719 case BO_Sub:
4720 case BO_Shl:
4721 case BO_Shr:
4722 case BO_LT:
4723 case BO_GT:
4724 case BO_LE:
4725 case BO_GE:
4726 case BO_EQ:
4727 case BO_NE:
4728 case BO_Cmp:
4729 case BO_And:
4730 case BO_Xor:
4731 case BO_Or:
4732 case BO_LAnd:
4733 case BO_LOr:
4734 case BO_Assign:
4735 case BO_Comma:
4736 llvm_unreachable("Not valid compound assignment operators");
4737 }
4738
4739 llvm_unreachable("Unhandled compound assignment operator");
4740 }
4741
4742 struct GEPOffsetAndOverflow {
4743 // The total (signed) byte offset for the GEP.
4744 llvm::Value *TotalOffset;
4745 // The offset overflow flag - true if the total offset overflows.
4746 llvm::Value *OffsetOverflows;
4747 };
4748
4749 /// Evaluate given GEPVal, which is either an inbounds GEP, or a constant,
4750 /// and compute the total offset it applies from it's base pointer BasePtr.
4751 /// Returns offset in bytes and a boolean flag whether an overflow happened
4752 /// during evaluation.
EmitGEPOffsetInBytes(Value * BasePtr,Value * GEPVal,llvm::LLVMContext & VMContext,CodeGenModule & CGM,CGBuilderTy & Builder)4753 static GEPOffsetAndOverflow EmitGEPOffsetInBytes(Value *BasePtr, Value *GEPVal,
4754 llvm::LLVMContext &VMContext,
4755 CodeGenModule &CGM,
4756 CGBuilderTy &Builder) {
4757 const auto &DL = CGM.getDataLayout();
4758
4759 // The total (signed) byte offset for the GEP.
4760 llvm::Value *TotalOffset = nullptr;
4761
4762 // Was the GEP already reduced to a constant?
4763 if (isa<llvm::Constant>(GEPVal)) {
4764 // Compute the offset by casting both pointers to integers and subtracting:
4765 // GEPVal = BasePtr + ptr(Offset) <--> Offset = int(GEPVal) - int(BasePtr)
4766 Value *BasePtr_int =
4767 Builder.CreatePtrToInt(BasePtr, DL.getIntPtrType(BasePtr->getType()));
4768 Value *GEPVal_int =
4769 Builder.CreatePtrToInt(GEPVal, DL.getIntPtrType(GEPVal->getType()));
4770 TotalOffset = Builder.CreateSub(GEPVal_int, BasePtr_int);
4771 return {TotalOffset, /*OffsetOverflows=*/Builder.getFalse()};
4772 }
4773
4774 auto *GEP = cast<llvm::GEPOperator>(GEPVal);
4775 assert(GEP->getPointerOperand() == BasePtr &&
4776 "BasePtr must be the the base of the GEP.");
4777 assert(GEP->isInBounds() && "Expected inbounds GEP");
4778
4779 auto *IntPtrTy = DL.getIntPtrType(GEP->getPointerOperandType());
4780
4781 // Grab references to the signed add/mul overflow intrinsics for intptr_t.
4782 auto *Zero = llvm::ConstantInt::getNullValue(IntPtrTy);
4783 auto *SAddIntrinsic =
4784 CGM.getIntrinsic(llvm::Intrinsic::sadd_with_overflow, IntPtrTy);
4785 auto *SMulIntrinsic =
4786 CGM.getIntrinsic(llvm::Intrinsic::smul_with_overflow, IntPtrTy);
4787
4788 // The offset overflow flag - true if the total offset overflows.
4789 llvm::Value *OffsetOverflows = Builder.getFalse();
4790
4791 /// Return the result of the given binary operation.
4792 auto eval = [&](BinaryOperator::Opcode Opcode, llvm::Value *LHS,
4793 llvm::Value *RHS) -> llvm::Value * {
4794 assert((Opcode == BO_Add || Opcode == BO_Mul) && "Can't eval binop");
4795
4796 // If the operands are constants, return a constant result.
4797 if (auto *LHSCI = dyn_cast<llvm::ConstantInt>(LHS)) {
4798 if (auto *RHSCI = dyn_cast<llvm::ConstantInt>(RHS)) {
4799 llvm::APInt N;
4800 bool HasOverflow = mayHaveIntegerOverflow(LHSCI, RHSCI, Opcode,
4801 /*Signed=*/true, N);
4802 if (HasOverflow)
4803 OffsetOverflows = Builder.getTrue();
4804 return llvm::ConstantInt::get(VMContext, N);
4805 }
4806 }
4807
4808 // Otherwise, compute the result with checked arithmetic.
4809 auto *ResultAndOverflow = Builder.CreateCall(
4810 (Opcode == BO_Add) ? SAddIntrinsic : SMulIntrinsic, {LHS, RHS});
4811 OffsetOverflows = Builder.CreateOr(
4812 Builder.CreateExtractValue(ResultAndOverflow, 1), OffsetOverflows);
4813 return Builder.CreateExtractValue(ResultAndOverflow, 0);
4814 };
4815
4816 // Determine the total byte offset by looking at each GEP operand.
4817 for (auto GTI = llvm::gep_type_begin(GEP), GTE = llvm::gep_type_end(GEP);
4818 GTI != GTE; ++GTI) {
4819 llvm::Value *LocalOffset;
4820 auto *Index = GTI.getOperand();
4821 // Compute the local offset contributed by this indexing step:
4822 if (auto *STy = GTI.getStructTypeOrNull()) {
4823 // For struct indexing, the local offset is the byte position of the
4824 // specified field.
4825 unsigned FieldNo = cast<llvm::ConstantInt>(Index)->getZExtValue();
4826 LocalOffset = llvm::ConstantInt::get(
4827 IntPtrTy, DL.getStructLayout(STy)->getElementOffset(FieldNo));
4828 } else {
4829 // Otherwise this is array-like indexing. The local offset is the index
4830 // multiplied by the element size.
4831 auto *ElementSize = llvm::ConstantInt::get(
4832 IntPtrTy, DL.getTypeAllocSize(GTI.getIndexedType()));
4833 auto *IndexS = Builder.CreateIntCast(Index, IntPtrTy, /*isSigned=*/true);
4834 LocalOffset = eval(BO_Mul, ElementSize, IndexS);
4835 }
4836
4837 // If this is the first offset, set it as the total offset. Otherwise, add
4838 // the local offset into the running total.
4839 if (!TotalOffset || TotalOffset == Zero)
4840 TotalOffset = LocalOffset;
4841 else
4842 TotalOffset = eval(BO_Add, TotalOffset, LocalOffset);
4843 }
4844
4845 return {TotalOffset, OffsetOverflows};
4846 }
4847
4848 Value *
EmitCheckedInBoundsGEP(Value * Ptr,ArrayRef<Value * > IdxList,bool SignedIndices,bool IsSubtraction,SourceLocation Loc,const Twine & Name)4849 CodeGenFunction::EmitCheckedInBoundsGEP(Value *Ptr, ArrayRef<Value *> IdxList,
4850 bool SignedIndices, bool IsSubtraction,
4851 SourceLocation Loc, const Twine &Name) {
4852 Value *GEPVal = Builder.CreateInBoundsGEP(Ptr, IdxList, Name);
4853
4854 // If the pointer overflow sanitizer isn't enabled, do nothing.
4855 if (!SanOpts.has(SanitizerKind::PointerOverflow))
4856 return GEPVal;
4857
4858 llvm::Type *PtrTy = Ptr->getType();
4859
4860 // Perform nullptr-and-offset check unless the nullptr is defined.
4861 bool PerformNullCheck = !NullPointerIsDefined(
4862 Builder.GetInsertBlock()->getParent(), PtrTy->getPointerAddressSpace());
4863 // Check for overflows unless the GEP got constant-folded,
4864 // and only in the default address space
4865 bool PerformOverflowCheck =
4866 !isa<llvm::Constant>(GEPVal) && PtrTy->getPointerAddressSpace() == 0;
4867
4868 if (!(PerformNullCheck || PerformOverflowCheck))
4869 return GEPVal;
4870
4871 const auto &DL = CGM.getDataLayout();
4872
4873 SanitizerScope SanScope(this);
4874 llvm::Type *IntPtrTy = DL.getIntPtrType(PtrTy);
4875
4876 GEPOffsetAndOverflow EvaluatedGEP =
4877 EmitGEPOffsetInBytes(Ptr, GEPVal, getLLVMContext(), CGM, Builder);
4878
4879 assert((!isa<llvm::Constant>(EvaluatedGEP.TotalOffset) ||
4880 EvaluatedGEP.OffsetOverflows == Builder.getFalse()) &&
4881 "If the offset got constant-folded, we don't expect that there was an "
4882 "overflow.");
4883
4884 auto *Zero = llvm::ConstantInt::getNullValue(IntPtrTy);
4885
4886 // Common case: if the total offset is zero, and we are using C++ semantics,
4887 // where nullptr+0 is defined, don't emit a check.
4888 if (EvaluatedGEP.TotalOffset == Zero && CGM.getLangOpts().CPlusPlus)
4889 return GEPVal;
4890
4891 // Now that we've computed the total offset, add it to the base pointer (with
4892 // wrapping semantics).
4893 auto *IntPtr = Builder.CreatePtrToInt(Ptr, IntPtrTy);
4894 auto *ComputedGEP = Builder.CreateAdd(IntPtr, EvaluatedGEP.TotalOffset);
4895
4896 llvm::SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks;
4897
4898 if (PerformNullCheck) {
4899 // In C++, if the base pointer evaluates to a null pointer value,
4900 // the only valid pointer this inbounds GEP can produce is also
4901 // a null pointer, so the offset must also evaluate to zero.
4902 // Likewise, if we have non-zero base pointer, we can not get null pointer
4903 // as a result, so the offset can not be -intptr_t(BasePtr).
4904 // In other words, both pointers are either null, or both are non-null,
4905 // or the behaviour is undefined.
4906 //
4907 // C, however, is more strict in this regard, and gives more
4908 // optimization opportunities: in C, additionally, nullptr+0 is undefined.
4909 // So both the input to the 'gep inbounds' AND the output must not be null.
4910 auto *BaseIsNotNullptr = Builder.CreateIsNotNull(Ptr);
4911 auto *ResultIsNotNullptr = Builder.CreateIsNotNull(ComputedGEP);
4912 auto *Valid =
4913 CGM.getLangOpts().CPlusPlus
4914 ? Builder.CreateICmpEQ(BaseIsNotNullptr, ResultIsNotNullptr)
4915 : Builder.CreateAnd(BaseIsNotNullptr, ResultIsNotNullptr);
4916 Checks.emplace_back(Valid, SanitizerKind::PointerOverflow);
4917 }
4918
4919 if (PerformOverflowCheck) {
4920 // The GEP is valid if:
4921 // 1) The total offset doesn't overflow, and
4922 // 2) The sign of the difference between the computed address and the base
4923 // pointer matches the sign of the total offset.
4924 llvm::Value *ValidGEP;
4925 auto *NoOffsetOverflow = Builder.CreateNot(EvaluatedGEP.OffsetOverflows);
4926 if (SignedIndices) {
4927 // GEP is computed as `unsigned base + signed offset`, therefore:
4928 // * If offset was positive, then the computed pointer can not be
4929 // [unsigned] less than the base pointer, unless it overflowed.
4930 // * If offset was negative, then the computed pointer can not be
4931 // [unsigned] greater than the bas pointere, unless it overflowed.
4932 auto *PosOrZeroValid = Builder.CreateICmpUGE(ComputedGEP, IntPtr);
4933 auto *PosOrZeroOffset =
4934 Builder.CreateICmpSGE(EvaluatedGEP.TotalOffset, Zero);
4935 llvm::Value *NegValid = Builder.CreateICmpULT(ComputedGEP, IntPtr);
4936 ValidGEP =
4937 Builder.CreateSelect(PosOrZeroOffset, PosOrZeroValid, NegValid);
4938 } else if (!IsSubtraction) {
4939 // GEP is computed as `unsigned base + unsigned offset`, therefore the
4940 // computed pointer can not be [unsigned] less than base pointer,
4941 // unless there was an overflow.
4942 // Equivalent to `@llvm.uadd.with.overflow(%base, %offset)`.
4943 ValidGEP = Builder.CreateICmpUGE(ComputedGEP, IntPtr);
4944 } else {
4945 // GEP is computed as `unsigned base - unsigned offset`, therefore the
4946 // computed pointer can not be [unsigned] greater than base pointer,
4947 // unless there was an overflow.
4948 // Equivalent to `@llvm.usub.with.overflow(%base, sub(0, %offset))`.
4949 ValidGEP = Builder.CreateICmpULE(ComputedGEP, IntPtr);
4950 }
4951 ValidGEP = Builder.CreateAnd(ValidGEP, NoOffsetOverflow);
4952 Checks.emplace_back(ValidGEP, SanitizerKind::PointerOverflow);
4953 }
4954
4955 assert(!Checks.empty() && "Should have produced some checks.");
4956
4957 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc)};
4958 // Pass the computed GEP to the runtime to avoid emitting poisoned arguments.
4959 llvm::Value *DynamicArgs[] = {IntPtr, ComputedGEP};
4960 EmitCheck(Checks, SanitizerHandler::PointerOverflow, StaticArgs, DynamicArgs);
4961
4962 return GEPVal;
4963 }
4964