CGExprScalar.cpp revision a3cac5b76a5243d8fca812d3a276950b0cfc56b6
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 "clang/Frontend/CodeGenOptions.h" 15#include "CodeGenFunction.h" 16#include "CGCXXABI.h" 17#include "CGObjCRuntime.h" 18#include "CodeGenModule.h" 19#include "CGDebugInfo.h" 20#include "clang/AST/ASTContext.h" 21#include "clang/AST/DeclObjC.h" 22#include "clang/AST/RecordLayout.h" 23#include "clang/AST/StmtVisitor.h" 24#include "clang/Basic/TargetInfo.h" 25#include "llvm/Constants.h" 26#include "llvm/Function.h" 27#include "llvm/GlobalVariable.h" 28#include "llvm/Intrinsics.h" 29#include "llvm/Module.h" 30#include "llvm/Support/CFG.h" 31#include "llvm/Target/TargetData.h" 32#include <cstdarg> 33 34using namespace clang; 35using namespace CodeGen; 36using llvm::Value; 37 38//===----------------------------------------------------------------------===// 39// Scalar Expression Emitter 40//===----------------------------------------------------------------------===// 41 42namespace { 43struct BinOpInfo { 44 Value *LHS; 45 Value *RHS; 46 QualType Ty; // Computation Type. 47 BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform 48 const Expr *E; // Entire expr, for error unsupported. May not be binop. 49}; 50 51static bool MustVisitNullValue(const Expr *E) { 52 // If a null pointer expression's type is the C++0x nullptr_t, then 53 // it's not necessarily a simple constant and it must be evaluated 54 // for its potential side effects. 55 return E->getType()->isNullPtrType(); 56} 57 58class ScalarExprEmitter 59 : public StmtVisitor<ScalarExprEmitter, Value*> { 60 CodeGenFunction &CGF; 61 CGBuilderTy &Builder; 62 bool IgnoreResultAssign; 63 llvm::LLVMContext &VMContext; 64public: 65 66 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false) 67 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira), 68 VMContext(cgf.getLLVMContext()) { 69 } 70 71 //===--------------------------------------------------------------------===// 72 // Utilities 73 //===--------------------------------------------------------------------===// 74 75 bool TestAndClearIgnoreResultAssign() { 76 bool I = IgnoreResultAssign; 77 IgnoreResultAssign = false; 78 return I; 79 } 80 81 llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); } 82 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); } 83 LValue EmitCheckedLValue(const Expr *E) { return CGF.EmitCheckedLValue(E); } 84 85 Value *EmitLoadOfLValue(LValue LV) { 86 return CGF.EmitLoadOfLValue(LV).getScalarVal(); 87 } 88 89 /// EmitLoadOfLValue - Given an expression with complex type that represents a 90 /// value l-value, this method emits the address of the l-value, then loads 91 /// and returns the result. 92 Value *EmitLoadOfLValue(const Expr *E) { 93 return EmitLoadOfLValue(EmitCheckedLValue(E)); 94 } 95 96 /// EmitConversionToBool - Convert the specified expression value to a 97 /// boolean (i1) truth value. This is equivalent to "Val != 0". 98 Value *EmitConversionToBool(Value *Src, QualType DstTy); 99 100 /// EmitScalarConversion - Emit a conversion from the specified type to the 101 /// specified destination type, both of which are LLVM scalar types. 102 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy); 103 104 /// EmitComplexToScalarConversion - Emit a conversion from the specified 105 /// complex type to the specified destination type, where the destination type 106 /// is an LLVM scalar type. 107 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src, 108 QualType SrcTy, QualType DstTy); 109 110 /// EmitNullValue - Emit a value that corresponds to null for the given type. 111 Value *EmitNullValue(QualType Ty); 112 113 /// EmitFloatToBoolConversion - Perform an FP to boolean conversion. 114 Value *EmitFloatToBoolConversion(Value *V) { 115 // Compare against 0.0 for fp scalars. 116 llvm::Value *Zero = llvm::Constant::getNullValue(V->getType()); 117 return Builder.CreateFCmpUNE(V, Zero, "tobool"); 118 } 119 120 /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion. 121 Value *EmitPointerToBoolConversion(Value *V) { 122 Value *Zero = llvm::ConstantPointerNull::get( 123 cast<llvm::PointerType>(V->getType())); 124 return Builder.CreateICmpNE(V, Zero, "tobool"); 125 } 126 127 Value *EmitIntToBoolConversion(Value *V) { 128 // Because of the type rules of C, we often end up computing a 129 // logical value, then zero extending it to int, then wanting it 130 // as a logical value again. Optimize this common case. 131 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) { 132 if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) { 133 Value *Result = ZI->getOperand(0); 134 // If there aren't any more uses, zap the instruction to save space. 135 // Note that there can be more uses, for example if this 136 // is the result of an assignment. 137 if (ZI->use_empty()) 138 ZI->eraseFromParent(); 139 return Result; 140 } 141 } 142 143 return Builder.CreateIsNotNull(V, "tobool"); 144 } 145 146 //===--------------------------------------------------------------------===// 147 // Visitor Methods 148 //===--------------------------------------------------------------------===// 149 150 Value *Visit(Expr *E) { 151 return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E); 152 } 153 154 Value *VisitStmt(Stmt *S) { 155 S->dump(CGF.getContext().getSourceManager()); 156 llvm_unreachable("Stmt can't have complex result type!"); 157 } 158 Value *VisitExpr(Expr *S); 159 160 Value *VisitParenExpr(ParenExpr *PE) { 161 return Visit(PE->getSubExpr()); 162 } 163 Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) { 164 return Visit(E->getReplacement()); 165 } 166 Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) { 167 return Visit(GE->getResultExpr()); 168 } 169 170 // Leaves. 171 Value *VisitIntegerLiteral(const IntegerLiteral *E) { 172 return Builder.getInt(E->getValue()); 173 } 174 Value *VisitFloatingLiteral(const FloatingLiteral *E) { 175 return llvm::ConstantFP::get(VMContext, E->getValue()); 176 } 177 Value *VisitCharacterLiteral(const CharacterLiteral *E) { 178 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()); 179 } 180 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 181 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()); 182 } 183 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 184 return EmitNullValue(E->getType()); 185 } 186 Value *VisitGNUNullExpr(const GNUNullExpr *E) { 187 return EmitNullValue(E->getType()); 188 } 189 Value *VisitOffsetOfExpr(OffsetOfExpr *E); 190 Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 191 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) { 192 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel()); 193 return Builder.CreateBitCast(V, ConvertType(E->getType())); 194 } 195 196 Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) { 197 return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength()); 198 } 199 200 Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) { 201 return CGF.EmitPseudoObjectRValue(E).getScalarVal(); 202 } 203 204 Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) { 205 if (E->isGLValue()) 206 return EmitLoadOfLValue(CGF.getOpaqueLValueMapping(E)); 207 208 // Otherwise, assume the mapping is the scalar directly. 209 return CGF.getOpaqueRValueMapping(E).getScalarVal(); 210 } 211 212 // l-values. 213 Value *VisitDeclRefExpr(DeclRefExpr *E) { 214 Expr::EvalResult Result; 215 bool IsReferenceConstant = false; 216 QualType EvalTy = E->getType(); 217 if (!E->EvaluateAsRValue(Result, CGF.getContext())) { 218 // If this is a reference, try to determine what it is bound to. 219 if (!E->getDecl()->getType()->isReferenceType() || 220 !E->EvaluateAsLValue(Result, CGF.getContext())) 221 return EmitLoadOfLValue(E); 222 223 IsReferenceConstant = true; 224 EvalTy = E->getDecl()->getType(); 225 } 226 227 assert(!Result.HasSideEffects && "Constant declref with side-effect?!"); 228 229 llvm::Constant *C = CGF.CGM.EmitConstantValue(Result.Val, EvalTy, &CGF); 230 231 // Make sure we emit a debug reference to the global variable. 232 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) { 233 if (!CGF.getContext().DeclMustBeEmitted(VD)) 234 CGF.EmitDeclRefExprDbgValue(E, C); 235 } else if (isa<EnumConstantDecl>(E->getDecl())) { 236 CGF.EmitDeclRefExprDbgValue(E, C); 237 } 238 239 if (IsReferenceConstant) 240 return EmitLoadOfLValue(CGF.MakeNaturalAlignAddrLValue(C, E->getType())); 241 242 return C; 243 } 244 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) { 245 return CGF.EmitObjCSelectorExpr(E); 246 } 247 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) { 248 return CGF.EmitObjCProtocolExpr(E); 249 } 250 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { 251 return EmitLoadOfLValue(E); 252 } 253 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) { 254 if (E->getMethodDecl() && 255 E->getMethodDecl()->getResultType()->isReferenceType()) 256 return EmitLoadOfLValue(E); 257 return CGF.EmitObjCMessageExpr(E).getScalarVal(); 258 } 259 260 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) { 261 LValue LV = CGF.EmitObjCIsaExpr(E); 262 Value *V = CGF.EmitLoadOfLValue(LV).getScalarVal(); 263 return V; 264 } 265 266 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E); 267 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E); 268 Value *VisitMemberExpr(MemberExpr *E); 269 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); } 270 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { 271 return EmitLoadOfLValue(E); 272 } 273 274 Value *VisitInitListExpr(InitListExpr *E); 275 276 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 277 return CGF.CGM.EmitNullConstant(E->getType()); 278 } 279 Value *VisitExplicitCastExpr(ExplicitCastExpr *E) { 280 if (E->getType()->isVariablyModifiedType()) 281 CGF.EmitVariablyModifiedType(E->getType()); 282 return VisitCastExpr(E); 283 } 284 Value *VisitCastExpr(CastExpr *E); 285 286 Value *VisitCallExpr(const CallExpr *E) { 287 if (E->getCallReturnType()->isReferenceType()) 288 return EmitLoadOfLValue(E); 289 290 return CGF.EmitCallExpr(E).getScalarVal(); 291 } 292 293 Value *VisitStmtExpr(const StmtExpr *E); 294 295 Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E); 296 297 // Unary Operators. 298 Value *VisitUnaryPostDec(const UnaryOperator *E) { 299 LValue LV = EmitLValue(E->getSubExpr()); 300 return EmitScalarPrePostIncDec(E, LV, false, false); 301 } 302 Value *VisitUnaryPostInc(const UnaryOperator *E) { 303 LValue LV = EmitLValue(E->getSubExpr()); 304 return EmitScalarPrePostIncDec(E, LV, true, false); 305 } 306 Value *VisitUnaryPreDec(const UnaryOperator *E) { 307 LValue LV = EmitLValue(E->getSubExpr()); 308 return EmitScalarPrePostIncDec(E, LV, false, true); 309 } 310 Value *VisitUnaryPreInc(const UnaryOperator *E) { 311 LValue LV = EmitLValue(E->getSubExpr()); 312 return EmitScalarPrePostIncDec(E, LV, true, true); 313 } 314 315 llvm::Value *EmitAddConsiderOverflowBehavior(const UnaryOperator *E, 316 llvm::Value *InVal, 317 llvm::Value *NextVal, 318 bool IsInc); 319 320 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, 321 bool isInc, bool isPre); 322 323 324 Value *VisitUnaryAddrOf(const UnaryOperator *E) { 325 if (isa<MemberPointerType>(E->getType())) // never sugared 326 return CGF.CGM.getMemberPointerConstant(E); 327 328 return EmitLValue(E->getSubExpr()).getAddress(); 329 } 330 Value *VisitUnaryDeref(const UnaryOperator *E) { 331 if (E->getType()->isVoidType()) 332 return Visit(E->getSubExpr()); // the actual value should be unused 333 return EmitLoadOfLValue(E); 334 } 335 Value *VisitUnaryPlus(const UnaryOperator *E) { 336 // This differs from gcc, though, most likely due to a bug in gcc. 337 TestAndClearIgnoreResultAssign(); 338 return Visit(E->getSubExpr()); 339 } 340 Value *VisitUnaryMinus (const UnaryOperator *E); 341 Value *VisitUnaryNot (const UnaryOperator *E); 342 Value *VisitUnaryLNot (const UnaryOperator *E); 343 Value *VisitUnaryReal (const UnaryOperator *E); 344 Value *VisitUnaryImag (const UnaryOperator *E); 345 Value *VisitUnaryExtension(const UnaryOperator *E) { 346 return Visit(E->getSubExpr()); 347 } 348 349 // C++ 350 Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) { 351 return EmitLoadOfLValue(E); 352 } 353 354 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) { 355 return Visit(DAE->getExpr()); 356 } 357 Value *VisitCXXThisExpr(CXXThisExpr *TE) { 358 return CGF.LoadCXXThis(); 359 } 360 361 Value *VisitExprWithCleanups(ExprWithCleanups *E) { 362 CGF.enterFullExpression(E); 363 CodeGenFunction::RunCleanupsScope Scope(CGF); 364 return Visit(E->getSubExpr()); 365 } 366 Value *VisitCXXNewExpr(const CXXNewExpr *E) { 367 return CGF.EmitCXXNewExpr(E); 368 } 369 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) { 370 CGF.EmitCXXDeleteExpr(E); 371 return 0; 372 } 373 Value *VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) { 374 return Builder.getInt1(E->getValue()); 375 } 376 377 Value *VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) { 378 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()); 379 } 380 381 Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 382 return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue()); 383 } 384 385 Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 386 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue()); 387 } 388 389 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) { 390 // C++ [expr.pseudo]p1: 391 // The result shall only be used as the operand for the function call 392 // operator (), and the result of such a call has type void. The only 393 // effect is the evaluation of the postfix-expression before the dot or 394 // arrow. 395 CGF.EmitScalarExpr(E->getBase()); 396 return 0; 397 } 398 399 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 400 return EmitNullValue(E->getType()); 401 } 402 403 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) { 404 CGF.EmitCXXThrowExpr(E); 405 return 0; 406 } 407 408 Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 409 return Builder.getInt1(E->getValue()); 410 } 411 412 // Binary Operators. 413 Value *EmitMul(const BinOpInfo &Ops) { 414 if (Ops.Ty->isSignedIntegerOrEnumerationType()) { 415 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) { 416 case LangOptions::SOB_Undefined: 417 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul"); 418 case LangOptions::SOB_Defined: 419 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul"); 420 case LangOptions::SOB_Trapping: 421 return EmitOverflowCheckedBinOp(Ops); 422 } 423 } 424 425 if (Ops.LHS->getType()->isFPOrFPVectorTy()) 426 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul"); 427 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul"); 428 } 429 bool isTrapvOverflowBehavior() { 430 return CGF.getContext().getLangOptions().getSignedOverflowBehavior() 431 == LangOptions::SOB_Trapping; 432 } 433 /// Create a binary op that checks for overflow. 434 /// Currently only supports +, - and *. 435 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops); 436 // Emit the overflow BB when -ftrapv option is activated. 437 void EmitOverflowBB(llvm::BasicBlock *overflowBB) { 438 Builder.SetInsertPoint(overflowBB); 439 llvm::Function *Trap = CGF.CGM.getIntrinsic(llvm::Intrinsic::trap); 440 Builder.CreateCall(Trap); 441 Builder.CreateUnreachable(); 442 } 443 // Check for undefined division and modulus behaviors. 444 void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops, 445 llvm::Value *Zero,bool isDiv); 446 Value *EmitDiv(const BinOpInfo &Ops); 447 Value *EmitRem(const BinOpInfo &Ops); 448 Value *EmitAdd(const BinOpInfo &Ops); 449 Value *EmitSub(const BinOpInfo &Ops); 450 Value *EmitShl(const BinOpInfo &Ops); 451 Value *EmitShr(const BinOpInfo &Ops); 452 Value *EmitAnd(const BinOpInfo &Ops) { 453 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and"); 454 } 455 Value *EmitXor(const BinOpInfo &Ops) { 456 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor"); 457 } 458 Value *EmitOr (const BinOpInfo &Ops) { 459 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or"); 460 } 461 462 BinOpInfo EmitBinOps(const BinaryOperator *E); 463 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E, 464 Value *(ScalarExprEmitter::*F)(const BinOpInfo &), 465 Value *&Result); 466 467 Value *EmitCompoundAssign(const CompoundAssignOperator *E, 468 Value *(ScalarExprEmitter::*F)(const BinOpInfo &)); 469 470 // Binary operators and binary compound assignment operators. 471#define HANDLEBINOP(OP) \ 472 Value *VisitBin ## OP(const BinaryOperator *E) { \ 473 return Emit ## OP(EmitBinOps(E)); \ 474 } \ 475 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \ 476 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \ 477 } 478 HANDLEBINOP(Mul) 479 HANDLEBINOP(Div) 480 HANDLEBINOP(Rem) 481 HANDLEBINOP(Add) 482 HANDLEBINOP(Sub) 483 HANDLEBINOP(Shl) 484 HANDLEBINOP(Shr) 485 HANDLEBINOP(And) 486 HANDLEBINOP(Xor) 487 HANDLEBINOP(Or) 488#undef HANDLEBINOP 489 490 // Comparisons. 491 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc, 492 unsigned SICmpOpc, unsigned FCmpOpc); 493#define VISITCOMP(CODE, UI, SI, FP) \ 494 Value *VisitBin##CODE(const BinaryOperator *E) { \ 495 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \ 496 llvm::FCmpInst::FP); } 497 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT) 498 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT) 499 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE) 500 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE) 501 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ) 502 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE) 503#undef VISITCOMP 504 505 Value *VisitBinAssign (const BinaryOperator *E); 506 507 Value *VisitBinLAnd (const BinaryOperator *E); 508 Value *VisitBinLOr (const BinaryOperator *E); 509 Value *VisitBinComma (const BinaryOperator *E); 510 511 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); } 512 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); } 513 514 // Other Operators. 515 Value *VisitBlockExpr(const BlockExpr *BE); 516 Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *); 517 Value *VisitChooseExpr(ChooseExpr *CE); 518 Value *VisitVAArgExpr(VAArgExpr *VE); 519 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) { 520 return CGF.EmitObjCStringLiteral(E); 521 } 522 Value *VisitAsTypeExpr(AsTypeExpr *CE); 523 Value *VisitAtomicExpr(AtomicExpr *AE); 524}; 525} // end anonymous namespace. 526 527//===----------------------------------------------------------------------===// 528// Utilities 529//===----------------------------------------------------------------------===// 530 531/// EmitConversionToBool - Convert the specified expression value to a 532/// boolean (i1) truth value. This is equivalent to "Val != 0". 533Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) { 534 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs"); 535 536 if (SrcType->isRealFloatingType()) 537 return EmitFloatToBoolConversion(Src); 538 539 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType)) 540 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT); 541 542 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) && 543 "Unknown scalar type to convert"); 544 545 if (isa<llvm::IntegerType>(Src->getType())) 546 return EmitIntToBoolConversion(Src); 547 548 assert(isa<llvm::PointerType>(Src->getType())); 549 return EmitPointerToBoolConversion(Src); 550} 551 552/// EmitScalarConversion - Emit a conversion from the specified type to the 553/// specified destination type, both of which are LLVM scalar types. 554Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType, 555 QualType DstType) { 556 SrcType = CGF.getContext().getCanonicalType(SrcType); 557 DstType = CGF.getContext().getCanonicalType(DstType); 558 if (SrcType == DstType) return Src; 559 560 if (DstType->isVoidType()) return 0; 561 562 llvm::Type *SrcTy = Src->getType(); 563 564 // Floating casts might be a bit special: if we're doing casts to / from half 565 // FP, we should go via special intrinsics. 566 if (SrcType->isHalfType()) { 567 Src = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16), Src); 568 SrcType = CGF.getContext().FloatTy; 569 SrcTy = CGF.FloatTy; 570 } 571 572 // Handle conversions to bool first, they are special: comparisons against 0. 573 if (DstType->isBooleanType()) 574 return EmitConversionToBool(Src, SrcType); 575 576 llvm::Type *DstTy = ConvertType(DstType); 577 578 // Ignore conversions like int -> uint. 579 if (SrcTy == DstTy) 580 return Src; 581 582 // Handle pointer conversions next: pointers can only be converted to/from 583 // other pointers and integers. Check for pointer types in terms of LLVM, as 584 // some native types (like Obj-C id) may map to a pointer type. 585 if (isa<llvm::PointerType>(DstTy)) { 586 // The source value may be an integer, or a pointer. 587 if (isa<llvm::PointerType>(SrcTy)) 588 return Builder.CreateBitCast(Src, DstTy, "conv"); 589 590 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?"); 591 // First, convert to the correct width so that we control the kind of 592 // extension. 593 llvm::Type *MiddleTy = CGF.IntPtrTy; 594 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType(); 595 llvm::Value* IntResult = 596 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv"); 597 // Then, cast to pointer. 598 return Builder.CreateIntToPtr(IntResult, DstTy, "conv"); 599 } 600 601 if (isa<llvm::PointerType>(SrcTy)) { 602 // Must be an ptr to int cast. 603 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?"); 604 return Builder.CreatePtrToInt(Src, DstTy, "conv"); 605 } 606 607 // A scalar can be splatted to an extended vector of the same element type 608 if (DstType->isExtVectorType() && !SrcType->isVectorType()) { 609 // Cast the scalar to element type 610 QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType(); 611 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy); 612 613 // Insert the element in element zero of an undef vector 614 llvm::Value *UnV = llvm::UndefValue::get(DstTy); 615 llvm::Value *Idx = Builder.getInt32(0); 616 UnV = Builder.CreateInsertElement(UnV, Elt, Idx); 617 618 // Splat the element across to all elements 619 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements(); 620 llvm::Constant *Mask = llvm::ConstantVector::getSplat(NumElements, 621 Builder.getInt32(0)); 622 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat"); 623 return Yay; 624 } 625 626 // Allow bitcast from vector to integer/fp of the same size. 627 if (isa<llvm::VectorType>(SrcTy) || 628 isa<llvm::VectorType>(DstTy)) 629 return Builder.CreateBitCast(Src, DstTy, "conv"); 630 631 // Finally, we have the arithmetic types: real int/float. 632 Value *Res = NULL; 633 llvm::Type *ResTy = DstTy; 634 635 // Cast to half via float 636 if (DstType->isHalfType()) 637 DstTy = CGF.FloatTy; 638 639 if (isa<llvm::IntegerType>(SrcTy)) { 640 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType(); 641 if (isa<llvm::IntegerType>(DstTy)) 642 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv"); 643 else if (InputSigned) 644 Res = Builder.CreateSIToFP(Src, DstTy, "conv"); 645 else 646 Res = Builder.CreateUIToFP(Src, DstTy, "conv"); 647 } else if (isa<llvm::IntegerType>(DstTy)) { 648 assert(SrcTy->isFloatingPointTy() && "Unknown real conversion"); 649 if (DstType->isSignedIntegerOrEnumerationType()) 650 Res = Builder.CreateFPToSI(Src, DstTy, "conv"); 651 else 652 Res = Builder.CreateFPToUI(Src, DstTy, "conv"); 653 } else { 654 assert(SrcTy->isFloatingPointTy() && DstTy->isFloatingPointTy() && 655 "Unknown real conversion"); 656 if (DstTy->getTypeID() < SrcTy->getTypeID()) 657 Res = Builder.CreateFPTrunc(Src, DstTy, "conv"); 658 else 659 Res = Builder.CreateFPExt(Src, DstTy, "conv"); 660 } 661 662 if (DstTy != ResTy) { 663 assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion"); 664 Res = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16), Res); 665 } 666 667 return Res; 668} 669 670/// EmitComplexToScalarConversion - Emit a conversion from the specified complex 671/// type to the specified destination type, where the destination type is an 672/// LLVM scalar type. 673Value *ScalarExprEmitter:: 674EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src, 675 QualType SrcTy, QualType DstTy) { 676 // Get the source element type. 677 SrcTy = SrcTy->getAs<ComplexType>()->getElementType(); 678 679 // Handle conversions to bool first, they are special: comparisons against 0. 680 if (DstTy->isBooleanType()) { 681 // Complex != 0 -> (Real != 0) | (Imag != 0) 682 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy); 683 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy); 684 return Builder.CreateOr(Src.first, Src.second, "tobool"); 685 } 686 687 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type, 688 // the imaginary part of the complex value is discarded and the value of the 689 // real part is converted according to the conversion rules for the 690 // corresponding real type. 691 return EmitScalarConversion(Src.first, SrcTy, DstTy); 692} 693 694Value *ScalarExprEmitter::EmitNullValue(QualType Ty) { 695 if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>()) 696 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT); 697 698 return llvm::Constant::getNullValue(ConvertType(Ty)); 699} 700 701//===----------------------------------------------------------------------===// 702// Visitor Methods 703//===----------------------------------------------------------------------===// 704 705Value *ScalarExprEmitter::VisitExpr(Expr *E) { 706 CGF.ErrorUnsupported(E, "scalar expression"); 707 if (E->getType()->isVoidType()) 708 return 0; 709 return llvm::UndefValue::get(CGF.ConvertType(E->getType())); 710} 711 712Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) { 713 // Vector Mask Case 714 if (E->getNumSubExprs() == 2 || 715 (E->getNumSubExprs() == 3 && E->getExpr(2)->getType()->isVectorType())) { 716 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0)); 717 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1)); 718 Value *Mask; 719 720 llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType()); 721 unsigned LHSElts = LTy->getNumElements(); 722 723 if (E->getNumSubExprs() == 3) { 724 Mask = CGF.EmitScalarExpr(E->getExpr(2)); 725 726 // Shuffle LHS & RHS into one input vector. 727 SmallVector<llvm::Constant*, 32> concat; 728 for (unsigned i = 0; i != LHSElts; ++i) { 729 concat.push_back(Builder.getInt32(2*i)); 730 concat.push_back(Builder.getInt32(2*i+1)); 731 } 732 733 Value* CV = llvm::ConstantVector::get(concat); 734 LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat"); 735 LHSElts *= 2; 736 } else { 737 Mask = RHS; 738 } 739 740 llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType()); 741 llvm::Constant* EltMask; 742 743 // Treat vec3 like vec4. 744 if ((LHSElts == 6) && (E->getNumSubExprs() == 3)) 745 EltMask = llvm::ConstantInt::get(MTy->getElementType(), 746 (1 << llvm::Log2_32(LHSElts+2))-1); 747 else if ((LHSElts == 3) && (E->getNumSubExprs() == 2)) 748 EltMask = llvm::ConstantInt::get(MTy->getElementType(), 749 (1 << llvm::Log2_32(LHSElts+1))-1); 750 else 751 EltMask = llvm::ConstantInt::get(MTy->getElementType(), 752 (1 << llvm::Log2_32(LHSElts))-1); 753 754 // Mask off the high bits of each shuffle index. 755 Value *MaskBits = llvm::ConstantVector::getSplat(MTy->getNumElements(), 756 EltMask); 757 Mask = Builder.CreateAnd(Mask, MaskBits, "mask"); 758 759 // newv = undef 760 // mask = mask & maskbits 761 // for each elt 762 // n = extract mask i 763 // x = extract val n 764 // newv = insert newv, x, i 765 llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(), 766 MTy->getNumElements()); 767 Value* NewV = llvm::UndefValue::get(RTy); 768 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) { 769 Value *Indx = Builder.getInt32(i); 770 Indx = Builder.CreateExtractElement(Mask, Indx, "shuf_idx"); 771 Indx = Builder.CreateZExt(Indx, CGF.Int32Ty, "idx_zext"); 772 773 // Handle vec3 special since the index will be off by one for the RHS. 774 if ((LHSElts == 6) && (E->getNumSubExprs() == 3)) { 775 Value *cmpIndx, *newIndx; 776 cmpIndx = Builder.CreateICmpUGT(Indx, Builder.getInt32(3), 777 "cmp_shuf_idx"); 778 newIndx = Builder.CreateSub(Indx, Builder.getInt32(1), "shuf_idx_adj"); 779 Indx = Builder.CreateSelect(cmpIndx, newIndx, Indx, "sel_shuf_idx"); 780 } 781 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt"); 782 NewV = Builder.CreateInsertElement(NewV, VExt, Indx, "shuf_ins"); 783 } 784 return NewV; 785 } 786 787 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0)); 788 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1)); 789 790 // Handle vec3 special since the index will be off by one for the RHS. 791 llvm::VectorType *VTy = cast<llvm::VectorType>(V1->getType()); 792 SmallVector<llvm::Constant*, 32> indices; 793 for (unsigned i = 2; i < E->getNumSubExprs(); i++) { 794 unsigned Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2); 795 if (VTy->getNumElements() == 3 && Idx > 3) 796 Idx -= 1; 797 indices.push_back(Builder.getInt32(Idx)); 798 } 799 800 Value *SV = llvm::ConstantVector::get(indices); 801 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle"); 802} 803Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) { 804 llvm::APSInt Value; 805 if (E->EvaluateAsInt(Value, CGF.getContext(), Expr::SE_AllowSideEffects)) { 806 if (E->isArrow()) 807 CGF.EmitScalarExpr(E->getBase()); 808 else 809 EmitLValue(E->getBase()); 810 return Builder.getInt(Value); 811 } 812 813 // Emit debug info for aggregate now, if it was delayed to reduce 814 // debug info size. 815 CGDebugInfo *DI = CGF.getDebugInfo(); 816 if (DI && CGF.CGM.getCodeGenOpts().LimitDebugInfo) { 817 QualType PQTy = E->getBase()->IgnoreParenImpCasts()->getType(); 818 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy)) 819 if (FieldDecl *M = dyn_cast<FieldDecl>(E->getMemberDecl())) 820 DI->getOrCreateRecordType(PTy->getPointeeType(), 821 M->getParent()->getLocation()); 822 } 823 return EmitLoadOfLValue(E); 824} 825 826Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) { 827 TestAndClearIgnoreResultAssign(); 828 829 // Emit subscript expressions in rvalue context's. For most cases, this just 830 // loads the lvalue formed by the subscript expr. However, we have to be 831 // careful, because the base of a vector subscript is occasionally an rvalue, 832 // so we can't get it as an lvalue. 833 if (!E->getBase()->getType()->isVectorType()) 834 return EmitLoadOfLValue(E); 835 836 // Handle the vector case. The base must be a vector, the index must be an 837 // integer value. 838 Value *Base = Visit(E->getBase()); 839 Value *Idx = Visit(E->getIdx()); 840 bool IdxSigned = E->getIdx()->getType()->isSignedIntegerOrEnumerationType(); 841 Idx = Builder.CreateIntCast(Idx, CGF.Int32Ty, IdxSigned, "vecidxcast"); 842 return Builder.CreateExtractElement(Base, Idx, "vecext"); 843} 844 845static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx, 846 unsigned Off, llvm::Type *I32Ty) { 847 int MV = SVI->getMaskValue(Idx); 848 if (MV == -1) 849 return llvm::UndefValue::get(I32Ty); 850 return llvm::ConstantInt::get(I32Ty, Off+MV); 851} 852 853Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) { 854 bool Ignore = TestAndClearIgnoreResultAssign(); 855 (void)Ignore; 856 assert (Ignore == false && "init list ignored"); 857 unsigned NumInitElements = E->getNumInits(); 858 859 if (E->hadArrayRangeDesignator()) 860 CGF.ErrorUnsupported(E, "GNU array range designator extension"); 861 862 llvm::VectorType *VType = 863 dyn_cast<llvm::VectorType>(ConvertType(E->getType())); 864 865 if (!VType) { 866 if (NumInitElements == 0) { 867 // C++11 value-initialization for the scalar. 868 return EmitNullValue(E->getType()); 869 } 870 // We have a scalar in braces. Just use the first element. 871 return Visit(E->getInit(0)); 872 } 873 874 unsigned ResElts = VType->getNumElements(); 875 876 // Loop over initializers collecting the Value for each, and remembering 877 // whether the source was swizzle (ExtVectorElementExpr). This will allow 878 // us to fold the shuffle for the swizzle into the shuffle for the vector 879 // initializer, since LLVM optimizers generally do not want to touch 880 // shuffles. 881 unsigned CurIdx = 0; 882 bool VIsUndefShuffle = false; 883 llvm::Value *V = llvm::UndefValue::get(VType); 884 for (unsigned i = 0; i != NumInitElements; ++i) { 885 Expr *IE = E->getInit(i); 886 Value *Init = Visit(IE); 887 SmallVector<llvm::Constant*, 16> Args; 888 889 llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType()); 890 891 // Handle scalar elements. If the scalar initializer is actually one 892 // element of a different vector of the same width, use shuffle instead of 893 // extract+insert. 894 if (!VVT) { 895 if (isa<ExtVectorElementExpr>(IE)) { 896 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init); 897 898 if (EI->getVectorOperandType()->getNumElements() == ResElts) { 899 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand()); 900 Value *LHS = 0, *RHS = 0; 901 if (CurIdx == 0) { 902 // insert into undef -> shuffle (src, undef) 903 Args.push_back(C); 904 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty)); 905 906 LHS = EI->getVectorOperand(); 907 RHS = V; 908 VIsUndefShuffle = true; 909 } else if (VIsUndefShuffle) { 910 // insert into undefshuffle && size match -> shuffle (v, src) 911 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V); 912 for (unsigned j = 0; j != CurIdx; ++j) 913 Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty)); 914 Args.push_back(Builder.getInt32(ResElts + C->getZExtValue())); 915 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty)); 916 917 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0); 918 RHS = EI->getVectorOperand(); 919 VIsUndefShuffle = false; 920 } 921 if (!Args.empty()) { 922 llvm::Constant *Mask = llvm::ConstantVector::get(Args); 923 V = Builder.CreateShuffleVector(LHS, RHS, Mask); 924 ++CurIdx; 925 continue; 926 } 927 } 928 } 929 V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx), 930 "vecinit"); 931 VIsUndefShuffle = false; 932 ++CurIdx; 933 continue; 934 } 935 936 unsigned InitElts = VVT->getNumElements(); 937 938 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's 939 // input is the same width as the vector being constructed, generate an 940 // optimized shuffle of the swizzle input into the result. 941 unsigned Offset = (CurIdx == 0) ? 0 : ResElts; 942 if (isa<ExtVectorElementExpr>(IE)) { 943 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init); 944 Value *SVOp = SVI->getOperand(0); 945 llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType()); 946 947 if (OpTy->getNumElements() == ResElts) { 948 for (unsigned j = 0; j != CurIdx; ++j) { 949 // If the current vector initializer is a shuffle with undef, merge 950 // this shuffle directly into it. 951 if (VIsUndefShuffle) { 952 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0, 953 CGF.Int32Ty)); 954 } else { 955 Args.push_back(Builder.getInt32(j)); 956 } 957 } 958 for (unsigned j = 0, je = InitElts; j != je; ++j) 959 Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty)); 960 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty)); 961 962 if (VIsUndefShuffle) 963 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0); 964 965 Init = SVOp; 966 } 967 } 968 969 // Extend init to result vector length, and then shuffle its contribution 970 // to the vector initializer into V. 971 if (Args.empty()) { 972 for (unsigned j = 0; j != InitElts; ++j) 973 Args.push_back(Builder.getInt32(j)); 974 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty)); 975 llvm::Constant *Mask = llvm::ConstantVector::get(Args); 976 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT), 977 Mask, "vext"); 978 979 Args.clear(); 980 for (unsigned j = 0; j != CurIdx; ++j) 981 Args.push_back(Builder.getInt32(j)); 982 for (unsigned j = 0; j != InitElts; ++j) 983 Args.push_back(Builder.getInt32(j+Offset)); 984 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty)); 985 } 986 987 // If V is undef, make sure it ends up on the RHS of the shuffle to aid 988 // merging subsequent shuffles into this one. 989 if (CurIdx == 0) 990 std::swap(V, Init); 991 llvm::Constant *Mask = llvm::ConstantVector::get(Args); 992 V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit"); 993 VIsUndefShuffle = isa<llvm::UndefValue>(Init); 994 CurIdx += InitElts; 995 } 996 997 // FIXME: evaluate codegen vs. shuffling against constant null vector. 998 // Emit remaining default initializers. 999 llvm::Type *EltTy = VType->getElementType(); 1000 1001 // Emit remaining default initializers 1002 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) { 1003 Value *Idx = Builder.getInt32(CurIdx); 1004 llvm::Value *Init = llvm::Constant::getNullValue(EltTy); 1005 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit"); 1006 } 1007 return V; 1008} 1009 1010static bool ShouldNullCheckClassCastValue(const CastExpr *CE) { 1011 const Expr *E = CE->getSubExpr(); 1012 1013 if (CE->getCastKind() == CK_UncheckedDerivedToBase) 1014 return false; 1015 1016 if (isa<CXXThisExpr>(E)) { 1017 // We always assume that 'this' is never null. 1018 return false; 1019 } 1020 1021 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) { 1022 // And that glvalue casts are never null. 1023 if (ICE->getValueKind() != VK_RValue) 1024 return false; 1025 } 1026 1027 return true; 1028} 1029 1030// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts 1031// have to handle a more broad range of conversions than explicit casts, as they 1032// handle things like function to ptr-to-function decay etc. 1033Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) { 1034 Expr *E = CE->getSubExpr(); 1035 QualType DestTy = CE->getType(); 1036 CastKind Kind = CE->getCastKind(); 1037 1038 if (!DestTy->isVoidType()) 1039 TestAndClearIgnoreResultAssign(); 1040 1041 // Since almost all cast kinds apply to scalars, this switch doesn't have 1042 // a default case, so the compiler will warn on a missing case. The cases 1043 // are in the same order as in the CastKind enum. 1044 switch (Kind) { 1045 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!"); 1046 1047 case CK_LValueBitCast: 1048 case CK_ObjCObjectLValueCast: { 1049 Value *V = EmitLValue(E).getAddress(); 1050 V = Builder.CreateBitCast(V, 1051 ConvertType(CGF.getContext().getPointerType(DestTy))); 1052 return EmitLoadOfLValue(CGF.MakeNaturalAlignAddrLValue(V, DestTy)); 1053 } 1054 1055 case CK_CPointerToObjCPointerCast: 1056 case CK_BlockPointerToObjCPointerCast: 1057 case CK_AnyPointerToBlockPointerCast: 1058 case CK_BitCast: { 1059 Value *Src = Visit(const_cast<Expr*>(E)); 1060 return Builder.CreateBitCast(Src, ConvertType(DestTy)); 1061 } 1062 case CK_AtomicToNonAtomic: 1063 case CK_NonAtomicToAtomic: 1064 case CK_NoOp: 1065 case CK_UserDefinedConversion: 1066 return Visit(const_cast<Expr*>(E)); 1067 1068 case CK_BaseToDerived: { 1069 const CXXRecordDecl *DerivedClassDecl = 1070 DestTy->getCXXRecordDeclForPointerType(); 1071 1072 return CGF.GetAddressOfDerivedClass(Visit(E), DerivedClassDecl, 1073 CE->path_begin(), CE->path_end(), 1074 ShouldNullCheckClassCastValue(CE)); 1075 } 1076 case CK_UncheckedDerivedToBase: 1077 case CK_DerivedToBase: { 1078 const RecordType *DerivedClassTy = 1079 E->getType()->getAs<PointerType>()->getPointeeType()->getAs<RecordType>(); 1080 CXXRecordDecl *DerivedClassDecl = 1081 cast<CXXRecordDecl>(DerivedClassTy->getDecl()); 1082 1083 return CGF.GetAddressOfBaseClass(Visit(E), DerivedClassDecl, 1084 CE->path_begin(), CE->path_end(), 1085 ShouldNullCheckClassCastValue(CE)); 1086 } 1087 case CK_Dynamic: { 1088 Value *V = Visit(const_cast<Expr*>(E)); 1089 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE); 1090 return CGF.EmitDynamicCast(V, DCE); 1091 } 1092 1093 case CK_ArrayToPointerDecay: { 1094 assert(E->getType()->isArrayType() && 1095 "Array to pointer decay must have array source type!"); 1096 1097 Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays. 1098 1099 // Note that VLA pointers are always decayed, so we don't need to do 1100 // anything here. 1101 if (!E->getType()->isVariableArrayType()) { 1102 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer"); 1103 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType()) 1104 ->getElementType()) && 1105 "Expected pointer to array"); 1106 V = Builder.CreateStructGEP(V, 0, "arraydecay"); 1107 } 1108 1109 // Make sure the array decay ends up being the right type. This matters if 1110 // the array type was of an incomplete type. 1111 return CGF.Builder.CreateBitCast(V, ConvertType(CE->getType())); 1112 } 1113 case CK_FunctionToPointerDecay: 1114 return EmitLValue(E).getAddress(); 1115 1116 case CK_NullToPointer: 1117 if (MustVisitNullValue(E)) 1118 (void) Visit(E); 1119 1120 return llvm::ConstantPointerNull::get( 1121 cast<llvm::PointerType>(ConvertType(DestTy))); 1122 1123 case CK_NullToMemberPointer: { 1124 if (MustVisitNullValue(E)) 1125 (void) Visit(E); 1126 1127 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>(); 1128 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT); 1129 } 1130 1131 case CK_ReinterpretMemberPointer: 1132 case CK_BaseToDerivedMemberPointer: 1133 case CK_DerivedToBaseMemberPointer: { 1134 Value *Src = Visit(E); 1135 1136 // Note that the AST doesn't distinguish between checked and 1137 // unchecked member pointer conversions, so we always have to 1138 // implement checked conversions here. This is inefficient when 1139 // actual control flow may be required in order to perform the 1140 // check, which it is for data member pointers (but not member 1141 // function pointers on Itanium and ARM). 1142 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src); 1143 } 1144 1145 case CK_ARCProduceObject: 1146 return CGF.EmitARCRetainScalarExpr(E); 1147 case CK_ARCConsumeObject: 1148 return CGF.EmitObjCConsumeObject(E->getType(), Visit(E)); 1149 case CK_ARCReclaimReturnedObject: { 1150 llvm::Value *value = Visit(E); 1151 value = CGF.EmitARCRetainAutoreleasedReturnValue(value); 1152 return CGF.EmitObjCConsumeObject(E->getType(), value); 1153 } 1154 case CK_ARCExtendBlockObject: 1155 return CGF.EmitARCExtendBlockObject(E); 1156 1157 case CK_CopyAndAutoreleaseBlockObject: 1158 return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType()); 1159 1160 case CK_FloatingRealToComplex: 1161 case CK_FloatingComplexCast: 1162 case CK_IntegralRealToComplex: 1163 case CK_IntegralComplexCast: 1164 case CK_IntegralComplexToFloatingComplex: 1165 case CK_FloatingComplexToIntegralComplex: 1166 case CK_ConstructorConversion: 1167 case CK_ToUnion: 1168 llvm_unreachable("scalar cast to non-scalar value"); 1169 1170 case CK_LValueToRValue: 1171 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy)); 1172 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!"); 1173 return Visit(const_cast<Expr*>(E)); 1174 1175 case CK_IntegralToPointer: { 1176 Value *Src = Visit(const_cast<Expr*>(E)); 1177 1178 // First, convert to the correct width so that we control the kind of 1179 // extension. 1180 llvm::Type *MiddleTy = CGF.IntPtrTy; 1181 bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType(); 1182 llvm::Value* IntResult = 1183 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv"); 1184 1185 return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy)); 1186 } 1187 case CK_PointerToIntegral: 1188 assert(!DestTy->isBooleanType() && "bool should use PointerToBool"); 1189 return Builder.CreatePtrToInt(Visit(E), ConvertType(DestTy)); 1190 1191 case CK_ToVoid: { 1192 CGF.EmitIgnoredExpr(E); 1193 return 0; 1194 } 1195 case CK_VectorSplat: { 1196 llvm::Type *DstTy = ConvertType(DestTy); 1197 Value *Elt = Visit(const_cast<Expr*>(E)); 1198 Elt = EmitScalarConversion(Elt, E->getType(), 1199 DestTy->getAs<VectorType>()->getElementType()); 1200 1201 // Insert the element in element zero of an undef vector 1202 llvm::Value *UnV = llvm::UndefValue::get(DstTy); 1203 llvm::Value *Idx = Builder.getInt32(0); 1204 UnV = Builder.CreateInsertElement(UnV, Elt, Idx); 1205 1206 // Splat the element across to all elements 1207 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements(); 1208 llvm::Constant *Zero = Builder.getInt32(0); 1209 llvm::Constant *Mask = llvm::ConstantVector::getSplat(NumElements, Zero); 1210 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat"); 1211 return Yay; 1212 } 1213 1214 case CK_IntegralCast: 1215 case CK_IntegralToFloating: 1216 case CK_FloatingToIntegral: 1217 case CK_FloatingCast: 1218 return EmitScalarConversion(Visit(E), E->getType(), DestTy); 1219 case CK_IntegralToBoolean: 1220 return EmitIntToBoolConversion(Visit(E)); 1221 case CK_PointerToBoolean: 1222 return EmitPointerToBoolConversion(Visit(E)); 1223 case CK_FloatingToBoolean: 1224 return EmitFloatToBoolConversion(Visit(E)); 1225 case CK_MemberPointerToBoolean: { 1226 llvm::Value *MemPtr = Visit(E); 1227 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>(); 1228 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT); 1229 } 1230 1231 case CK_FloatingComplexToReal: 1232 case CK_IntegralComplexToReal: 1233 return CGF.EmitComplexExpr(E, false, true).first; 1234 1235 case CK_FloatingComplexToBoolean: 1236 case CK_IntegralComplexToBoolean: { 1237 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E); 1238 1239 // TODO: kill this function off, inline appropriate case here 1240 return EmitComplexToScalarConversion(V, E->getType(), DestTy); 1241 } 1242 1243 } 1244 1245 llvm_unreachable("unknown scalar cast"); 1246} 1247 1248Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) { 1249 CodeGenFunction::StmtExprEvaluation eval(CGF); 1250 return CGF.EmitCompoundStmt(*E->getSubStmt(), !E->getType()->isVoidType()) 1251 .getScalarVal(); 1252} 1253 1254Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) { 1255 LValue LV = CGF.EmitBlockDeclRefLValue(E); 1256 return CGF.EmitLoadOfLValue(LV).getScalarVal(); 1257} 1258 1259//===----------------------------------------------------------------------===// 1260// Unary Operators 1261//===----------------------------------------------------------------------===// 1262 1263llvm::Value *ScalarExprEmitter:: 1264EmitAddConsiderOverflowBehavior(const UnaryOperator *E, 1265 llvm::Value *InVal, 1266 llvm::Value *NextVal, bool IsInc) { 1267 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) { 1268 case LangOptions::SOB_Undefined: 1269 return Builder.CreateNSWAdd(InVal, NextVal, IsInc ? "inc" : "dec"); 1270 case LangOptions::SOB_Defined: 1271 return Builder.CreateAdd(InVal, NextVal, IsInc ? "inc" : "dec"); 1272 case LangOptions::SOB_Trapping: 1273 BinOpInfo BinOp; 1274 BinOp.LHS = InVal; 1275 BinOp.RHS = NextVal; 1276 BinOp.Ty = E->getType(); 1277 BinOp.Opcode = BO_Add; 1278 BinOp.E = E; 1279 return EmitOverflowCheckedBinOp(BinOp); 1280 } 1281 llvm_unreachable("Unknown SignedOverflowBehaviorTy"); 1282} 1283 1284llvm::Value * 1285ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, 1286 bool isInc, bool isPre) { 1287 1288 QualType type = E->getSubExpr()->getType(); 1289 llvm::Value *value = EmitLoadOfLValue(LV); 1290 llvm::Value *input = value; 1291 llvm::PHINode *atomicPHI = 0; 1292 1293 int amount = (isInc ? 1 : -1); 1294 1295 if (const AtomicType *atomicTy = type->getAs<AtomicType>()) { 1296 llvm::BasicBlock *startBB = Builder.GetInsertBlock(); 1297 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn); 1298 Builder.CreateBr(opBB); 1299 Builder.SetInsertPoint(opBB); 1300 atomicPHI = Builder.CreatePHI(value->getType(), 2); 1301 atomicPHI->addIncoming(value, startBB); 1302 type = atomicTy->getValueType(); 1303 value = atomicPHI; 1304 } 1305 1306 // Special case of integer increment that we have to check first: bool++. 1307 // Due to promotion rules, we get: 1308 // bool++ -> bool = bool + 1 1309 // -> bool = (int)bool + 1 1310 // -> bool = ((int)bool + 1 != 0) 1311 // An interesting aspect of this is that increment is always true. 1312 // Decrement does not have this property. 1313 if (isInc && type->isBooleanType()) { 1314 value = Builder.getTrue(); 1315 1316 // Most common case by far: integer increment. 1317 } else if (type->isIntegerType()) { 1318 1319 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount); 1320 1321 // Note that signed integer inc/dec with width less than int can't 1322 // overflow because of promotion rules; we're just eliding a few steps here. 1323 if (type->isSignedIntegerOrEnumerationType() && 1324 value->getType()->getPrimitiveSizeInBits() >= 1325 CGF.IntTy->getBitWidth()) 1326 value = EmitAddConsiderOverflowBehavior(E, value, amt, isInc); 1327 else 1328 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec"); 1329 1330 // Next most common: pointer increment. 1331 } else if (const PointerType *ptr = type->getAs<PointerType>()) { 1332 QualType type = ptr->getPointeeType(); 1333 1334 // VLA types don't have constant size. 1335 if (const VariableArrayType *vla 1336 = CGF.getContext().getAsVariableArrayType(type)) { 1337 llvm::Value *numElts = CGF.getVLASize(vla).first; 1338 if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize"); 1339 if (CGF.getContext().getLangOptions().isSignedOverflowDefined()) 1340 value = Builder.CreateGEP(value, numElts, "vla.inc"); 1341 else 1342 value = Builder.CreateInBoundsGEP(value, numElts, "vla.inc"); 1343 1344 // Arithmetic on function pointers (!) is just +-1. 1345 } else if (type->isFunctionType()) { 1346 llvm::Value *amt = Builder.getInt32(amount); 1347 1348 value = CGF.EmitCastToVoidPtr(value); 1349 if (CGF.getContext().getLangOptions().isSignedOverflowDefined()) 1350 value = Builder.CreateGEP(value, amt, "incdec.funcptr"); 1351 else 1352 value = Builder.CreateInBoundsGEP(value, amt, "incdec.funcptr"); 1353 value = Builder.CreateBitCast(value, input->getType()); 1354 1355 // For everything else, we can just do a simple increment. 1356 } else { 1357 llvm::Value *amt = Builder.getInt32(amount); 1358 if (CGF.getContext().getLangOptions().isSignedOverflowDefined()) 1359 value = Builder.CreateGEP(value, amt, "incdec.ptr"); 1360 else 1361 value = Builder.CreateInBoundsGEP(value, amt, "incdec.ptr"); 1362 } 1363 1364 // Vector increment/decrement. 1365 } else if (type->isVectorType()) { 1366 if (type->hasIntegerRepresentation()) { 1367 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount); 1368 1369 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec"); 1370 } else { 1371 value = Builder.CreateFAdd( 1372 value, 1373 llvm::ConstantFP::get(value->getType(), amount), 1374 isInc ? "inc" : "dec"); 1375 } 1376 1377 // Floating point. 1378 } else if (type->isRealFloatingType()) { 1379 // Add the inc/dec to the real part. 1380 llvm::Value *amt; 1381 1382 if (type->isHalfType()) { 1383 // Another special case: half FP increment should be done via float 1384 value = 1385 Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16), 1386 input); 1387 } 1388 1389 if (value->getType()->isFloatTy()) 1390 amt = llvm::ConstantFP::get(VMContext, 1391 llvm::APFloat(static_cast<float>(amount))); 1392 else if (value->getType()->isDoubleTy()) 1393 amt = llvm::ConstantFP::get(VMContext, 1394 llvm::APFloat(static_cast<double>(amount))); 1395 else { 1396 llvm::APFloat F(static_cast<float>(amount)); 1397 bool ignored; 1398 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero, 1399 &ignored); 1400 amt = llvm::ConstantFP::get(VMContext, F); 1401 } 1402 value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec"); 1403 1404 if (type->isHalfType()) 1405 value = 1406 Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16), 1407 value); 1408 1409 // Objective-C pointer types. 1410 } else { 1411 const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>(); 1412 value = CGF.EmitCastToVoidPtr(value); 1413 1414 CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType()); 1415 if (!isInc) size = -size; 1416 llvm::Value *sizeValue = 1417 llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity()); 1418 1419 if (CGF.getContext().getLangOptions().isSignedOverflowDefined()) 1420 value = Builder.CreateGEP(value, sizeValue, "incdec.objptr"); 1421 else 1422 value = Builder.CreateInBoundsGEP(value, sizeValue, "incdec.objptr"); 1423 value = Builder.CreateBitCast(value, input->getType()); 1424 } 1425 1426 if (atomicPHI) { 1427 llvm::BasicBlock *opBB = Builder.GetInsertBlock(); 1428 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn); 1429 llvm::Value *old = Builder.CreateAtomicCmpXchg(LV.getAddress(), atomicPHI, 1430 value, llvm::SequentiallyConsistent); 1431 atomicPHI->addIncoming(old, opBB); 1432 llvm::Value *success = Builder.CreateICmpEQ(old, atomicPHI); 1433 Builder.CreateCondBr(success, contBB, opBB); 1434 Builder.SetInsertPoint(contBB); 1435 return isPre ? value : input; 1436 } 1437 1438 // Store the updated result through the lvalue. 1439 if (LV.isBitField()) 1440 CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value); 1441 else 1442 CGF.EmitStoreThroughLValue(RValue::get(value), LV); 1443 1444 // If this is a postinc, return the value read from memory, otherwise use the 1445 // updated value. 1446 return isPre ? value : input; 1447} 1448 1449 1450 1451Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) { 1452 TestAndClearIgnoreResultAssign(); 1453 // Emit unary minus with EmitSub so we handle overflow cases etc. 1454 BinOpInfo BinOp; 1455 BinOp.RHS = Visit(E->getSubExpr()); 1456 1457 if (BinOp.RHS->getType()->isFPOrFPVectorTy()) 1458 BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType()); 1459 else 1460 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType()); 1461 BinOp.Ty = E->getType(); 1462 BinOp.Opcode = BO_Sub; 1463 BinOp.E = E; 1464 return EmitSub(BinOp); 1465} 1466 1467Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) { 1468 TestAndClearIgnoreResultAssign(); 1469 Value *Op = Visit(E->getSubExpr()); 1470 return Builder.CreateNot(Op, "neg"); 1471} 1472 1473Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) { 1474 1475 // Perform vector logical not on comparison with zero vector. 1476 if (E->getType()->isExtVectorType()) { 1477 Value *Oper = Visit(E->getSubExpr()); 1478 Value *Zero = llvm::Constant::getNullValue(Oper->getType()); 1479 Value *Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp"); 1480 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext"); 1481 } 1482 1483 // Compare operand to zero. 1484 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr()); 1485 1486 // Invert value. 1487 // TODO: Could dynamically modify easy computations here. For example, if 1488 // the operand is an icmp ne, turn into icmp eq. 1489 BoolVal = Builder.CreateNot(BoolVal, "lnot"); 1490 1491 // ZExt result to the expr type. 1492 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext"); 1493} 1494 1495Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) { 1496 // Try folding the offsetof to a constant. 1497 llvm::APSInt Value; 1498 if (E->EvaluateAsInt(Value, CGF.getContext())) 1499 return Builder.getInt(Value); 1500 1501 // Loop over the components of the offsetof to compute the value. 1502 unsigned n = E->getNumComponents(); 1503 llvm::Type* ResultType = ConvertType(E->getType()); 1504 llvm::Value* Result = llvm::Constant::getNullValue(ResultType); 1505 QualType CurrentType = E->getTypeSourceInfo()->getType(); 1506 for (unsigned i = 0; i != n; ++i) { 1507 OffsetOfExpr::OffsetOfNode ON = E->getComponent(i); 1508 llvm::Value *Offset = 0; 1509 switch (ON.getKind()) { 1510 case OffsetOfExpr::OffsetOfNode::Array: { 1511 // Compute the index 1512 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex()); 1513 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr); 1514 bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType(); 1515 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv"); 1516 1517 // Save the element type 1518 CurrentType = 1519 CGF.getContext().getAsArrayType(CurrentType)->getElementType(); 1520 1521 // Compute the element size 1522 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType, 1523 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity()); 1524 1525 // Multiply out to compute the result 1526 Offset = Builder.CreateMul(Idx, ElemSize); 1527 break; 1528 } 1529 1530 case OffsetOfExpr::OffsetOfNode::Field: { 1531 FieldDecl *MemberDecl = ON.getField(); 1532 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl(); 1533 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD); 1534 1535 // Compute the index of the field in its parent. 1536 unsigned i = 0; 1537 // FIXME: It would be nice if we didn't have to loop here! 1538 for (RecordDecl::field_iterator Field = RD->field_begin(), 1539 FieldEnd = RD->field_end(); 1540 Field != FieldEnd; (void)++Field, ++i) { 1541 if (*Field == MemberDecl) 1542 break; 1543 } 1544 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 1545 1546 // Compute the offset to the field 1547 int64_t OffsetInt = RL.getFieldOffset(i) / 1548 CGF.getContext().getCharWidth(); 1549 Offset = llvm::ConstantInt::get(ResultType, OffsetInt); 1550 1551 // Save the element type. 1552 CurrentType = MemberDecl->getType(); 1553 break; 1554 } 1555 1556 case OffsetOfExpr::OffsetOfNode::Identifier: 1557 llvm_unreachable("dependent __builtin_offsetof"); 1558 1559 case OffsetOfExpr::OffsetOfNode::Base: { 1560 if (ON.getBase()->isVirtual()) { 1561 CGF.ErrorUnsupported(E, "virtual base in offsetof"); 1562 continue; 1563 } 1564 1565 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl(); 1566 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD); 1567 1568 // Save the element type. 1569 CurrentType = ON.getBase()->getType(); 1570 1571 // Compute the offset to the base. 1572 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 1573 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl()); 1574 int64_t OffsetInt = RL.getBaseClassOffsetInBits(BaseRD) / 1575 CGF.getContext().getCharWidth(); 1576 Offset = llvm::ConstantInt::get(ResultType, OffsetInt); 1577 break; 1578 } 1579 } 1580 Result = Builder.CreateAdd(Result, Offset); 1581 } 1582 return Result; 1583} 1584 1585/// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of 1586/// argument of the sizeof expression as an integer. 1587Value * 1588ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr( 1589 const UnaryExprOrTypeTraitExpr *E) { 1590 QualType TypeToSize = E->getTypeOfArgument(); 1591 if (E->getKind() == UETT_SizeOf) { 1592 if (const VariableArrayType *VAT = 1593 CGF.getContext().getAsVariableArrayType(TypeToSize)) { 1594 if (E->isArgumentType()) { 1595 // sizeof(type) - make sure to emit the VLA size. 1596 CGF.EmitVariablyModifiedType(TypeToSize); 1597 } else { 1598 // C99 6.5.3.4p2: If the argument is an expression of type 1599 // VLA, it is evaluated. 1600 CGF.EmitIgnoredExpr(E->getArgumentExpr()); 1601 } 1602 1603 QualType eltType; 1604 llvm::Value *numElts; 1605 llvm::tie(numElts, eltType) = CGF.getVLASize(VAT); 1606 1607 llvm::Value *size = numElts; 1608 1609 // Scale the number of non-VLA elements by the non-VLA element size. 1610 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType); 1611 if (!eltSize.isOne()) 1612 size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), numElts); 1613 1614 return size; 1615 } 1616 } 1617 1618 // If this isn't sizeof(vla), the result must be constant; use the constant 1619 // folding logic so we don't have to duplicate it here. 1620 return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext())); 1621} 1622 1623Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) { 1624 Expr *Op = E->getSubExpr(); 1625 if (Op->getType()->isAnyComplexType()) { 1626 // If it's an l-value, load through the appropriate subobject l-value. 1627 // Note that we have to ask E because Op might be an l-value that 1628 // this won't work for, e.g. an Obj-C property. 1629 if (E->isGLValue()) 1630 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal(); 1631 1632 // Otherwise, calculate and project. 1633 return CGF.EmitComplexExpr(Op, false, true).first; 1634 } 1635 1636 return Visit(Op); 1637} 1638 1639Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) { 1640 Expr *Op = E->getSubExpr(); 1641 if (Op->getType()->isAnyComplexType()) { 1642 // If it's an l-value, load through the appropriate subobject l-value. 1643 // Note that we have to ask E because Op might be an l-value that 1644 // this won't work for, e.g. an Obj-C property. 1645 if (Op->isGLValue()) 1646 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal(); 1647 1648 // Otherwise, calculate and project. 1649 return CGF.EmitComplexExpr(Op, true, false).second; 1650 } 1651 1652 // __imag on a scalar returns zero. Emit the subexpr to ensure side 1653 // effects are evaluated, but not the actual value. 1654 if (Op->isGLValue()) 1655 CGF.EmitLValue(Op); 1656 else 1657 CGF.EmitScalarExpr(Op, true); 1658 return llvm::Constant::getNullValue(ConvertType(E->getType())); 1659} 1660 1661//===----------------------------------------------------------------------===// 1662// Binary Operators 1663//===----------------------------------------------------------------------===// 1664 1665BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) { 1666 TestAndClearIgnoreResultAssign(); 1667 BinOpInfo Result; 1668 Result.LHS = Visit(E->getLHS()); 1669 Result.RHS = Visit(E->getRHS()); 1670 Result.Ty = E->getType(); 1671 Result.Opcode = E->getOpcode(); 1672 Result.E = E; 1673 return Result; 1674} 1675 1676LValue ScalarExprEmitter::EmitCompoundAssignLValue( 1677 const CompoundAssignOperator *E, 1678 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &), 1679 Value *&Result) { 1680 QualType LHSTy = E->getLHS()->getType(); 1681 BinOpInfo OpInfo; 1682 1683 if (E->getComputationResultType()->isAnyComplexType()) { 1684 // This needs to go through the complex expression emitter, but it's a tad 1685 // complicated to do that... I'm leaving it out for now. (Note that we do 1686 // actually need the imaginary part of the RHS for multiplication and 1687 // division.) 1688 CGF.ErrorUnsupported(E, "complex compound assignment"); 1689 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType())); 1690 return LValue(); 1691 } 1692 1693 // Emit the RHS first. __block variables need to have the rhs evaluated 1694 // first, plus this should improve codegen a little. 1695 OpInfo.RHS = Visit(E->getRHS()); 1696 OpInfo.Ty = E->getComputationResultType(); 1697 OpInfo.Opcode = E->getOpcode(); 1698 OpInfo.E = E; 1699 // Load/convert the LHS. 1700 LValue LHSLV = EmitCheckedLValue(E->getLHS()); 1701 OpInfo.LHS = EmitLoadOfLValue(LHSLV); 1702 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, 1703 E->getComputationLHSType()); 1704 1705 llvm::PHINode *atomicPHI = 0; 1706 if (const AtomicType *atomicTy = OpInfo.Ty->getAs<AtomicType>()) { 1707 // FIXME: For floating point types, we should be saving and restoring the 1708 // floating point environment in the loop. 1709 llvm::BasicBlock *startBB = Builder.GetInsertBlock(); 1710 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn); 1711 Builder.CreateBr(opBB); 1712 Builder.SetInsertPoint(opBB); 1713 atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2); 1714 atomicPHI->addIncoming(OpInfo.LHS, startBB); 1715 OpInfo.Ty = atomicTy->getValueType(); 1716 OpInfo.LHS = atomicPHI; 1717 } 1718 1719 // Expand the binary operator. 1720 Result = (this->*Func)(OpInfo); 1721 1722 // Convert the result back to the LHS type. 1723 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy); 1724 1725 if (atomicPHI) { 1726 llvm::BasicBlock *opBB = Builder.GetInsertBlock(); 1727 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn); 1728 llvm::Value *old = Builder.CreateAtomicCmpXchg(LHSLV.getAddress(), atomicPHI, 1729 Result, llvm::SequentiallyConsistent); 1730 atomicPHI->addIncoming(old, opBB); 1731 llvm::Value *success = Builder.CreateICmpEQ(old, atomicPHI); 1732 Builder.CreateCondBr(success, contBB, opBB); 1733 Builder.SetInsertPoint(contBB); 1734 return LHSLV; 1735 } 1736 1737 // Store the result value into the LHS lvalue. Bit-fields are handled 1738 // specially because the result is altered by the store, i.e., [C99 6.5.16p1] 1739 // 'An assignment expression has the value of the left operand after the 1740 // assignment...'. 1741 if (LHSLV.isBitField()) 1742 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result); 1743 else 1744 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV); 1745 1746 return LHSLV; 1747} 1748 1749Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E, 1750 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) { 1751 bool Ignore = TestAndClearIgnoreResultAssign(); 1752 Value *RHS; 1753 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS); 1754 1755 // If the result is clearly ignored, return now. 1756 if (Ignore) 1757 return 0; 1758 1759 // The result of an assignment in C is the assigned r-value. 1760 if (!CGF.getContext().getLangOptions().CPlusPlus) 1761 return RHS; 1762 1763 // If the lvalue is non-volatile, return the computed value of the assignment. 1764 if (!LHS.isVolatileQualified()) 1765 return RHS; 1766 1767 // Otherwise, reload the value. 1768 return EmitLoadOfLValue(LHS); 1769} 1770 1771void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck( 1772 const BinOpInfo &Ops, 1773 llvm::Value *Zero, bool isDiv) { 1774 llvm::Function::iterator insertPt = Builder.GetInsertBlock(); 1775 llvm::BasicBlock *contBB = 1776 CGF.createBasicBlock(isDiv ? "div.cont" : "rem.cont", CGF.CurFn, 1777 llvm::next(insertPt)); 1778 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn); 1779 1780 llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType()); 1781 1782 if (Ops.Ty->hasSignedIntegerRepresentation()) { 1783 llvm::Value *IntMin = 1784 Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth())); 1785 llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL); 1786 1787 llvm::Value *Cond1 = Builder.CreateICmpEQ(Ops.RHS, Zero); 1788 llvm::Value *LHSCmp = Builder.CreateICmpEQ(Ops.LHS, IntMin); 1789 llvm::Value *RHSCmp = Builder.CreateICmpEQ(Ops.RHS, NegOne); 1790 llvm::Value *Cond2 = Builder.CreateAnd(LHSCmp, RHSCmp, "and"); 1791 Builder.CreateCondBr(Builder.CreateOr(Cond1, Cond2, "or"), 1792 overflowBB, contBB); 1793 } else { 1794 CGF.Builder.CreateCondBr(Builder.CreateICmpEQ(Ops.RHS, Zero), 1795 overflowBB, contBB); 1796 } 1797 EmitOverflowBB(overflowBB); 1798 Builder.SetInsertPoint(contBB); 1799} 1800 1801Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) { 1802 if (isTrapvOverflowBehavior()) { 1803 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty)); 1804 1805 if (Ops.Ty->isIntegerType()) 1806 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true); 1807 else if (Ops.Ty->isRealFloatingType()) { 1808 llvm::Function::iterator insertPt = Builder.GetInsertBlock(); 1809 llvm::BasicBlock *DivCont = CGF.createBasicBlock("div.cont", CGF.CurFn, 1810 llvm::next(insertPt)); 1811 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", 1812 CGF.CurFn); 1813 CGF.Builder.CreateCondBr(Builder.CreateFCmpOEQ(Ops.RHS, Zero), 1814 overflowBB, DivCont); 1815 EmitOverflowBB(overflowBB); 1816 Builder.SetInsertPoint(DivCont); 1817 } 1818 } 1819 if (Ops.LHS->getType()->isFPOrFPVectorTy()) { 1820 llvm::Value *Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div"); 1821 if (CGF.getContext().getLangOptions().OpenCL) { 1822 // OpenCL 1.1 7.4: minimum accuracy of single precision / is 2.5ulp 1823 llvm::Type *ValTy = Val->getType(); 1824 if (ValTy->isFloatTy() || 1825 (isa<llvm::VectorType>(ValTy) && 1826 cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy())) 1827 CGF.SetFPAccuracy(Val, 5, 2); 1828 } 1829 return Val; 1830 } 1831 else if (Ops.Ty->hasUnsignedIntegerRepresentation()) 1832 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div"); 1833 else 1834 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div"); 1835} 1836 1837Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) { 1838 // Rem in C can't be a floating point type: C99 6.5.5p2. 1839 if (isTrapvOverflowBehavior()) { 1840 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty)); 1841 1842 if (Ops.Ty->isIntegerType()) 1843 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false); 1844 } 1845 1846 if (Ops.Ty->hasUnsignedIntegerRepresentation()) 1847 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem"); 1848 else 1849 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem"); 1850} 1851 1852Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) { 1853 unsigned IID; 1854 unsigned OpID = 0; 1855 1856 switch (Ops.Opcode) { 1857 case BO_Add: 1858 case BO_AddAssign: 1859 OpID = 1; 1860 IID = llvm::Intrinsic::sadd_with_overflow; 1861 break; 1862 case BO_Sub: 1863 case BO_SubAssign: 1864 OpID = 2; 1865 IID = llvm::Intrinsic::ssub_with_overflow; 1866 break; 1867 case BO_Mul: 1868 case BO_MulAssign: 1869 OpID = 3; 1870 IID = llvm::Intrinsic::smul_with_overflow; 1871 break; 1872 default: 1873 llvm_unreachable("Unsupported operation for overflow detection"); 1874 } 1875 OpID <<= 1; 1876 OpID |= 1; 1877 1878 llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty); 1879 1880 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy); 1881 1882 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS); 1883 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0); 1884 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1); 1885 1886 // Branch in case of overflow. 1887 llvm::BasicBlock *initialBB = Builder.GetInsertBlock(); 1888 llvm::Function::iterator insertPt = initialBB; 1889 llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn, 1890 llvm::next(insertPt)); 1891 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn); 1892 1893 Builder.CreateCondBr(overflow, overflowBB, continueBB); 1894 1895 // Handle overflow with llvm.trap. 1896 const std::string *handlerName = 1897 &CGF.getContext().getLangOptions().OverflowHandler; 1898 if (handlerName->empty()) { 1899 EmitOverflowBB(overflowBB); 1900 Builder.SetInsertPoint(continueBB); 1901 return result; 1902 } 1903 1904 // If an overflow handler is set, then we want to call it and then use its 1905 // result, if it returns. 1906 Builder.SetInsertPoint(overflowBB); 1907 1908 // Get the overflow handler. 1909 llvm::Type *Int8Ty = CGF.Int8Ty; 1910 llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty }; 1911 llvm::FunctionType *handlerTy = 1912 llvm::FunctionType::get(CGF.Int64Ty, argTypes, true); 1913 llvm::Value *handler = CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName); 1914 1915 // Sign extend the args to 64-bit, so that we can use the same handler for 1916 // all types of overflow. 1917 llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty); 1918 llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty); 1919 1920 // Call the handler with the two arguments, the operation, and the size of 1921 // the result. 1922 llvm::Value *handlerResult = Builder.CreateCall4(handler, lhs, rhs, 1923 Builder.getInt8(OpID), 1924 Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth())); 1925 1926 // Truncate the result back to the desired size. 1927 handlerResult = Builder.CreateTrunc(handlerResult, opTy); 1928 Builder.CreateBr(continueBB); 1929 1930 Builder.SetInsertPoint(continueBB); 1931 llvm::PHINode *phi = Builder.CreatePHI(opTy, 2); 1932 phi->addIncoming(result, initialBB); 1933 phi->addIncoming(handlerResult, overflowBB); 1934 1935 return phi; 1936} 1937 1938/// Emit pointer + index arithmetic. 1939static Value *emitPointerArithmetic(CodeGenFunction &CGF, 1940 const BinOpInfo &op, 1941 bool isSubtraction) { 1942 // Must have binary (not unary) expr here. Unary pointer 1943 // increment/decrement doesn't use this path. 1944 const BinaryOperator *expr = cast<BinaryOperator>(op.E); 1945 1946 Value *pointer = op.LHS; 1947 Expr *pointerOperand = expr->getLHS(); 1948 Value *index = op.RHS; 1949 Expr *indexOperand = expr->getRHS(); 1950 1951 // In a subtraction, the LHS is always the pointer. 1952 if (!isSubtraction && !pointer->getType()->isPointerTy()) { 1953 std::swap(pointer, index); 1954 std::swap(pointerOperand, indexOperand); 1955 } 1956 1957 unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth(); 1958 if (width != CGF.PointerWidthInBits) { 1959 // Zero-extend or sign-extend the pointer value according to 1960 // whether the index is signed or not. 1961 bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType(); 1962 index = CGF.Builder.CreateIntCast(index, CGF.PtrDiffTy, isSigned, 1963 "idx.ext"); 1964 } 1965 1966 // If this is subtraction, negate the index. 1967 if (isSubtraction) 1968 index = CGF.Builder.CreateNeg(index, "idx.neg"); 1969 1970 const PointerType *pointerType 1971 = pointerOperand->getType()->getAs<PointerType>(); 1972 if (!pointerType) { 1973 QualType objectType = pointerOperand->getType() 1974 ->castAs<ObjCObjectPointerType>() 1975 ->getPointeeType(); 1976 llvm::Value *objectSize 1977 = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType)); 1978 1979 index = CGF.Builder.CreateMul(index, objectSize); 1980 1981 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy); 1982 result = CGF.Builder.CreateGEP(result, index, "add.ptr"); 1983 return CGF.Builder.CreateBitCast(result, pointer->getType()); 1984 } 1985 1986 QualType elementType = pointerType->getPointeeType(); 1987 if (const VariableArrayType *vla 1988 = CGF.getContext().getAsVariableArrayType(elementType)) { 1989 // The element count here is the total number of non-VLA elements. 1990 llvm::Value *numElements = CGF.getVLASize(vla).first; 1991 1992 // Effectively, the multiply by the VLA size is part of the GEP. 1993 // GEP indexes are signed, and scaling an index isn't permitted to 1994 // signed-overflow, so we use the same semantics for our explicit 1995 // multiply. We suppress this if overflow is not undefined behavior. 1996 if (CGF.getLangOptions().isSignedOverflowDefined()) { 1997 index = CGF.Builder.CreateMul(index, numElements, "vla.index"); 1998 pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr"); 1999 } else { 2000 index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index"); 2001 pointer = CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr"); 2002 } 2003 return pointer; 2004 } 2005 2006 // Explicitly handle GNU void* and function pointer arithmetic extensions. The 2007 // GNU void* casts amount to no-ops since our void* type is i8*, but this is 2008 // future proof. 2009 if (elementType->isVoidType() || elementType->isFunctionType()) { 2010 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy); 2011 result = CGF.Builder.CreateGEP(result, index, "add.ptr"); 2012 return CGF.Builder.CreateBitCast(result, pointer->getType()); 2013 } 2014 2015 if (CGF.getLangOptions().isSignedOverflowDefined()) 2016 return CGF.Builder.CreateGEP(pointer, index, "add.ptr"); 2017 2018 return CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr"); 2019} 2020 2021Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) { 2022 if (op.LHS->getType()->isPointerTy() || 2023 op.RHS->getType()->isPointerTy()) 2024 return emitPointerArithmetic(CGF, op, /*subtraction*/ false); 2025 2026 if (op.Ty->isSignedIntegerOrEnumerationType()) { 2027 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) { 2028 case LangOptions::SOB_Undefined: 2029 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add"); 2030 case LangOptions::SOB_Defined: 2031 return Builder.CreateAdd(op.LHS, op.RHS, "add"); 2032 case LangOptions::SOB_Trapping: 2033 return EmitOverflowCheckedBinOp(op); 2034 } 2035 } 2036 2037 if (op.LHS->getType()->isFPOrFPVectorTy()) 2038 return Builder.CreateFAdd(op.LHS, op.RHS, "add"); 2039 2040 return Builder.CreateAdd(op.LHS, op.RHS, "add"); 2041} 2042 2043Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) { 2044 // The LHS is always a pointer if either side is. 2045 if (!op.LHS->getType()->isPointerTy()) { 2046 if (op.Ty->isSignedIntegerOrEnumerationType()) { 2047 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) { 2048 case LangOptions::SOB_Undefined: 2049 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub"); 2050 case LangOptions::SOB_Defined: 2051 return Builder.CreateSub(op.LHS, op.RHS, "sub"); 2052 case LangOptions::SOB_Trapping: 2053 return EmitOverflowCheckedBinOp(op); 2054 } 2055 } 2056 2057 if (op.LHS->getType()->isFPOrFPVectorTy()) 2058 return Builder.CreateFSub(op.LHS, op.RHS, "sub"); 2059 2060 return Builder.CreateSub(op.LHS, op.RHS, "sub"); 2061 } 2062 2063 // If the RHS is not a pointer, then we have normal pointer 2064 // arithmetic. 2065 if (!op.RHS->getType()->isPointerTy()) 2066 return emitPointerArithmetic(CGF, op, /*subtraction*/ true); 2067 2068 // Otherwise, this is a pointer subtraction. 2069 2070 // Do the raw subtraction part. 2071 llvm::Value *LHS 2072 = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast"); 2073 llvm::Value *RHS 2074 = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast"); 2075 Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub"); 2076 2077 // Okay, figure out the element size. 2078 const BinaryOperator *expr = cast<BinaryOperator>(op.E); 2079 QualType elementType = expr->getLHS()->getType()->getPointeeType(); 2080 2081 llvm::Value *divisor = 0; 2082 2083 // For a variable-length array, this is going to be non-constant. 2084 if (const VariableArrayType *vla 2085 = CGF.getContext().getAsVariableArrayType(elementType)) { 2086 llvm::Value *numElements; 2087 llvm::tie(numElements, elementType) = CGF.getVLASize(vla); 2088 2089 divisor = numElements; 2090 2091 // Scale the number of non-VLA elements by the non-VLA element size. 2092 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType); 2093 if (!eltSize.isOne()) 2094 divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor); 2095 2096 // For everything elese, we can just compute it, safe in the 2097 // assumption that Sema won't let anything through that we can't 2098 // safely compute the size of. 2099 } else { 2100 CharUnits elementSize; 2101 // Handle GCC extension for pointer arithmetic on void* and 2102 // function pointer types. 2103 if (elementType->isVoidType() || elementType->isFunctionType()) 2104 elementSize = CharUnits::One(); 2105 else 2106 elementSize = CGF.getContext().getTypeSizeInChars(elementType); 2107 2108 // Don't even emit the divide for element size of 1. 2109 if (elementSize.isOne()) 2110 return diffInChars; 2111 2112 divisor = CGF.CGM.getSize(elementSize); 2113 } 2114 2115 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since 2116 // pointer difference in C is only defined in the case where both operands 2117 // are pointing to elements of an array. 2118 return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div"); 2119} 2120 2121Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) { 2122 // LLVM requires the LHS and RHS to be the same type: promote or truncate the 2123 // RHS to the same size as the LHS. 2124 Value *RHS = Ops.RHS; 2125 if (Ops.LHS->getType() != RHS->getType()) 2126 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom"); 2127 2128 if (CGF.CatchUndefined 2129 && isa<llvm::IntegerType>(Ops.LHS->getType())) { 2130 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth(); 2131 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont"); 2132 CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS, 2133 llvm::ConstantInt::get(RHS->getType(), Width)), 2134 Cont, CGF.getTrapBB()); 2135 CGF.EmitBlock(Cont); 2136 } 2137 2138 return Builder.CreateShl(Ops.LHS, RHS, "shl"); 2139} 2140 2141Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) { 2142 // LLVM requires the LHS and RHS to be the same type: promote or truncate the 2143 // RHS to the same size as the LHS. 2144 Value *RHS = Ops.RHS; 2145 if (Ops.LHS->getType() != RHS->getType()) 2146 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom"); 2147 2148 if (CGF.CatchUndefined 2149 && isa<llvm::IntegerType>(Ops.LHS->getType())) { 2150 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth(); 2151 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont"); 2152 CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS, 2153 llvm::ConstantInt::get(RHS->getType(), Width)), 2154 Cont, CGF.getTrapBB()); 2155 CGF.EmitBlock(Cont); 2156 } 2157 2158 if (Ops.Ty->hasUnsignedIntegerRepresentation()) 2159 return Builder.CreateLShr(Ops.LHS, RHS, "shr"); 2160 return Builder.CreateAShr(Ops.LHS, RHS, "shr"); 2161} 2162 2163enum IntrinsicType { VCMPEQ, VCMPGT }; 2164// return corresponding comparison intrinsic for given vector type 2165static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT, 2166 BuiltinType::Kind ElemKind) { 2167 switch (ElemKind) { 2168 default: llvm_unreachable("unexpected element type"); 2169 case BuiltinType::Char_U: 2170 case BuiltinType::UChar: 2171 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p : 2172 llvm::Intrinsic::ppc_altivec_vcmpgtub_p; 2173 case BuiltinType::Char_S: 2174 case BuiltinType::SChar: 2175 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p : 2176 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p; 2177 case BuiltinType::UShort: 2178 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p : 2179 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p; 2180 case BuiltinType::Short: 2181 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p : 2182 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p; 2183 case BuiltinType::UInt: 2184 case BuiltinType::ULong: 2185 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p : 2186 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p; 2187 case BuiltinType::Int: 2188 case BuiltinType::Long: 2189 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p : 2190 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p; 2191 case BuiltinType::Float: 2192 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p : 2193 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p; 2194 } 2195} 2196 2197Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc, 2198 unsigned SICmpOpc, unsigned FCmpOpc) { 2199 TestAndClearIgnoreResultAssign(); 2200 Value *Result; 2201 QualType LHSTy = E->getLHS()->getType(); 2202 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) { 2203 assert(E->getOpcode() == BO_EQ || 2204 E->getOpcode() == BO_NE); 2205 Value *LHS = CGF.EmitScalarExpr(E->getLHS()); 2206 Value *RHS = CGF.EmitScalarExpr(E->getRHS()); 2207 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison( 2208 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE); 2209 } else if (!LHSTy->isAnyComplexType()) { 2210 Value *LHS = Visit(E->getLHS()); 2211 Value *RHS = Visit(E->getRHS()); 2212 2213 // If AltiVec, the comparison results in a numeric type, so we use 2214 // intrinsics comparing vectors and giving 0 or 1 as a result 2215 if (LHSTy->isVectorType() && !E->getType()->isVectorType()) { 2216 // constants for mapping CR6 register bits to predicate result 2217 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6; 2218 2219 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic; 2220 2221 // in several cases vector arguments order will be reversed 2222 Value *FirstVecArg = LHS, 2223 *SecondVecArg = RHS; 2224 2225 QualType ElTy = LHSTy->getAs<VectorType>()->getElementType(); 2226 const BuiltinType *BTy = ElTy->getAs<BuiltinType>(); 2227 BuiltinType::Kind ElementKind = BTy->getKind(); 2228 2229 switch(E->getOpcode()) { 2230 default: llvm_unreachable("is not a comparison operation"); 2231 case BO_EQ: 2232 CR6 = CR6_LT; 2233 ID = GetIntrinsic(VCMPEQ, ElementKind); 2234 break; 2235 case BO_NE: 2236 CR6 = CR6_EQ; 2237 ID = GetIntrinsic(VCMPEQ, ElementKind); 2238 break; 2239 case BO_LT: 2240 CR6 = CR6_LT; 2241 ID = GetIntrinsic(VCMPGT, ElementKind); 2242 std::swap(FirstVecArg, SecondVecArg); 2243 break; 2244 case BO_GT: 2245 CR6 = CR6_LT; 2246 ID = GetIntrinsic(VCMPGT, ElementKind); 2247 break; 2248 case BO_LE: 2249 if (ElementKind == BuiltinType::Float) { 2250 CR6 = CR6_LT; 2251 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p; 2252 std::swap(FirstVecArg, SecondVecArg); 2253 } 2254 else { 2255 CR6 = CR6_EQ; 2256 ID = GetIntrinsic(VCMPGT, ElementKind); 2257 } 2258 break; 2259 case BO_GE: 2260 if (ElementKind == BuiltinType::Float) { 2261 CR6 = CR6_LT; 2262 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p; 2263 } 2264 else { 2265 CR6 = CR6_EQ; 2266 ID = GetIntrinsic(VCMPGT, ElementKind); 2267 std::swap(FirstVecArg, SecondVecArg); 2268 } 2269 break; 2270 } 2271 2272 Value *CR6Param = Builder.getInt32(CR6); 2273 llvm::Function *F = CGF.CGM.getIntrinsic(ID); 2274 Result = Builder.CreateCall3(F, CR6Param, FirstVecArg, SecondVecArg, ""); 2275 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType()); 2276 } 2277 2278 if (LHS->getType()->isFPOrFPVectorTy()) { 2279 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc, 2280 LHS, RHS, "cmp"); 2281 } else if (LHSTy->hasSignedIntegerRepresentation()) { 2282 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc, 2283 LHS, RHS, "cmp"); 2284 } else { 2285 // Unsigned integers and pointers. 2286 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc, 2287 LHS, RHS, "cmp"); 2288 } 2289 2290 // If this is a vector comparison, sign extend the result to the appropriate 2291 // vector integer type and return it (don't convert to bool). 2292 if (LHSTy->isVectorType()) 2293 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext"); 2294 2295 } else { 2296 // Complex Comparison: can only be an equality comparison. 2297 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS()); 2298 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS()); 2299 2300 QualType CETy = LHSTy->getAs<ComplexType>()->getElementType(); 2301 2302 Value *ResultR, *ResultI; 2303 if (CETy->isRealFloatingType()) { 2304 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc, 2305 LHS.first, RHS.first, "cmp.r"); 2306 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc, 2307 LHS.second, RHS.second, "cmp.i"); 2308 } else { 2309 // Complex comparisons can only be equality comparisons. As such, signed 2310 // and unsigned opcodes are the same. 2311 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc, 2312 LHS.first, RHS.first, "cmp.r"); 2313 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc, 2314 LHS.second, RHS.second, "cmp.i"); 2315 } 2316 2317 if (E->getOpcode() == BO_EQ) { 2318 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri"); 2319 } else { 2320 assert(E->getOpcode() == BO_NE && 2321 "Complex comparison other than == or != ?"); 2322 Result = Builder.CreateOr(ResultR, ResultI, "or.ri"); 2323 } 2324 } 2325 2326 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType()); 2327} 2328 2329Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) { 2330 bool Ignore = TestAndClearIgnoreResultAssign(); 2331 2332 Value *RHS; 2333 LValue LHS; 2334 2335 switch (E->getLHS()->getType().getObjCLifetime()) { 2336 case Qualifiers::OCL_Strong: 2337 llvm::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore); 2338 break; 2339 2340 case Qualifiers::OCL_Autoreleasing: 2341 llvm::tie(LHS,RHS) = CGF.EmitARCStoreAutoreleasing(E); 2342 break; 2343 2344 case Qualifiers::OCL_Weak: 2345 RHS = Visit(E->getRHS()); 2346 LHS = EmitCheckedLValue(E->getLHS()); 2347 RHS = CGF.EmitARCStoreWeak(LHS.getAddress(), RHS, Ignore); 2348 break; 2349 2350 // No reason to do any of these differently. 2351 case Qualifiers::OCL_None: 2352 case Qualifiers::OCL_ExplicitNone: 2353 // __block variables need to have the rhs evaluated first, plus 2354 // this should improve codegen just a little. 2355 RHS = Visit(E->getRHS()); 2356 LHS = EmitCheckedLValue(E->getLHS()); 2357 2358 // Store the value into the LHS. Bit-fields are handled specially 2359 // because the result is altered by the store, i.e., [C99 6.5.16p1] 2360 // 'An assignment expression has the value of the left operand after 2361 // the assignment...'. 2362 if (LHS.isBitField()) 2363 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS); 2364 else 2365 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS); 2366 } 2367 2368 // If the result is clearly ignored, return now. 2369 if (Ignore) 2370 return 0; 2371 2372 // The result of an assignment in C is the assigned r-value. 2373 if (!CGF.getContext().getLangOptions().CPlusPlus) 2374 return RHS; 2375 2376 // If the lvalue is non-volatile, return the computed value of the assignment. 2377 if (!LHS.isVolatileQualified()) 2378 return RHS; 2379 2380 // Otherwise, reload the value. 2381 return EmitLoadOfLValue(LHS); 2382} 2383 2384Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) { 2385 2386 // Perform vector logical and on comparisons with zero vectors. 2387 if (E->getType()->isVectorType()) { 2388 Value *LHS = Visit(E->getLHS()); 2389 Value *RHS = Visit(E->getRHS()); 2390 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType()); 2391 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp"); 2392 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp"); 2393 Value *And = Builder.CreateAnd(LHS, RHS); 2394 return Builder.CreateSExt(And, Zero->getType(), "sext"); 2395 } 2396 2397 llvm::Type *ResTy = ConvertType(E->getType()); 2398 2399 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0. 2400 // If we have 1 && X, just emit X without inserting the control flow. 2401 bool LHSCondVal; 2402 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) { 2403 if (LHSCondVal) { // If we have 1 && X, just emit X. 2404 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 2405 // ZExt result to int or bool. 2406 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext"); 2407 } 2408 2409 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false. 2410 if (!CGF.ContainsLabel(E->getRHS())) 2411 return llvm::Constant::getNullValue(ResTy); 2412 } 2413 2414 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end"); 2415 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs"); 2416 2417 CodeGenFunction::ConditionalEvaluation eval(CGF); 2418 2419 // Branch on the LHS first. If it is false, go to the failure (cont) block. 2420 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock); 2421 2422 // Any edges into the ContBlock are now from an (indeterminate number of) 2423 // edges from this first condition. All of these values will be false. Start 2424 // setting up the PHI node in the Cont Block for this. 2425 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2, 2426 "", ContBlock); 2427 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock); 2428 PI != PE; ++PI) 2429 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI); 2430 2431 eval.begin(CGF); 2432 CGF.EmitBlock(RHSBlock); 2433 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 2434 eval.end(CGF); 2435 2436 // Reaquire the RHS block, as there may be subblocks inserted. 2437 RHSBlock = Builder.GetInsertBlock(); 2438 2439 // Emit an unconditional branch from this block to ContBlock. Insert an entry 2440 // into the phi node for the edge with the value of RHSCond. 2441 if (CGF.getDebugInfo()) 2442 // There is no need to emit line number for unconditional branch. 2443 Builder.SetCurrentDebugLocation(llvm::DebugLoc()); 2444 CGF.EmitBlock(ContBlock); 2445 PN->addIncoming(RHSCond, RHSBlock); 2446 2447 // ZExt result to int. 2448 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext"); 2449} 2450 2451Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) { 2452 2453 // Perform vector logical or on comparisons with zero vectors. 2454 if (E->getType()->isVectorType()) { 2455 Value *LHS = Visit(E->getLHS()); 2456 Value *RHS = Visit(E->getRHS()); 2457 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType()); 2458 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp"); 2459 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp"); 2460 Value *Or = Builder.CreateOr(LHS, RHS); 2461 return Builder.CreateSExt(Or, Zero->getType(), "sext"); 2462 } 2463 2464 llvm::Type *ResTy = ConvertType(E->getType()); 2465 2466 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1. 2467 // If we have 0 || X, just emit X without inserting the control flow. 2468 bool LHSCondVal; 2469 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) { 2470 if (!LHSCondVal) { // If we have 0 || X, just emit X. 2471 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 2472 // ZExt result to int or bool. 2473 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext"); 2474 } 2475 2476 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true. 2477 if (!CGF.ContainsLabel(E->getRHS())) 2478 return llvm::ConstantInt::get(ResTy, 1); 2479 } 2480 2481 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end"); 2482 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs"); 2483 2484 CodeGenFunction::ConditionalEvaluation eval(CGF); 2485 2486 // Branch on the LHS first. If it is true, go to the success (cont) block. 2487 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock); 2488 2489 // Any edges into the ContBlock are now from an (indeterminate number of) 2490 // edges from this first condition. All of these values will be true. Start 2491 // setting up the PHI node in the Cont Block for this. 2492 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2, 2493 "", ContBlock); 2494 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock); 2495 PI != PE; ++PI) 2496 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI); 2497 2498 eval.begin(CGF); 2499 2500 // Emit the RHS condition as a bool value. 2501 CGF.EmitBlock(RHSBlock); 2502 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 2503 2504 eval.end(CGF); 2505 2506 // Reaquire the RHS block, as there may be subblocks inserted. 2507 RHSBlock = Builder.GetInsertBlock(); 2508 2509 // Emit an unconditional branch from this block to ContBlock. Insert an entry 2510 // into the phi node for the edge with the value of RHSCond. 2511 CGF.EmitBlock(ContBlock); 2512 PN->addIncoming(RHSCond, RHSBlock); 2513 2514 // ZExt result to int. 2515 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext"); 2516} 2517 2518Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) { 2519 CGF.EmitIgnoredExpr(E->getLHS()); 2520 CGF.EnsureInsertPoint(); 2521 return Visit(E->getRHS()); 2522} 2523 2524//===----------------------------------------------------------------------===// 2525// Other Operators 2526//===----------------------------------------------------------------------===// 2527 2528/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified 2529/// expression is cheap enough and side-effect-free enough to evaluate 2530/// unconditionally instead of conditionally. This is used to convert control 2531/// flow into selects in some cases. 2532static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E, 2533 CodeGenFunction &CGF) { 2534 E = E->IgnoreParens(); 2535 2536 // Anything that is an integer or floating point constant is fine. 2537 if (E->isConstantInitializer(CGF.getContext(), false)) 2538 return true; 2539 2540 // Non-volatile automatic variables too, to get "cond ? X : Y" where 2541 // X and Y are local variables. 2542 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 2543 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) 2544 if (VD->hasLocalStorage() && !(CGF.getContext() 2545 .getCanonicalType(VD->getType()) 2546 .isVolatileQualified())) 2547 return true; 2548 2549 return false; 2550} 2551 2552 2553Value *ScalarExprEmitter:: 2554VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) { 2555 TestAndClearIgnoreResultAssign(); 2556 2557 // Bind the common expression if necessary. 2558 CodeGenFunction::OpaqueValueMapping binding(CGF, E); 2559 2560 Expr *condExpr = E->getCond(); 2561 Expr *lhsExpr = E->getTrueExpr(); 2562 Expr *rhsExpr = E->getFalseExpr(); 2563 2564 // If the condition constant folds and can be elided, try to avoid emitting 2565 // the condition and the dead arm. 2566 bool CondExprBool; 2567 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) { 2568 Expr *live = lhsExpr, *dead = rhsExpr; 2569 if (!CondExprBool) std::swap(live, dead); 2570 2571 // If the dead side doesn't have labels we need, just emit the Live part. 2572 if (!CGF.ContainsLabel(dead)) { 2573 Value *Result = Visit(live); 2574 2575 // If the live part is a throw expression, it acts like it has a void 2576 // type, so evaluating it returns a null Value*. However, a conditional 2577 // with non-void type must return a non-null Value*. 2578 if (!Result && !E->getType()->isVoidType()) 2579 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType())); 2580 2581 return Result; 2582 } 2583 } 2584 2585 // OpenCL: If the condition is a vector, we can treat this condition like 2586 // the select function. 2587 if (CGF.getContext().getLangOptions().OpenCL 2588 && condExpr->getType()->isVectorType()) { 2589 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr); 2590 llvm::Value *LHS = Visit(lhsExpr); 2591 llvm::Value *RHS = Visit(rhsExpr); 2592 2593 llvm::Type *condType = ConvertType(condExpr->getType()); 2594 llvm::VectorType *vecTy = cast<llvm::VectorType>(condType); 2595 2596 unsigned numElem = vecTy->getNumElements(); 2597 llvm::Type *elemType = vecTy->getElementType(); 2598 2599 llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy); 2600 llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec); 2601 llvm::Value *tmp = Builder.CreateSExt(TestMSB, 2602 llvm::VectorType::get(elemType, 2603 numElem), 2604 "sext"); 2605 llvm::Value *tmp2 = Builder.CreateNot(tmp); 2606 2607 // Cast float to int to perform ANDs if necessary. 2608 llvm::Value *RHSTmp = RHS; 2609 llvm::Value *LHSTmp = LHS; 2610 bool wasCast = false; 2611 llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType()); 2612 if (rhsVTy->getElementType()->isFloatTy()) { 2613 RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType()); 2614 LHSTmp = Builder.CreateBitCast(LHS, tmp->getType()); 2615 wasCast = true; 2616 } 2617 2618 llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2); 2619 llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp); 2620 llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond"); 2621 if (wasCast) 2622 tmp5 = Builder.CreateBitCast(tmp5, RHS->getType()); 2623 2624 return tmp5; 2625 } 2626 2627 // If this is a really simple expression (like x ? 4 : 5), emit this as a 2628 // select instead of as control flow. We can only do this if it is cheap and 2629 // safe to evaluate the LHS and RHS unconditionally. 2630 if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) && 2631 isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) { 2632 llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr); 2633 llvm::Value *LHS = Visit(lhsExpr); 2634 llvm::Value *RHS = Visit(rhsExpr); 2635 if (!LHS) { 2636 // If the conditional has void type, make sure we return a null Value*. 2637 assert(!RHS && "LHS and RHS types must match"); 2638 return 0; 2639 } 2640 return Builder.CreateSelect(CondV, LHS, RHS, "cond"); 2641 } 2642 2643 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true"); 2644 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false"); 2645 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end"); 2646 2647 CodeGenFunction::ConditionalEvaluation eval(CGF); 2648 CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock); 2649 2650 CGF.EmitBlock(LHSBlock); 2651 eval.begin(CGF); 2652 Value *LHS = Visit(lhsExpr); 2653 eval.end(CGF); 2654 2655 LHSBlock = Builder.GetInsertBlock(); 2656 Builder.CreateBr(ContBlock); 2657 2658 CGF.EmitBlock(RHSBlock); 2659 eval.begin(CGF); 2660 Value *RHS = Visit(rhsExpr); 2661 eval.end(CGF); 2662 2663 RHSBlock = Builder.GetInsertBlock(); 2664 CGF.EmitBlock(ContBlock); 2665 2666 // If the LHS or RHS is a throw expression, it will be legitimately null. 2667 if (!LHS) 2668 return RHS; 2669 if (!RHS) 2670 return LHS; 2671 2672 // Create a PHI node for the real part. 2673 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond"); 2674 PN->addIncoming(LHS, LHSBlock); 2675 PN->addIncoming(RHS, RHSBlock); 2676 return PN; 2677} 2678 2679Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) { 2680 return Visit(E->getChosenSubExpr(CGF.getContext())); 2681} 2682 2683Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) { 2684 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr()); 2685 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType()); 2686 2687 // If EmitVAArg fails, we fall back to the LLVM instruction. 2688 if (!ArgPtr) 2689 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType())); 2690 2691 // FIXME Volatility. 2692 return Builder.CreateLoad(ArgPtr); 2693} 2694 2695Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) { 2696 return CGF.EmitBlockLiteral(block); 2697} 2698 2699Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) { 2700 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr()); 2701 llvm::Type *DstTy = ConvertType(E->getType()); 2702 2703 // Going from vec4->vec3 or vec3->vec4 is a special case and requires 2704 // a shuffle vector instead of a bitcast. 2705 llvm::Type *SrcTy = Src->getType(); 2706 if (isa<llvm::VectorType>(DstTy) && isa<llvm::VectorType>(SrcTy)) { 2707 unsigned numElementsDst = cast<llvm::VectorType>(DstTy)->getNumElements(); 2708 unsigned numElementsSrc = cast<llvm::VectorType>(SrcTy)->getNumElements(); 2709 if ((numElementsDst == 3 && numElementsSrc == 4) 2710 || (numElementsDst == 4 && numElementsSrc == 3)) { 2711 2712 2713 // In the case of going from int4->float3, a bitcast is needed before 2714 // doing a shuffle. 2715 llvm::Type *srcElemTy = 2716 cast<llvm::VectorType>(SrcTy)->getElementType(); 2717 llvm::Type *dstElemTy = 2718 cast<llvm::VectorType>(DstTy)->getElementType(); 2719 2720 if ((srcElemTy->isIntegerTy() && dstElemTy->isFloatTy()) 2721 || (srcElemTy->isFloatTy() && dstElemTy->isIntegerTy())) { 2722 // Create a float type of the same size as the source or destination. 2723 llvm::VectorType *newSrcTy = llvm::VectorType::get(dstElemTy, 2724 numElementsSrc); 2725 2726 Src = Builder.CreateBitCast(Src, newSrcTy, "astypeCast"); 2727 } 2728 2729 llvm::Value *UnV = llvm::UndefValue::get(Src->getType()); 2730 2731 SmallVector<llvm::Constant*, 3> Args; 2732 Args.push_back(Builder.getInt32(0)); 2733 Args.push_back(Builder.getInt32(1)); 2734 Args.push_back(Builder.getInt32(2)); 2735 2736 if (numElementsDst == 4) 2737 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty)); 2738 2739 llvm::Constant *Mask = llvm::ConstantVector::get(Args); 2740 2741 return Builder.CreateShuffleVector(Src, UnV, Mask, "astype"); 2742 } 2743 } 2744 2745 return Builder.CreateBitCast(Src, DstTy, "astype"); 2746} 2747 2748Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) { 2749 return CGF.EmitAtomicExpr(E).getScalarVal(); 2750} 2751 2752//===----------------------------------------------------------------------===// 2753// Entry Point into this File 2754//===----------------------------------------------------------------------===// 2755 2756/// EmitScalarExpr - Emit the computation of the specified expression of scalar 2757/// type, ignoring the result. 2758Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) { 2759 assert(E && !hasAggregateLLVMType(E->getType()) && 2760 "Invalid scalar expression to emit"); 2761 2762 if (isa<CXXDefaultArgExpr>(E)) 2763 disableDebugInfo(); 2764 Value *V = ScalarExprEmitter(*this, IgnoreResultAssign) 2765 .Visit(const_cast<Expr*>(E)); 2766 if (isa<CXXDefaultArgExpr>(E)) 2767 enableDebugInfo(); 2768 return V; 2769} 2770 2771/// EmitScalarConversion - Emit a conversion from the specified type to the 2772/// specified destination type, both of which are LLVM scalar types. 2773Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy, 2774 QualType DstTy) { 2775 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) && 2776 "Invalid scalar expression to emit"); 2777 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy); 2778} 2779 2780/// EmitComplexToScalarConversion - Emit a conversion from the specified complex 2781/// type to the specified destination type, where the destination type is an 2782/// LLVM scalar type. 2783Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src, 2784 QualType SrcTy, 2785 QualType DstTy) { 2786 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) && 2787 "Invalid complex -> scalar conversion"); 2788 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy, 2789 DstTy); 2790} 2791 2792 2793llvm::Value *CodeGenFunction:: 2794EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, 2795 bool isInc, bool isPre) { 2796 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre); 2797} 2798 2799LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) { 2800 llvm::Value *V; 2801 // object->isa or (*object).isa 2802 // Generate code as for: *(Class*)object 2803 // build Class* type 2804 llvm::Type *ClassPtrTy = ConvertType(E->getType()); 2805 2806 Expr *BaseExpr = E->getBase(); 2807 if (BaseExpr->isRValue()) { 2808 V = CreateMemTemp(E->getType(), "resval"); 2809 llvm::Value *Src = EmitScalarExpr(BaseExpr); 2810 Builder.CreateStore(Src, V); 2811 V = ScalarExprEmitter(*this).EmitLoadOfLValue( 2812 MakeNaturalAlignAddrLValue(V, E->getType())); 2813 } else { 2814 if (E->isArrow()) 2815 V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr); 2816 else 2817 V = EmitLValue(BaseExpr).getAddress(); 2818 } 2819 2820 // build Class* type 2821 ClassPtrTy = ClassPtrTy->getPointerTo(); 2822 V = Builder.CreateBitCast(V, ClassPtrTy); 2823 return MakeNaturalAlignAddrLValue(V, E->getType()); 2824} 2825 2826 2827LValue CodeGenFunction::EmitCompoundAssignmentLValue( 2828 const CompoundAssignOperator *E) { 2829 ScalarExprEmitter Scalar(*this); 2830 Value *Result = 0; 2831 switch (E->getOpcode()) { 2832#define COMPOUND_OP(Op) \ 2833 case BO_##Op##Assign: \ 2834 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \ 2835 Result) 2836 COMPOUND_OP(Mul); 2837 COMPOUND_OP(Div); 2838 COMPOUND_OP(Rem); 2839 COMPOUND_OP(Add); 2840 COMPOUND_OP(Sub); 2841 COMPOUND_OP(Shl); 2842 COMPOUND_OP(Shr); 2843 COMPOUND_OP(And); 2844 COMPOUND_OP(Xor); 2845 COMPOUND_OP(Or); 2846#undef COMPOUND_OP 2847 2848 case BO_PtrMemD: 2849 case BO_PtrMemI: 2850 case BO_Mul: 2851 case BO_Div: 2852 case BO_Rem: 2853 case BO_Add: 2854 case BO_Sub: 2855 case BO_Shl: 2856 case BO_Shr: 2857 case BO_LT: 2858 case BO_GT: 2859 case BO_LE: 2860 case BO_GE: 2861 case BO_EQ: 2862 case BO_NE: 2863 case BO_And: 2864 case BO_Xor: 2865 case BO_Or: 2866 case BO_LAnd: 2867 case BO_LOr: 2868 case BO_Assign: 2869 case BO_Comma: 2870 llvm_unreachable("Not valid compound assignment operators"); 2871 } 2872 2873 llvm_unreachable("Unhandled compound assignment operator"); 2874} 2875