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