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