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