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