CGExprScalar.cpp revision c849c052d6b4b70f2651c1969531861a5f230053
1//===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This contains code to emit Expr nodes with scalar LLVM types as LLVM code. 11// 12//===----------------------------------------------------------------------===// 13 14#include "CodeGenFunction.h" 15#include "CGObjCRuntime.h" 16#include "CodeGenModule.h" 17#include "clang/AST/ASTContext.h" 18#include "clang/AST/DeclObjC.h" 19#include "clang/AST/RecordLayout.h" 20#include "clang/AST/StmtVisitor.h" 21#include "clang/Basic/TargetInfo.h" 22#include "llvm/Constants.h" 23#include "llvm/Function.h" 24#include "llvm/GlobalVariable.h" 25#include "llvm/Intrinsics.h" 26#include "llvm/Module.h" 27#include "llvm/Support/Compiler.h" 28#include "llvm/Support/CFG.h" 29#include "llvm/Target/TargetData.h" 30#include <cstdarg> 31 32using namespace clang; 33using namespace CodeGen; 34using llvm::Value; 35 36//===----------------------------------------------------------------------===// 37// Scalar Expression Emitter 38//===----------------------------------------------------------------------===// 39 40struct BinOpInfo { 41 Value *LHS; 42 Value *RHS; 43 QualType Ty; // Computation Type. 44 const BinaryOperator *E; 45}; 46 47namespace { 48class VISIBILITY_HIDDEN ScalarExprEmitter 49 : public StmtVisitor<ScalarExprEmitter, Value*> { 50 CodeGenFunction &CGF; 51 CGBuilderTy &Builder; 52 bool IgnoreResultAssign; 53 llvm::LLVMContext &VMContext; 54public: 55 56 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false) 57 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira), 58 VMContext(cgf.getLLVMContext()) { 59 } 60 61 //===--------------------------------------------------------------------===// 62 // Utilities 63 //===--------------------------------------------------------------------===// 64 65 bool TestAndClearIgnoreResultAssign() { 66 bool I = IgnoreResultAssign; 67 IgnoreResultAssign = false; 68 return I; 69 } 70 71 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); } 72 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); } 73 74 Value *EmitLoadOfLValue(LValue LV, QualType T) { 75 return CGF.EmitLoadOfLValue(LV, T).getScalarVal(); 76 } 77 78 /// EmitLoadOfLValue - Given an expression with complex type that represents a 79 /// value l-value, this method emits the address of the l-value, then loads 80 /// and returns the result. 81 Value *EmitLoadOfLValue(const Expr *E) { 82 return EmitLoadOfLValue(EmitLValue(E), E->getType()); 83 } 84 85 /// EmitConversionToBool - Convert the specified expression value to a 86 /// boolean (i1) truth value. This is equivalent to "Val != 0". 87 Value *EmitConversionToBool(Value *Src, QualType DstTy); 88 89 /// EmitScalarConversion - Emit a conversion from the specified type to the 90 /// specified destination type, both of which are LLVM scalar types. 91 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy); 92 93 /// EmitComplexToScalarConversion - Emit a conversion from the specified 94 /// complex type to the specified destination type, where the destination type 95 /// is an LLVM scalar type. 96 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src, 97 QualType SrcTy, QualType DstTy); 98 99 //===--------------------------------------------------------------------===// 100 // Visitor Methods 101 //===--------------------------------------------------------------------===// 102 103 Value *VisitStmt(Stmt *S) { 104 S->dump(CGF.getContext().getSourceManager()); 105 assert(0 && "Stmt can't have complex result type!"); 106 return 0; 107 } 108 Value *VisitExpr(Expr *S); 109 110 Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); } 111 112 // Leaves. 113 Value *VisitIntegerLiteral(const IntegerLiteral *E) { 114 return llvm::ConstantInt::get(VMContext, E->getValue()); 115 } 116 Value *VisitFloatingLiteral(const FloatingLiteral *E) { 117 return llvm::ConstantFP::get(VMContext, E->getValue()); 118 } 119 Value *VisitCharacterLiteral(const CharacterLiteral *E) { 120 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()); 121 } 122 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 123 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()); 124 } 125 Value *VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) { 126 return llvm::Constant::getNullValue(ConvertType(E->getType())); 127 } 128 Value *VisitGNUNullExpr(const GNUNullExpr *E) { 129 return llvm::Constant::getNullValue(ConvertType(E->getType())); 130 } 131 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) { 132 return llvm::ConstantInt::get(ConvertType(E->getType()), 133 CGF.getContext().typesAreCompatible( 134 E->getArgType1(), E->getArgType2())); 135 } 136 Value *VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E); 137 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) { 138 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel()); 139 return Builder.CreateBitCast(V, ConvertType(E->getType())); 140 } 141 142 // l-values. 143 Value *VisitDeclRefExpr(DeclRefExpr *E) { 144 if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(E->getDecl())) 145 return llvm::ConstantInt::get(VMContext, EC->getInitVal()); 146 return EmitLoadOfLValue(E); 147 } 148 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) { 149 return CGF.EmitObjCSelectorExpr(E); 150 } 151 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) { 152 return CGF.EmitObjCProtocolExpr(E); 153 } 154 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { 155 return EmitLoadOfLValue(E); 156 } 157 Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) { 158 return EmitLoadOfLValue(E); 159 } 160 Value *VisitObjCImplicitSetterGetterRefExpr( 161 ObjCImplicitSetterGetterRefExpr *E) { 162 return EmitLoadOfLValue(E); 163 } 164 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) { 165 return CGF.EmitObjCMessageExpr(E).getScalarVal(); 166 } 167 168 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E); 169 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E); 170 Value *VisitMemberExpr(Expr *E) { return EmitLoadOfLValue(E); } 171 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); } 172 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { 173 return EmitLoadOfLValue(E); 174 } 175 Value *VisitStringLiteral(Expr *E) { return EmitLValue(E).getAddress(); } 176 Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { 177 return EmitLValue(E).getAddress(); 178 } 179 180 Value *VisitPredefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); } 181 182 Value *VisitInitListExpr(InitListExpr *E); 183 184 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 185 return llvm::Constant::getNullValue(ConvertType(E->getType())); 186 } 187 Value *VisitCastExpr(const CastExpr *E) { 188 // Make sure to evaluate VLA bounds now so that we have them for later. 189 if (E->getType()->isVariablyModifiedType()) 190 CGF.EmitVLASize(E->getType()); 191 192 return EmitCastExpr(E); 193 } 194 Value *EmitCastExpr(const CastExpr *E); 195 196 Value *VisitCallExpr(const CallExpr *E) { 197 if (E->getCallReturnType()->isReferenceType()) 198 return EmitLoadOfLValue(E); 199 200 return CGF.EmitCallExpr(E).getScalarVal(); 201 } 202 203 Value *VisitStmtExpr(const StmtExpr *E); 204 205 Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E); 206 207 // Unary Operators. 208 Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre); 209 Value *VisitUnaryPostDec(const UnaryOperator *E) { 210 return VisitPrePostIncDec(E, false, false); 211 } 212 Value *VisitUnaryPostInc(const UnaryOperator *E) { 213 return VisitPrePostIncDec(E, true, false); 214 } 215 Value *VisitUnaryPreDec(const UnaryOperator *E) { 216 return VisitPrePostIncDec(E, false, true); 217 } 218 Value *VisitUnaryPreInc(const UnaryOperator *E) { 219 return VisitPrePostIncDec(E, true, true); 220 } 221 Value *VisitUnaryAddrOf(const UnaryOperator *E) { 222 return EmitLValue(E->getSubExpr()).getAddress(); 223 } 224 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); } 225 Value *VisitUnaryPlus(const UnaryOperator *E) { 226 // This differs from gcc, though, most likely due to a bug in gcc. 227 TestAndClearIgnoreResultAssign(); 228 return Visit(E->getSubExpr()); 229 } 230 Value *VisitUnaryMinus (const UnaryOperator *E); 231 Value *VisitUnaryNot (const UnaryOperator *E); 232 Value *VisitUnaryLNot (const UnaryOperator *E); 233 Value *VisitUnaryReal (const UnaryOperator *E); 234 Value *VisitUnaryImag (const UnaryOperator *E); 235 Value *VisitUnaryExtension(const UnaryOperator *E) { 236 return Visit(E->getSubExpr()); 237 } 238 Value *VisitUnaryOffsetOf(const UnaryOperator *E); 239 240 // C++ 241 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) { 242 return Visit(DAE->getExpr()); 243 } 244 Value *VisitCXXThisExpr(CXXThisExpr *TE) { 245 return CGF.LoadCXXThis(); 246 } 247 248 Value *VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) { 249 return CGF.EmitCXXExprWithTemporaries(E).getScalarVal(); 250 } 251 Value *VisitCXXNewExpr(const CXXNewExpr *E) { 252 return CGF.EmitCXXNewExpr(E); 253 } 254 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) { 255 CGF.EmitCXXDeleteExpr(E); 256 return 0; 257 } 258 259 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) { 260 // C++ [expr.pseudo]p1: 261 // The result shall only be used as the operand for the function call 262 // operator (), and the result of such a call has type void. The only 263 // effect is the evaluation of the postfix-expression before the dot or 264 // arrow. 265 CGF.EmitScalarExpr(E->getBase()); 266 return 0; 267 } 268 269 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 270 return llvm::Constant::getNullValue(ConvertType(E->getType())); 271 } 272 273 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) { 274 CGF.EmitCXXThrowExpr(E); 275 return 0; 276 } 277 278 // Binary Operators. 279 Value *EmitMul(const BinOpInfo &Ops) { 280 if (CGF.getContext().getLangOptions().OverflowChecking 281 && Ops.Ty->isSignedIntegerType()) 282 return EmitOverflowCheckedBinOp(Ops); 283 if (Ops.LHS->getType()->isFPOrFPVector()) 284 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul"); 285 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul"); 286 } 287 /// Create a binary op that checks for overflow. 288 /// Currently only supports +, - and *. 289 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops); 290 Value *EmitDiv(const BinOpInfo &Ops); 291 Value *EmitRem(const BinOpInfo &Ops); 292 Value *EmitAdd(const BinOpInfo &Ops); 293 Value *EmitSub(const BinOpInfo &Ops); 294 Value *EmitShl(const BinOpInfo &Ops); 295 Value *EmitShr(const BinOpInfo &Ops); 296 Value *EmitAnd(const BinOpInfo &Ops) { 297 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and"); 298 } 299 Value *EmitXor(const BinOpInfo &Ops) { 300 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor"); 301 } 302 Value *EmitOr (const BinOpInfo &Ops) { 303 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or"); 304 } 305 306 BinOpInfo EmitBinOps(const BinaryOperator *E); 307 Value *EmitCompoundAssign(const CompoundAssignOperator *E, 308 Value *(ScalarExprEmitter::*F)(const BinOpInfo &)); 309 310 // Binary operators and binary compound assignment operators. 311#define HANDLEBINOP(OP) \ 312 Value *VisitBin ## OP(const BinaryOperator *E) { \ 313 return Emit ## OP(EmitBinOps(E)); \ 314 } \ 315 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \ 316 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \ 317 } 318 HANDLEBINOP(Mul); 319 HANDLEBINOP(Div); 320 HANDLEBINOP(Rem); 321 HANDLEBINOP(Add); 322 HANDLEBINOP(Sub); 323 HANDLEBINOP(Shl); 324 HANDLEBINOP(Shr); 325 HANDLEBINOP(And); 326 HANDLEBINOP(Xor); 327 HANDLEBINOP(Or); 328#undef HANDLEBINOP 329 330 // Comparisons. 331 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc, 332 unsigned SICmpOpc, unsigned FCmpOpc); 333#define VISITCOMP(CODE, UI, SI, FP) \ 334 Value *VisitBin##CODE(const BinaryOperator *E) { \ 335 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \ 336 llvm::FCmpInst::FP); } 337 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT); 338 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT); 339 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE); 340 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE); 341 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ); 342 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE); 343#undef VISITCOMP 344 345 Value *VisitBinAssign (const BinaryOperator *E); 346 347 Value *VisitBinLAnd (const BinaryOperator *E); 348 Value *VisitBinLOr (const BinaryOperator *E); 349 Value *VisitBinComma (const BinaryOperator *E); 350 351 // Other Operators. 352 Value *VisitBlockExpr(const BlockExpr *BE); 353 Value *VisitConditionalOperator(const ConditionalOperator *CO); 354 Value *VisitChooseExpr(ChooseExpr *CE); 355 Value *VisitVAArgExpr(VAArgExpr *VE); 356 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) { 357 return CGF.EmitObjCStringLiteral(E); 358 } 359}; 360} // end anonymous namespace. 361 362//===----------------------------------------------------------------------===// 363// Utilities 364//===----------------------------------------------------------------------===// 365 366/// EmitConversionToBool - Convert the specified expression value to a 367/// boolean (i1) truth value. This is equivalent to "Val != 0". 368Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) { 369 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs"); 370 371 if (SrcType->isRealFloatingType()) { 372 // Compare against 0.0 for fp scalars. 373 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType()); 374 return Builder.CreateFCmpUNE(Src, Zero, "tobool"); 375 } 376 377 if (SrcType->isMemberPointerType()) { 378 // FIXME: This is ABI specific. 379 380 // Compare against -1. 381 llvm::Value *NegativeOne = llvm::Constant::getAllOnesValue(Src->getType()); 382 return Builder.CreateICmpNE(Src, NegativeOne, "tobool"); 383 } 384 385 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) && 386 "Unknown scalar type to convert"); 387 388 // Because of the type rules of C, we often end up computing a logical value, 389 // then zero extending it to int, then wanting it as a logical value again. 390 // Optimize this common case. 391 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) { 392 if (ZI->getOperand(0)->getType() == 393 llvm::Type::getInt1Ty(CGF.getLLVMContext())) { 394 Value *Result = ZI->getOperand(0); 395 // If there aren't any more uses, zap the instruction to save space. 396 // Note that there can be more uses, for example if this 397 // is the result of an assignment. 398 if (ZI->use_empty()) 399 ZI->eraseFromParent(); 400 return Result; 401 } 402 } 403 404 // Compare against an integer or pointer null. 405 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType()); 406 return Builder.CreateICmpNE(Src, Zero, "tobool"); 407} 408 409/// EmitScalarConversion - Emit a conversion from the specified type to the 410/// specified destination type, both of which are LLVM scalar types. 411Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType, 412 QualType DstType) { 413 SrcType = CGF.getContext().getCanonicalType(SrcType); 414 DstType = CGF.getContext().getCanonicalType(DstType); 415 if (SrcType == DstType) return Src; 416 417 if (DstType->isVoidType()) return 0; 418 419 llvm::LLVMContext &VMContext = CGF.getLLVMContext(); 420 421 // Handle conversions to bool first, they are special: comparisons against 0. 422 if (DstType->isBooleanType()) 423 return EmitConversionToBool(Src, SrcType); 424 425 const llvm::Type *DstTy = ConvertType(DstType); 426 427 // Ignore conversions like int -> uint. 428 if (Src->getType() == DstTy) 429 return Src; 430 431 // Handle pointer conversions next: pointers can only be converted to/from 432 // other pointers and integers. Check for pointer types in terms of LLVM, as 433 // some native types (like Obj-C id) may map to a pointer type. 434 if (isa<llvm::PointerType>(DstTy)) { 435 // The source value may be an integer, or a pointer. 436 if (isa<llvm::PointerType>(Src->getType())) 437 return Builder.CreateBitCast(Src, DstTy, "conv"); 438 439 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?"); 440 // First, convert to the correct width so that we control the kind of 441 // extension. 442 const llvm::Type *MiddleTy = 443 llvm::IntegerType::get(VMContext, CGF.LLVMPointerWidth); 444 bool InputSigned = SrcType->isSignedIntegerType(); 445 llvm::Value* IntResult = 446 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv"); 447 // Then, cast to pointer. 448 return Builder.CreateIntToPtr(IntResult, DstTy, "conv"); 449 } 450 451 if (isa<llvm::PointerType>(Src->getType())) { 452 // Must be an ptr to int cast. 453 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?"); 454 return Builder.CreatePtrToInt(Src, DstTy, "conv"); 455 } 456 457 // A scalar can be splatted to an extended vector of the same element type 458 if (DstType->isExtVectorType() && !SrcType->isVectorType()) { 459 // Cast the scalar to element type 460 QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType(); 461 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy); 462 463 // Insert the element in element zero of an undef vector 464 llvm::Value *UnV = llvm::UndefValue::get(DstTy); 465 llvm::Value *Idx = 466 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0); 467 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp"); 468 469 // Splat the element across to all elements 470 llvm::SmallVector<llvm::Constant*, 16> Args; 471 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements(); 472 for (unsigned i = 0; i < NumElements; i++) 473 Args.push_back(llvm::ConstantInt::get( 474 llvm::Type::getInt32Ty(VMContext), 0)); 475 476 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements); 477 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat"); 478 return Yay; 479 } 480 481 // Allow bitcast from vector to integer/fp of the same size. 482 if (isa<llvm::VectorType>(Src->getType()) || 483 isa<llvm::VectorType>(DstTy)) 484 return Builder.CreateBitCast(Src, DstTy, "conv"); 485 486 // Finally, we have the arithmetic types: real int/float. 487 if (isa<llvm::IntegerType>(Src->getType())) { 488 bool InputSigned = SrcType->isSignedIntegerType(); 489 if (isa<llvm::IntegerType>(DstTy)) 490 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv"); 491 else if (InputSigned) 492 return Builder.CreateSIToFP(Src, DstTy, "conv"); 493 else 494 return Builder.CreateUIToFP(Src, DstTy, "conv"); 495 } 496 497 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion"); 498 if (isa<llvm::IntegerType>(DstTy)) { 499 if (DstType->isSignedIntegerType()) 500 return Builder.CreateFPToSI(Src, DstTy, "conv"); 501 else 502 return Builder.CreateFPToUI(Src, DstTy, "conv"); 503 } 504 505 assert(DstTy->isFloatingPoint() && "Unknown real conversion"); 506 if (DstTy->getTypeID() < Src->getType()->getTypeID()) 507 return Builder.CreateFPTrunc(Src, DstTy, "conv"); 508 else 509 return Builder.CreateFPExt(Src, DstTy, "conv"); 510} 511 512/// EmitComplexToScalarConversion - Emit a conversion from the specified complex 513/// type to the specified destination type, where the destination type is an 514/// LLVM scalar type. 515Value *ScalarExprEmitter:: 516EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src, 517 QualType SrcTy, QualType DstTy) { 518 // Get the source element type. 519 SrcTy = SrcTy->getAs<ComplexType>()->getElementType(); 520 521 // Handle conversions to bool first, they are special: comparisons against 0. 522 if (DstTy->isBooleanType()) { 523 // Complex != 0 -> (Real != 0) | (Imag != 0) 524 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy); 525 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy); 526 return Builder.CreateOr(Src.first, Src.second, "tobool"); 527 } 528 529 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type, 530 // the imaginary part of the complex value is discarded and the value of the 531 // real part is converted according to the conversion rules for the 532 // corresponding real type. 533 return EmitScalarConversion(Src.first, SrcTy, DstTy); 534} 535 536 537//===----------------------------------------------------------------------===// 538// Visitor Methods 539//===----------------------------------------------------------------------===// 540 541Value *ScalarExprEmitter::VisitExpr(Expr *E) { 542 if (const BinaryOperator *BExpr = dyn_cast<BinaryOperator>(E)) 543 if (BExpr->getOpcode() == BinaryOperator::PtrMemD) { 544 LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(BExpr); 545 Value *InVal = CGF.EmitLoadOfLValue(LV, E->getType()).getScalarVal(); 546 return InVal; 547 } 548 549 CGF.ErrorUnsupported(E, "scalar expression"); 550 if (E->getType()->isVoidType()) 551 return 0; 552 return llvm::UndefValue::get(CGF.ConvertType(E->getType())); 553} 554 555Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) { 556 llvm::SmallVector<llvm::Constant*, 32> indices; 557 for (unsigned i = 2; i < E->getNumSubExprs(); i++) { 558 indices.push_back(cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i)))); 559 } 560 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0)); 561 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1)); 562 Value* SV = llvm::ConstantVector::get(indices.begin(), indices.size()); 563 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle"); 564} 565 566Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) { 567 TestAndClearIgnoreResultAssign(); 568 569 // Emit subscript expressions in rvalue context's. For most cases, this just 570 // loads the lvalue formed by the subscript expr. However, we have to be 571 // careful, because the base of a vector subscript is occasionally an rvalue, 572 // so we can't get it as an lvalue. 573 if (!E->getBase()->getType()->isVectorType()) 574 return EmitLoadOfLValue(E); 575 576 // Handle the vector case. The base must be a vector, the index must be an 577 // integer value. 578 Value *Base = Visit(E->getBase()); 579 Value *Idx = Visit(E->getIdx()); 580 bool IdxSigned = E->getIdx()->getType()->isSignedIntegerType(); 581 Idx = Builder.CreateIntCast(Idx, 582 llvm::Type::getInt32Ty(CGF.getLLVMContext()), 583 IdxSigned, 584 "vecidxcast"); 585 return Builder.CreateExtractElement(Base, Idx, "vecext"); 586} 587 588static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx, 589 unsigned Off, const llvm::Type *I32Ty) { 590 int MV = SVI->getMaskValue(Idx); 591 if (MV == -1) 592 return llvm::UndefValue::get(I32Ty); 593 return llvm::ConstantInt::get(I32Ty, Off+MV); 594} 595 596Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) { 597 bool Ignore = TestAndClearIgnoreResultAssign(); 598 (void)Ignore; 599 assert (Ignore == false && "init list ignored"); 600 unsigned NumInitElements = E->getNumInits(); 601 602 if (E->hadArrayRangeDesignator()) 603 CGF.ErrorUnsupported(E, "GNU array range designator extension"); 604 605 const llvm::VectorType *VType = 606 dyn_cast<llvm::VectorType>(ConvertType(E->getType())); 607 608 // We have a scalar in braces. Just use the first element. 609 if (!VType) 610 return Visit(E->getInit(0)); 611 612 unsigned ResElts = VType->getNumElements(); 613 const llvm::Type *I32Ty = llvm::Type::getInt32Ty(CGF.getLLVMContext()); 614 615 // Loop over initializers collecting the Value for each, and remembering 616 // whether the source was swizzle (ExtVectorElementExpr). This will allow 617 // us to fold the shuffle for the swizzle into the shuffle for the vector 618 // initializer, since LLVM optimizers generally do not want to touch 619 // shuffles. 620 unsigned CurIdx = 0; 621 bool VIsUndefShuffle = false; 622 llvm::Value *V = llvm::UndefValue::get(VType); 623 for (unsigned i = 0; i != NumInitElements; ++i) { 624 Expr *IE = E->getInit(i); 625 Value *Init = Visit(IE); 626 llvm::SmallVector<llvm::Constant*, 16> Args; 627 628 const llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType()); 629 630 // Handle scalar elements. If the scalar initializer is actually one 631 // element of a different vector of the same width, use shuffle instead of 632 // extract+insert. 633 if (!VVT) { 634 if (isa<ExtVectorElementExpr>(IE)) { 635 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init); 636 637 if (EI->getVectorOperandType()->getNumElements() == ResElts) { 638 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand()); 639 Value *LHS = 0, *RHS = 0; 640 if (CurIdx == 0) { 641 // insert into undef -> shuffle (src, undef) 642 Args.push_back(C); 643 for (unsigned j = 1; j != ResElts; ++j) 644 Args.push_back(llvm::UndefValue::get(I32Ty)); 645 646 LHS = EI->getVectorOperand(); 647 RHS = V; 648 VIsUndefShuffle = true; 649 } else if (VIsUndefShuffle) { 650 // insert into undefshuffle && size match -> shuffle (v, src) 651 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V); 652 for (unsigned j = 0; j != CurIdx; ++j) 653 Args.push_back(getMaskElt(SVV, j, 0, I32Ty)); 654 Args.push_back(llvm::ConstantInt::get(I32Ty, 655 ResElts + C->getZExtValue())); 656 for (unsigned j = CurIdx + 1; j != ResElts; ++j) 657 Args.push_back(llvm::UndefValue::get(I32Ty)); 658 659 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0); 660 RHS = EI->getVectorOperand(); 661 VIsUndefShuffle = false; 662 } 663 if (!Args.empty()) { 664 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], ResElts); 665 V = Builder.CreateShuffleVector(LHS, RHS, Mask); 666 ++CurIdx; 667 continue; 668 } 669 } 670 } 671 Value *Idx = llvm::ConstantInt::get(I32Ty, CurIdx); 672 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit"); 673 VIsUndefShuffle = false; 674 ++CurIdx; 675 continue; 676 } 677 678 unsigned InitElts = VVT->getNumElements(); 679 680 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's 681 // input is the same width as the vector being constructed, generate an 682 // optimized shuffle of the swizzle input into the result. 683 unsigned Offset = (CurIdx == 0) ? 0 : ResElts; 684 if (isa<ExtVectorElementExpr>(IE)) { 685 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init); 686 Value *SVOp = SVI->getOperand(0); 687 const llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType()); 688 689 if (OpTy->getNumElements() == ResElts) { 690 for (unsigned j = 0; j != CurIdx; ++j) { 691 // If the current vector initializer is a shuffle with undef, merge 692 // this shuffle directly into it. 693 if (VIsUndefShuffle) { 694 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0, 695 I32Ty)); 696 } else { 697 Args.push_back(llvm::ConstantInt::get(I32Ty, j)); 698 } 699 } 700 for (unsigned j = 0, je = InitElts; j != je; ++j) 701 Args.push_back(getMaskElt(SVI, j, Offset, I32Ty)); 702 for (unsigned j = CurIdx + InitElts; j != ResElts; ++j) 703 Args.push_back(llvm::UndefValue::get(I32Ty)); 704 705 if (VIsUndefShuffle) 706 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0); 707 708 Init = SVOp; 709 } 710 } 711 712 // Extend init to result vector length, and then shuffle its contribution 713 // to the vector initializer into V. 714 if (Args.empty()) { 715 for (unsigned j = 0; j != InitElts; ++j) 716 Args.push_back(llvm::ConstantInt::get(I32Ty, j)); 717 for (unsigned j = InitElts; j != ResElts; ++j) 718 Args.push_back(llvm::UndefValue::get(I32Ty)); 719 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], ResElts); 720 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT), 721 Mask, "vext"); 722 723 Args.clear(); 724 for (unsigned j = 0; j != CurIdx; ++j) 725 Args.push_back(llvm::ConstantInt::get(I32Ty, j)); 726 for (unsigned j = 0; j != InitElts; ++j) 727 Args.push_back(llvm::ConstantInt::get(I32Ty, j+Offset)); 728 for (unsigned j = CurIdx + InitElts; j != ResElts; ++j) 729 Args.push_back(llvm::UndefValue::get(I32Ty)); 730 } 731 732 // If V is undef, make sure it ends up on the RHS of the shuffle to aid 733 // merging subsequent shuffles into this one. 734 if (CurIdx == 0) 735 std::swap(V, Init); 736 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], ResElts); 737 V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit"); 738 VIsUndefShuffle = isa<llvm::UndefValue>(Init); 739 CurIdx += InitElts; 740 } 741 742 // FIXME: evaluate codegen vs. shuffling against constant null vector. 743 // Emit remaining default initializers. 744 const llvm::Type *EltTy = VType->getElementType(); 745 746 // Emit remaining default initializers 747 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) { 748 Value *Idx = llvm::ConstantInt::get(I32Ty, CurIdx); 749 llvm::Value *Init = llvm::Constant::getNullValue(EltTy); 750 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit"); 751 } 752 return V; 753} 754 755// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts 756// have to handle a more broad range of conversions than explicit casts, as they 757// handle things like function to ptr-to-function decay etc. 758Value *ScalarExprEmitter::EmitCastExpr(const CastExpr *CE) { 759 const Expr *E = CE->getSubExpr(); 760 QualType DestTy = CE->getType(); 761 CastExpr::CastKind Kind = CE->getCastKind(); 762 763 if (!DestTy->isVoidType()) 764 TestAndClearIgnoreResultAssign(); 765 766 switch (Kind) { 767 default: 768 // FIXME: Assert here. 769 // assert(0 && "Unhandled cast kind!"); 770 break; 771 case CastExpr::CK_Unknown: 772 // FIXME: We should really assert here - Unknown casts should never get 773 // as far as to codegen. 774 break; 775 case CastExpr::CK_BitCast: { 776 Value *Src = Visit(const_cast<Expr*>(E)); 777 return Builder.CreateBitCast(Src, ConvertType(DestTy)); 778 } 779 case CastExpr::CK_ArrayToPointerDecay: { 780 assert(E->getType()->isArrayType() && 781 "Array to pointer decay must have array source type!"); 782 783 Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays. 784 785 // Note that VLA pointers are always decayed, so we don't need to do 786 // anything here. 787 if (!E->getType()->isVariableArrayType()) { 788 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer"); 789 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType()) 790 ->getElementType()) && 791 "Expected pointer to array"); 792 V = Builder.CreateStructGEP(V, 0, "arraydecay"); 793 } 794 795 // The resultant pointer type can be implicitly casted to other pointer 796 // types as well (e.g. void*) and can be implicitly converted to integer. 797 const llvm::Type *DestLTy = ConvertType(DestTy); 798 if (V->getType() != DestLTy) { 799 if (isa<llvm::PointerType>(DestLTy)) 800 V = Builder.CreateBitCast(V, DestLTy, "ptrconv"); 801 else { 802 assert(isa<llvm::IntegerType>(DestLTy) && "Unknown array decay"); 803 V = Builder.CreatePtrToInt(V, DestLTy, "ptrconv"); 804 } 805 } 806 return V; 807 } 808 case CastExpr::CK_NullToMemberPointer: 809 return CGF.CGM.EmitNullConstant(DestTy); 810 811 case CastExpr::CK_DerivedToBase: { 812 const RecordType *DerivedClassTy = 813 E->getType()->getAs<PointerType>()->getPointeeType()->getAs<RecordType>(); 814 CXXRecordDecl *DerivedClassDecl = 815 cast<CXXRecordDecl>(DerivedClassTy->getDecl()); 816 817 const RecordType *BaseClassTy = 818 DestTy->getAs<PointerType>()->getPointeeType()->getAs<RecordType>(); 819 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseClassTy->getDecl()); 820 821 Value *Src = Visit(const_cast<Expr*>(E)); 822 823 bool NullCheckValue = true; 824 825 if (isa<CXXThisExpr>(E)) { 826 // We always assume that 'this' is never null. 827 NullCheckValue = false; 828 } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) { 829 // And that lvalue casts are never null. 830 if (ICE->isLvalueCast()) 831 NullCheckValue = false; 832 } 833 return CGF.GetAddressCXXOfBaseClass(Src, DerivedClassDecl, BaseClassDecl, 834 NullCheckValue); 835 } 836 837 case CastExpr::CK_IntegralToPointer: { 838 Value *Src = Visit(const_cast<Expr*>(E)); 839 840 // First, convert to the correct width so that we control the kind of 841 // extension. 842 const llvm::Type *MiddleTy = 843 llvm::IntegerType::get(VMContext, CGF.LLVMPointerWidth); 844 bool InputSigned = E->getType()->isSignedIntegerType(); 845 llvm::Value* IntResult = 846 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv"); 847 848 return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy)); 849 } 850 851 case CastExpr::CK_PointerToIntegral: { 852 Value *Src = Visit(const_cast<Expr*>(E)); 853 return Builder.CreatePtrToInt(Src, ConvertType(DestTy)); 854 } 855 856 case CastExpr::CK_Dynamic: { 857 Value *V = Visit(const_cast<Expr*>(E)); 858 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE); 859 return CGF.EmitDynamicCast(V, DCE); 860 } 861 862 } 863 864 // Handle cases where the source is an non-complex type. 865 866 if (!CGF.hasAggregateLLVMType(E->getType())) { 867 Value *Src = Visit(const_cast<Expr*>(E)); 868 869 // Use EmitScalarConversion to perform the conversion. 870 return EmitScalarConversion(Src, E->getType(), DestTy); 871 } 872 873 if (E->getType()->isAnyComplexType()) { 874 // Handle cases where the source is a complex type. 875 bool IgnoreImag = true; 876 bool IgnoreImagAssign = true; 877 bool IgnoreReal = IgnoreResultAssign; 878 bool IgnoreRealAssign = IgnoreResultAssign; 879 if (DestTy->isBooleanType()) 880 IgnoreImagAssign = IgnoreImag = false; 881 else if (DestTy->isVoidType()) { 882 IgnoreReal = IgnoreImag = false; 883 IgnoreRealAssign = IgnoreImagAssign = true; 884 } 885 CodeGenFunction::ComplexPairTy V 886 = CGF.EmitComplexExpr(E, IgnoreReal, IgnoreImag, IgnoreRealAssign, 887 IgnoreImagAssign); 888 return EmitComplexToScalarConversion(V, E->getType(), DestTy); 889 } 890 891 // Okay, this is a cast from an aggregate. It must be a cast to void. Just 892 // evaluate the result and return. 893 CGF.EmitAggExpr(E, 0, false, true); 894 return 0; 895} 896 897Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) { 898 return CGF.EmitCompoundStmt(*E->getSubStmt(), 899 !E->getType()->isVoidType()).getScalarVal(); 900} 901 902Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) { 903 llvm::Value *V = CGF.GetAddrOfBlockDecl(E); 904 if (E->getType().isObjCGCWeak()) 905 return CGF.CGM.getObjCRuntime().EmitObjCWeakRead(CGF, V); 906 return Builder.CreateLoad(V, false, "tmp"); 907} 908 909//===----------------------------------------------------------------------===// 910// Unary Operators 911//===----------------------------------------------------------------------===// 912 913Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E, 914 bool isInc, bool isPre) { 915 LValue LV = EmitLValue(E->getSubExpr()); 916 QualType ValTy = E->getSubExpr()->getType(); 917 Value *InVal = CGF.EmitLoadOfLValue(LV, ValTy).getScalarVal(); 918 919 llvm::LLVMContext &VMContext = CGF.getLLVMContext(); 920 921 int AmountVal = isInc ? 1 : -1; 922 923 if (ValTy->isPointerType() && 924 ValTy->getAs<PointerType>()->isVariableArrayType()) { 925 // The amount of the addition/subtraction needs to account for the VLA size 926 CGF.ErrorUnsupported(E, "VLA pointer inc/dec"); 927 } 928 929 Value *NextVal; 930 if (const llvm::PointerType *PT = 931 dyn_cast<llvm::PointerType>(InVal->getType())) { 932 llvm::Constant *Inc = 933 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), AmountVal); 934 if (!isa<llvm::FunctionType>(PT->getElementType())) { 935 QualType PTEE = ValTy->getPointeeType(); 936 if (const ObjCInterfaceType *OIT = 937 dyn_cast<ObjCInterfaceType>(PTEE)) { 938 // Handle interface types, which are not represented with a concrete type. 939 int size = CGF.getContext().getTypeSize(OIT) / 8; 940 if (!isInc) 941 size = -size; 942 Inc = llvm::ConstantInt::get(Inc->getType(), size); 943 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext); 944 InVal = Builder.CreateBitCast(InVal, i8Ty); 945 NextVal = Builder.CreateGEP(InVal, Inc, "add.ptr"); 946 llvm::Value *lhs = LV.getAddress(); 947 lhs = Builder.CreateBitCast(lhs, llvm::PointerType::getUnqual(i8Ty)); 948 LV = LValue::MakeAddr(lhs, CGF.MakeQualifiers(ValTy)); 949 } else 950 NextVal = Builder.CreateInBoundsGEP(InVal, Inc, "ptrincdec"); 951 } else { 952 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext); 953 NextVal = Builder.CreateBitCast(InVal, i8Ty, "tmp"); 954 NextVal = Builder.CreateGEP(NextVal, Inc, "ptrincdec"); 955 NextVal = Builder.CreateBitCast(NextVal, InVal->getType()); 956 } 957 } else if (InVal->getType() == llvm::Type::getInt1Ty(VMContext) && isInc) { 958 // Bool++ is an interesting case, due to promotion rules, we get: 959 // Bool++ -> Bool = Bool+1 -> Bool = (int)Bool+1 -> 960 // Bool = ((int)Bool+1) != 0 961 // An interesting aspect of this is that increment is always true. 962 // Decrement does not have this property. 963 NextVal = llvm::ConstantInt::getTrue(VMContext); 964 } else if (isa<llvm::IntegerType>(InVal->getType())) { 965 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal); 966 967 // Signed integer overflow is undefined behavior. 968 if (ValTy->isSignedIntegerType()) 969 NextVal = Builder.CreateNSWAdd(InVal, NextVal, isInc ? "inc" : "dec"); 970 else 971 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec"); 972 } else { 973 // Add the inc/dec to the real part. 974 if (InVal->getType()->isFloatTy()) 975 NextVal = 976 llvm::ConstantFP::get(VMContext, 977 llvm::APFloat(static_cast<float>(AmountVal))); 978 else if (InVal->getType()->isDoubleTy()) 979 NextVal = 980 llvm::ConstantFP::get(VMContext, 981 llvm::APFloat(static_cast<double>(AmountVal))); 982 else { 983 llvm::APFloat F(static_cast<float>(AmountVal)); 984 bool ignored; 985 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero, 986 &ignored); 987 NextVal = llvm::ConstantFP::get(VMContext, F); 988 } 989 NextVal = Builder.CreateFAdd(InVal, NextVal, isInc ? "inc" : "dec"); 990 } 991 992 // Store the updated result through the lvalue. 993 if (LV.isBitfield()) 994 CGF.EmitStoreThroughBitfieldLValue(RValue::get(NextVal), LV, ValTy, 995 &NextVal); 996 else 997 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV, ValTy); 998 999 // If this is a postinc, return the value read from memory, otherwise use the 1000 // updated value. 1001 return isPre ? NextVal : InVal; 1002} 1003 1004 1005Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) { 1006 TestAndClearIgnoreResultAssign(); 1007 Value *Op = Visit(E->getSubExpr()); 1008 if (Op->getType()->isFPOrFPVector()) 1009 return Builder.CreateFNeg(Op, "neg"); 1010 return Builder.CreateNeg(Op, "neg"); 1011} 1012 1013Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) { 1014 TestAndClearIgnoreResultAssign(); 1015 Value *Op = Visit(E->getSubExpr()); 1016 return Builder.CreateNot(Op, "neg"); 1017} 1018 1019Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) { 1020 // Compare operand to zero. 1021 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr()); 1022 1023 // Invert value. 1024 // TODO: Could dynamically modify easy computations here. For example, if 1025 // the operand is an icmp ne, turn into icmp eq. 1026 BoolVal = Builder.CreateNot(BoolVal, "lnot"); 1027 1028 // ZExt result to the expr type. 1029 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext"); 1030} 1031 1032/// VisitSizeOfAlignOfExpr - Return the size or alignment of the type of 1033/// argument of the sizeof expression as an integer. 1034Value * 1035ScalarExprEmitter::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) { 1036 QualType TypeToSize = E->getTypeOfArgument(); 1037 if (E->isSizeOf()) { 1038 if (const VariableArrayType *VAT = 1039 CGF.getContext().getAsVariableArrayType(TypeToSize)) { 1040 if (E->isArgumentType()) { 1041 // sizeof(type) - make sure to emit the VLA size. 1042 CGF.EmitVLASize(TypeToSize); 1043 } else { 1044 // C99 6.5.3.4p2: If the argument is an expression of type 1045 // VLA, it is evaluated. 1046 CGF.EmitAnyExpr(E->getArgumentExpr()); 1047 } 1048 1049 return CGF.GetVLASize(VAT); 1050 } 1051 } 1052 1053 // If this isn't sizeof(vla), the result must be constant; use the constant 1054 // folding logic so we don't have to duplicate it here. 1055 Expr::EvalResult Result; 1056 E->Evaluate(Result, CGF.getContext()); 1057 return llvm::ConstantInt::get(VMContext, Result.Val.getInt()); 1058} 1059 1060Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) { 1061 Expr *Op = E->getSubExpr(); 1062 if (Op->getType()->isAnyComplexType()) 1063 return CGF.EmitComplexExpr(Op, false, true, false, true).first; 1064 return Visit(Op); 1065} 1066Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) { 1067 Expr *Op = E->getSubExpr(); 1068 if (Op->getType()->isAnyComplexType()) 1069 return CGF.EmitComplexExpr(Op, true, false, true, false).second; 1070 1071 // __imag on a scalar returns zero. Emit the subexpr to ensure side 1072 // effects are evaluated, but not the actual value. 1073 if (E->isLvalue(CGF.getContext()) == Expr::LV_Valid) 1074 CGF.EmitLValue(Op); 1075 else 1076 CGF.EmitScalarExpr(Op, true); 1077 return llvm::Constant::getNullValue(ConvertType(E->getType())); 1078} 1079 1080Value *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E) { 1081 Value* ResultAsPtr = EmitLValue(E->getSubExpr()).getAddress(); 1082 const llvm::Type* ResultType = ConvertType(E->getType()); 1083 return Builder.CreatePtrToInt(ResultAsPtr, ResultType, "offsetof"); 1084} 1085 1086//===----------------------------------------------------------------------===// 1087// Binary Operators 1088//===----------------------------------------------------------------------===// 1089 1090BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) { 1091 TestAndClearIgnoreResultAssign(); 1092 BinOpInfo Result; 1093 Result.LHS = Visit(E->getLHS()); 1094 Result.RHS = Visit(E->getRHS()); 1095 Result.Ty = E->getType(); 1096 Result.E = E; 1097 return Result; 1098} 1099 1100Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E, 1101 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) { 1102 bool Ignore = TestAndClearIgnoreResultAssign(); 1103 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType(); 1104 1105 BinOpInfo OpInfo; 1106 1107 if (E->getComputationResultType()->isAnyComplexType()) { 1108 // This needs to go through the complex expression emitter, but it's a tad 1109 // complicated to do that... I'm leaving it out for now. (Note that we do 1110 // actually need the imaginary part of the RHS for multiplication and 1111 // division.) 1112 CGF.ErrorUnsupported(E, "complex compound assignment"); 1113 return llvm::UndefValue::get(CGF.ConvertType(E->getType())); 1114 } 1115 1116 // Emit the RHS first. __block variables need to have the rhs evaluated 1117 // first, plus this should improve codegen a little. 1118 OpInfo.RHS = Visit(E->getRHS()); 1119 OpInfo.Ty = E->getComputationResultType(); 1120 OpInfo.E = E; 1121 // Load/convert the LHS. 1122 LValue LHSLV = EmitLValue(E->getLHS()); 1123 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy); 1124 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, 1125 E->getComputationLHSType()); 1126 1127 // Expand the binary operator. 1128 Value *Result = (this->*Func)(OpInfo); 1129 1130 // Convert the result back to the LHS type. 1131 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy); 1132 1133 // Store the result value into the LHS lvalue. Bit-fields are handled 1134 // specially because the result is altered by the store, i.e., [C99 6.5.16p1] 1135 // 'An assignment expression has the value of the left operand after the 1136 // assignment...'. 1137 if (LHSLV.isBitfield()) { 1138 if (!LHSLV.isVolatileQualified()) { 1139 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy, 1140 &Result); 1141 return Result; 1142 } else 1143 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy); 1144 } else 1145 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy); 1146 if (Ignore) 1147 return 0; 1148 return EmitLoadOfLValue(LHSLV, E->getType()); 1149} 1150 1151 1152Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) { 1153 if (Ops.LHS->getType()->isFPOrFPVector()) 1154 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div"); 1155 else if (Ops.Ty->isUnsignedIntegerType()) 1156 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div"); 1157 else 1158 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div"); 1159} 1160 1161Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) { 1162 // Rem in C can't be a floating point type: C99 6.5.5p2. 1163 if (Ops.Ty->isUnsignedIntegerType()) 1164 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem"); 1165 else 1166 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem"); 1167} 1168 1169Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) { 1170 unsigned IID; 1171 unsigned OpID = 0; 1172 1173 switch (Ops.E->getOpcode()) { 1174 case BinaryOperator::Add: 1175 case BinaryOperator::AddAssign: 1176 OpID = 1; 1177 IID = llvm::Intrinsic::sadd_with_overflow; 1178 break; 1179 case BinaryOperator::Sub: 1180 case BinaryOperator::SubAssign: 1181 OpID = 2; 1182 IID = llvm::Intrinsic::ssub_with_overflow; 1183 break; 1184 case BinaryOperator::Mul: 1185 case BinaryOperator::MulAssign: 1186 OpID = 3; 1187 IID = llvm::Intrinsic::smul_with_overflow; 1188 break; 1189 default: 1190 assert(false && "Unsupported operation for overflow detection"); 1191 IID = 0; 1192 } 1193 OpID <<= 1; 1194 OpID |= 1; 1195 1196 const llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty); 1197 1198 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, &opTy, 1); 1199 1200 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS); 1201 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0); 1202 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1); 1203 1204 // Branch in case of overflow. 1205 llvm::BasicBlock *initialBB = Builder.GetInsertBlock(); 1206 llvm::BasicBlock *overflowBB = 1207 CGF.createBasicBlock("overflow", CGF.CurFn); 1208 llvm::BasicBlock *continueBB = 1209 CGF.createBasicBlock("overflow.continue", CGF.CurFn); 1210 1211 Builder.CreateCondBr(overflow, overflowBB, continueBB); 1212 1213 // Handle overflow 1214 1215 Builder.SetInsertPoint(overflowBB); 1216 1217 // Handler is: 1218 // long long *__overflow_handler)(long long a, long long b, char op, 1219 // char width) 1220 std::vector<const llvm::Type*> handerArgTypes; 1221 handerArgTypes.push_back(llvm::Type::getInt64Ty(VMContext)); 1222 handerArgTypes.push_back(llvm::Type::getInt64Ty(VMContext)); 1223 handerArgTypes.push_back(llvm::Type::getInt8Ty(VMContext)); 1224 handerArgTypes.push_back(llvm::Type::getInt8Ty(VMContext)); 1225 llvm::FunctionType *handlerTy = llvm::FunctionType::get( 1226 llvm::Type::getInt64Ty(VMContext), handerArgTypes, false); 1227 llvm::Value *handlerFunction = 1228 CGF.CGM.getModule().getOrInsertGlobal("__overflow_handler", 1229 llvm::PointerType::getUnqual(handlerTy)); 1230 handlerFunction = Builder.CreateLoad(handlerFunction); 1231 1232 llvm::Value *handlerResult = Builder.CreateCall4(handlerFunction, 1233 Builder.CreateSExt(Ops.LHS, llvm::Type::getInt64Ty(VMContext)), 1234 Builder.CreateSExt(Ops.RHS, llvm::Type::getInt64Ty(VMContext)), 1235 llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext), OpID), 1236 llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext), 1237 cast<llvm::IntegerType>(opTy)->getBitWidth())); 1238 1239 handlerResult = Builder.CreateTrunc(handlerResult, opTy); 1240 1241 Builder.CreateBr(continueBB); 1242 1243 // Set up the continuation 1244 Builder.SetInsertPoint(continueBB); 1245 // Get the correct result 1246 llvm::PHINode *phi = Builder.CreatePHI(opTy); 1247 phi->reserveOperandSpace(2); 1248 phi->addIncoming(result, initialBB); 1249 phi->addIncoming(handlerResult, overflowBB); 1250 1251 return phi; 1252} 1253 1254Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) { 1255 if (!Ops.Ty->isAnyPointerType()) { 1256 if (CGF.getContext().getLangOptions().OverflowChecking && 1257 Ops.Ty->isSignedIntegerType()) 1258 return EmitOverflowCheckedBinOp(Ops); 1259 1260 if (Ops.LHS->getType()->isFPOrFPVector()) 1261 return Builder.CreateFAdd(Ops.LHS, Ops.RHS, "add"); 1262 1263 // Signed integer overflow is undefined behavior. 1264 if (Ops.Ty->isSignedIntegerType()) 1265 return Builder.CreateNSWAdd(Ops.LHS, Ops.RHS, "add"); 1266 1267 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add"); 1268 } 1269 1270 if (Ops.Ty->isPointerType() && 1271 Ops.Ty->getAs<PointerType>()->isVariableArrayType()) { 1272 // The amount of the addition needs to account for the VLA size 1273 CGF.ErrorUnsupported(Ops.E, "VLA pointer addition"); 1274 } 1275 Value *Ptr, *Idx; 1276 Expr *IdxExp; 1277 const PointerType *PT = Ops.E->getLHS()->getType()->getAs<PointerType>(); 1278 const ObjCObjectPointerType *OPT = 1279 Ops.E->getLHS()->getType()->getAs<ObjCObjectPointerType>(); 1280 if (PT || OPT) { 1281 Ptr = Ops.LHS; 1282 Idx = Ops.RHS; 1283 IdxExp = Ops.E->getRHS(); 1284 } else { // int + pointer 1285 PT = Ops.E->getRHS()->getType()->getAs<PointerType>(); 1286 OPT = Ops.E->getRHS()->getType()->getAs<ObjCObjectPointerType>(); 1287 assert((PT || OPT) && "Invalid add expr"); 1288 Ptr = Ops.RHS; 1289 Idx = Ops.LHS; 1290 IdxExp = Ops.E->getLHS(); 1291 } 1292 1293 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth(); 1294 if (Width < CGF.LLVMPointerWidth) { 1295 // Zero or sign extend the pointer value based on whether the index is 1296 // signed or not. 1297 const llvm::Type *IdxType = 1298 llvm::IntegerType::get(VMContext, CGF.LLVMPointerWidth); 1299 if (IdxExp->getType()->isSignedIntegerType()) 1300 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext"); 1301 else 1302 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext"); 1303 } 1304 const QualType ElementType = PT ? PT->getPointeeType() : OPT->getPointeeType(); 1305 // Handle interface types, which are not represented with a concrete type. 1306 if (const ObjCInterfaceType *OIT = dyn_cast<ObjCInterfaceType>(ElementType)) { 1307 llvm::Value *InterfaceSize = 1308 llvm::ConstantInt::get(Idx->getType(), 1309 CGF.getContext().getTypeSize(OIT) / 8); 1310 Idx = Builder.CreateMul(Idx, InterfaceSize); 1311 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext); 1312 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty); 1313 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr"); 1314 return Builder.CreateBitCast(Res, Ptr->getType()); 1315 } 1316 1317 // Explicitly handle GNU void* and function pointer arithmetic extensions. The 1318 // GNU void* casts amount to no-ops since our void* type is i8*, but this is 1319 // future proof. 1320 if (ElementType->isVoidType() || ElementType->isFunctionType()) { 1321 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext); 1322 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty); 1323 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr"); 1324 return Builder.CreateBitCast(Res, Ptr->getType()); 1325 } 1326 1327 return Builder.CreateInBoundsGEP(Ptr, Idx, "add.ptr"); 1328} 1329 1330Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) { 1331 if (!isa<llvm::PointerType>(Ops.LHS->getType())) { 1332 if (CGF.getContext().getLangOptions().OverflowChecking 1333 && Ops.Ty->isSignedIntegerType()) 1334 return EmitOverflowCheckedBinOp(Ops); 1335 1336 if (Ops.LHS->getType()->isFPOrFPVector()) 1337 return Builder.CreateFSub(Ops.LHS, Ops.RHS, "sub"); 1338 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub"); 1339 } 1340 1341 if (Ops.E->getLHS()->getType()->isPointerType() && 1342 Ops.E->getLHS()->getType()->getAs<PointerType>()->isVariableArrayType()) { 1343 // The amount of the addition needs to account for the VLA size for 1344 // ptr-int 1345 // The amount of the division needs to account for the VLA size for 1346 // ptr-ptr. 1347 CGF.ErrorUnsupported(Ops.E, "VLA pointer subtraction"); 1348 } 1349 1350 const QualType LHSType = Ops.E->getLHS()->getType(); 1351 const QualType LHSElementType = LHSType->getPointeeType(); 1352 if (!isa<llvm::PointerType>(Ops.RHS->getType())) { 1353 // pointer - int 1354 Value *Idx = Ops.RHS; 1355 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth(); 1356 if (Width < CGF.LLVMPointerWidth) { 1357 // Zero or sign extend the pointer value based on whether the index is 1358 // signed or not. 1359 const llvm::Type *IdxType = 1360 llvm::IntegerType::get(VMContext, CGF.LLVMPointerWidth); 1361 if (Ops.E->getRHS()->getType()->isSignedIntegerType()) 1362 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext"); 1363 else 1364 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext"); 1365 } 1366 Idx = Builder.CreateNeg(Idx, "sub.ptr.neg"); 1367 1368 // Handle interface types, which are not represented with a concrete type. 1369 if (const ObjCInterfaceType *OIT = 1370 dyn_cast<ObjCInterfaceType>(LHSElementType)) { 1371 llvm::Value *InterfaceSize = 1372 llvm::ConstantInt::get(Idx->getType(), 1373 CGF.getContext().getTypeSize(OIT) / 8); 1374 Idx = Builder.CreateMul(Idx, InterfaceSize); 1375 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext); 1376 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty); 1377 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "add.ptr"); 1378 return Builder.CreateBitCast(Res, Ops.LHS->getType()); 1379 } 1380 1381 // Explicitly handle GNU void* and function pointer arithmetic 1382 // extensions. The GNU void* casts amount to no-ops since our void* type is 1383 // i8*, but this is future proof. 1384 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) { 1385 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext); 1386 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty); 1387 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "sub.ptr"); 1388 return Builder.CreateBitCast(Res, Ops.LHS->getType()); 1389 } 1390 1391 return Builder.CreateInBoundsGEP(Ops.LHS, Idx, "sub.ptr"); 1392 } else { 1393 // pointer - pointer 1394 Value *LHS = Ops.LHS; 1395 Value *RHS = Ops.RHS; 1396 1397 uint64_t ElementSize; 1398 1399 // Handle GCC extension for pointer arithmetic on void* and function pointer 1400 // types. 1401 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) { 1402 ElementSize = 1; 1403 } else { 1404 ElementSize = CGF.getContext().getTypeSize(LHSElementType) / 8; 1405 } 1406 1407 const llvm::Type *ResultType = ConvertType(Ops.Ty); 1408 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast"); 1409 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast"); 1410 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub"); 1411 1412 // Optimize out the shift for element size of 1. 1413 if (ElementSize == 1) 1414 return BytesBetween; 1415 1416 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since 1417 // pointer difference in C is only defined in the case where both operands 1418 // are pointing to elements of an array. 1419 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize); 1420 return Builder.CreateExactSDiv(BytesBetween, BytesPerElt, "sub.ptr.div"); 1421 } 1422} 1423 1424Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) { 1425 // LLVM requires the LHS and RHS to be the same type: promote or truncate the 1426 // RHS to the same size as the LHS. 1427 Value *RHS = Ops.RHS; 1428 if (Ops.LHS->getType() != RHS->getType()) 1429 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom"); 1430 1431 return Builder.CreateShl(Ops.LHS, RHS, "shl"); 1432} 1433 1434Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) { 1435 // LLVM requires the LHS and RHS to be the same type: promote or truncate the 1436 // RHS to the same size as the LHS. 1437 Value *RHS = Ops.RHS; 1438 if (Ops.LHS->getType() != RHS->getType()) 1439 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom"); 1440 1441 if (Ops.Ty->isUnsignedIntegerType()) 1442 return Builder.CreateLShr(Ops.LHS, RHS, "shr"); 1443 return Builder.CreateAShr(Ops.LHS, RHS, "shr"); 1444} 1445 1446Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc, 1447 unsigned SICmpOpc, unsigned FCmpOpc) { 1448 TestAndClearIgnoreResultAssign(); 1449 Value *Result; 1450 QualType LHSTy = E->getLHS()->getType(); 1451 if (!LHSTy->isAnyComplexType()) { 1452 Value *LHS = Visit(E->getLHS()); 1453 Value *RHS = Visit(E->getRHS()); 1454 1455 if (LHS->getType()->isFPOrFPVector()) { 1456 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc, 1457 LHS, RHS, "cmp"); 1458 } else if (LHSTy->isSignedIntegerType()) { 1459 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc, 1460 LHS, RHS, "cmp"); 1461 } else { 1462 // Unsigned integers and pointers. 1463 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc, 1464 LHS, RHS, "cmp"); 1465 } 1466 1467 // If this is a vector comparison, sign extend the result to the appropriate 1468 // vector integer type and return it (don't convert to bool). 1469 if (LHSTy->isVectorType()) 1470 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext"); 1471 1472 } else { 1473 // Complex Comparison: can only be an equality comparison. 1474 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS()); 1475 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS()); 1476 1477 QualType CETy = LHSTy->getAs<ComplexType>()->getElementType(); 1478 1479 Value *ResultR, *ResultI; 1480 if (CETy->isRealFloatingType()) { 1481 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc, 1482 LHS.first, RHS.first, "cmp.r"); 1483 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc, 1484 LHS.second, RHS.second, "cmp.i"); 1485 } else { 1486 // Complex comparisons can only be equality comparisons. As such, signed 1487 // and unsigned opcodes are the same. 1488 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc, 1489 LHS.first, RHS.first, "cmp.r"); 1490 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc, 1491 LHS.second, RHS.second, "cmp.i"); 1492 } 1493 1494 if (E->getOpcode() == BinaryOperator::EQ) { 1495 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri"); 1496 } else { 1497 assert(E->getOpcode() == BinaryOperator::NE && 1498 "Complex comparison other than == or != ?"); 1499 Result = Builder.CreateOr(ResultR, ResultI, "or.ri"); 1500 } 1501 } 1502 1503 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType()); 1504} 1505 1506Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) { 1507 bool Ignore = TestAndClearIgnoreResultAssign(); 1508 1509 // __block variables need to have the rhs evaluated first, plus this should 1510 // improve codegen just a little. 1511 Value *RHS = Visit(E->getRHS()); 1512 LValue LHS = EmitLValue(E->getLHS()); 1513 1514 // Store the value into the LHS. Bit-fields are handled specially 1515 // because the result is altered by the store, i.e., [C99 6.5.16p1] 1516 // 'An assignment expression has the value of the left operand after 1517 // the assignment...'. 1518 if (LHS.isBitfield()) { 1519 if (!LHS.isVolatileQualified()) { 1520 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType(), 1521 &RHS); 1522 return RHS; 1523 } else 1524 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType()); 1525 } else 1526 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType()); 1527 if (Ignore) 1528 return 0; 1529 return EmitLoadOfLValue(LHS, E->getType()); 1530} 1531 1532Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) { 1533 const llvm::Type *ResTy = ConvertType(E->getType()); 1534 1535 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0. 1536 // If we have 1 && X, just emit X without inserting the control flow. 1537 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) { 1538 if (Cond == 1) { // If we have 1 && X, just emit X. 1539 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 1540 // ZExt result to int or bool. 1541 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext"); 1542 } 1543 1544 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false. 1545 if (!CGF.ContainsLabel(E->getRHS())) 1546 return llvm::Constant::getNullValue(ResTy); 1547 } 1548 1549 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end"); 1550 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs"); 1551 1552 // Branch on the LHS first. If it is false, go to the failure (cont) block. 1553 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock); 1554 1555 // Any edges into the ContBlock are now from an (indeterminate number of) 1556 // edges from this first condition. All of these values will be false. Start 1557 // setting up the PHI node in the Cont Block for this. 1558 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 1559 "", ContBlock); 1560 PN->reserveOperandSpace(2); // Normal case, two inputs. 1561 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock); 1562 PI != PE; ++PI) 1563 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI); 1564 1565 CGF.PushConditionalTempDestruction(); 1566 CGF.EmitBlock(RHSBlock); 1567 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 1568 CGF.PopConditionalTempDestruction(); 1569 1570 // Reaquire the RHS block, as there may be subblocks inserted. 1571 RHSBlock = Builder.GetInsertBlock(); 1572 1573 // Emit an unconditional branch from this block to ContBlock. Insert an entry 1574 // into the phi node for the edge with the value of RHSCond. 1575 CGF.EmitBlock(ContBlock); 1576 PN->addIncoming(RHSCond, RHSBlock); 1577 1578 // ZExt result to int. 1579 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext"); 1580} 1581 1582Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) { 1583 const llvm::Type *ResTy = ConvertType(E->getType()); 1584 1585 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1. 1586 // If we have 0 || X, just emit X without inserting the control flow. 1587 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) { 1588 if (Cond == -1) { // If we have 0 || X, just emit X. 1589 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 1590 // ZExt result to int or bool. 1591 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext"); 1592 } 1593 1594 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true. 1595 if (!CGF.ContainsLabel(E->getRHS())) 1596 return llvm::ConstantInt::get(ResTy, 1); 1597 } 1598 1599 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end"); 1600 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs"); 1601 1602 // Branch on the LHS first. If it is true, go to the success (cont) block. 1603 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock); 1604 1605 // Any edges into the ContBlock are now from an (indeterminate number of) 1606 // edges from this first condition. All of these values will be true. Start 1607 // setting up the PHI node in the Cont Block for this. 1608 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 1609 "", ContBlock); 1610 PN->reserveOperandSpace(2); // Normal case, two inputs. 1611 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock); 1612 PI != PE; ++PI) 1613 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI); 1614 1615 CGF.PushConditionalTempDestruction(); 1616 1617 // Emit the RHS condition as a bool value. 1618 CGF.EmitBlock(RHSBlock); 1619 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 1620 1621 CGF.PopConditionalTempDestruction(); 1622 1623 // Reaquire the RHS block, as there may be subblocks inserted. 1624 RHSBlock = Builder.GetInsertBlock(); 1625 1626 // Emit an unconditional branch from this block to ContBlock. Insert an entry 1627 // into the phi node for the edge with the value of RHSCond. 1628 CGF.EmitBlock(ContBlock); 1629 PN->addIncoming(RHSCond, RHSBlock); 1630 1631 // ZExt result to int. 1632 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext"); 1633} 1634 1635Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) { 1636 CGF.EmitStmt(E->getLHS()); 1637 CGF.EnsureInsertPoint(); 1638 return Visit(E->getRHS()); 1639} 1640 1641//===----------------------------------------------------------------------===// 1642// Other Operators 1643//===----------------------------------------------------------------------===// 1644 1645/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified 1646/// expression is cheap enough and side-effect-free enough to evaluate 1647/// unconditionally instead of conditionally. This is used to convert control 1648/// flow into selects in some cases. 1649static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E, 1650 CodeGenFunction &CGF) { 1651 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 1652 return isCheapEnoughToEvaluateUnconditionally(PE->getSubExpr(), CGF); 1653 1654 // TODO: Allow anything we can constant fold to an integer or fp constant. 1655 if (isa<IntegerLiteral>(E) || isa<CharacterLiteral>(E) || 1656 isa<FloatingLiteral>(E)) 1657 return true; 1658 1659 // Non-volatile automatic variables too, to get "cond ? X : Y" where 1660 // X and Y are local variables. 1661 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 1662 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) 1663 if (VD->hasLocalStorage() && !(CGF.getContext() 1664 .getCanonicalType(VD->getType()) 1665 .isVolatileQualified())) 1666 return true; 1667 1668 return false; 1669} 1670 1671 1672Value *ScalarExprEmitter:: 1673VisitConditionalOperator(const ConditionalOperator *E) { 1674 TestAndClearIgnoreResultAssign(); 1675 // If the condition constant folds and can be elided, try to avoid emitting 1676 // the condition and the dead arm. 1677 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getCond())){ 1678 Expr *Live = E->getLHS(), *Dead = E->getRHS(); 1679 if (Cond == -1) 1680 std::swap(Live, Dead); 1681 1682 // If the dead side doesn't have labels we need, and if the Live side isn't 1683 // the gnu missing ?: extension (which we could handle, but don't bother 1684 // to), just emit the Live part. 1685 if ((!Dead || !CGF.ContainsLabel(Dead)) && // No labels in dead part 1686 Live) // Live part isn't missing. 1687 return Visit(Live); 1688 } 1689 1690 1691 // If this is a really simple expression (like x ? 4 : 5), emit this as a 1692 // select instead of as control flow. We can only do this if it is cheap and 1693 // safe to evaluate the LHS and RHS unconditionally. 1694 if (E->getLHS() && isCheapEnoughToEvaluateUnconditionally(E->getLHS(), 1695 CGF) && 1696 isCheapEnoughToEvaluateUnconditionally(E->getRHS(), CGF)) { 1697 llvm::Value *CondV = CGF.EvaluateExprAsBool(E->getCond()); 1698 llvm::Value *LHS = Visit(E->getLHS()); 1699 llvm::Value *RHS = Visit(E->getRHS()); 1700 return Builder.CreateSelect(CondV, LHS, RHS, "cond"); 1701 } 1702 1703 1704 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true"); 1705 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false"); 1706 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end"); 1707 Value *CondVal = 0; 1708 1709 // If we don't have the GNU missing condition extension, emit a branch on bool 1710 // the normal way. 1711 if (E->getLHS()) { 1712 // Otherwise, just use EmitBranchOnBoolExpr to get small and simple code for 1713 // the branch on bool. 1714 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock); 1715 } else { 1716 // Otherwise, for the ?: extension, evaluate the conditional and then 1717 // convert it to bool the hard way. We do this explicitly because we need 1718 // the unconverted value for the missing middle value of the ?:. 1719 CondVal = CGF.EmitScalarExpr(E->getCond()); 1720 1721 // In some cases, EmitScalarConversion will delete the "CondVal" expression 1722 // if there are no extra uses (an optimization). Inhibit this by making an 1723 // extra dead use, because we're going to add a use of CondVal later. We 1724 // don't use the builder for this, because we don't want it to get optimized 1725 // away. This leaves dead code, but the ?: extension isn't common. 1726 new llvm::BitCastInst(CondVal, CondVal->getType(), "dummy?:holder", 1727 Builder.GetInsertBlock()); 1728 1729 Value *CondBoolVal = 1730 CGF.EmitScalarConversion(CondVal, E->getCond()->getType(), 1731 CGF.getContext().BoolTy); 1732 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock); 1733 } 1734 1735 CGF.PushConditionalTempDestruction(); 1736 CGF.EmitBlock(LHSBlock); 1737 1738 // Handle the GNU extension for missing LHS. 1739 Value *LHS; 1740 if (E->getLHS()) 1741 LHS = Visit(E->getLHS()); 1742 else // Perform promotions, to handle cases like "short ?: int" 1743 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType()); 1744 1745 CGF.PopConditionalTempDestruction(); 1746 LHSBlock = Builder.GetInsertBlock(); 1747 CGF.EmitBranch(ContBlock); 1748 1749 CGF.PushConditionalTempDestruction(); 1750 CGF.EmitBlock(RHSBlock); 1751 1752 Value *RHS = Visit(E->getRHS()); 1753 CGF.PopConditionalTempDestruction(); 1754 RHSBlock = Builder.GetInsertBlock(); 1755 CGF.EmitBranch(ContBlock); 1756 1757 CGF.EmitBlock(ContBlock); 1758 1759 if (!LHS || !RHS) { 1760 assert(E->getType()->isVoidType() && "Non-void value should have a value"); 1761 return 0; 1762 } 1763 1764 // Create a PHI node for the real part. 1765 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond"); 1766 PN->reserveOperandSpace(2); 1767 PN->addIncoming(LHS, LHSBlock); 1768 PN->addIncoming(RHS, RHSBlock); 1769 return PN; 1770} 1771 1772Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) { 1773 return Visit(E->getChosenSubExpr(CGF.getContext())); 1774} 1775 1776Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) { 1777 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr()); 1778 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType()); 1779 1780 // If EmitVAArg fails, we fall back to the LLVM instruction. 1781 if (!ArgPtr) 1782 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType())); 1783 1784 // FIXME Volatility. 1785 return Builder.CreateLoad(ArgPtr); 1786} 1787 1788Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *BE) { 1789 return CGF.BuildBlockLiteralTmp(BE); 1790} 1791 1792//===----------------------------------------------------------------------===// 1793// Entry Point into this File 1794//===----------------------------------------------------------------------===// 1795 1796/// EmitScalarExpr - Emit the computation of the specified expression of scalar 1797/// type, ignoring the result. 1798Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) { 1799 assert(E && !hasAggregateLLVMType(E->getType()) && 1800 "Invalid scalar expression to emit"); 1801 1802 return ScalarExprEmitter(*this, IgnoreResultAssign) 1803 .Visit(const_cast<Expr*>(E)); 1804} 1805 1806/// EmitScalarConversion - Emit a conversion from the specified type to the 1807/// specified destination type, both of which are LLVM scalar types. 1808Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy, 1809 QualType DstTy) { 1810 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) && 1811 "Invalid scalar expression to emit"); 1812 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy); 1813} 1814 1815/// EmitComplexToScalarConversion - Emit a conversion from the specified complex 1816/// type to the specified destination type, where the destination type is an 1817/// LLVM scalar type. 1818Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src, 1819 QualType SrcTy, 1820 QualType DstTy) { 1821 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) && 1822 "Invalid complex -> scalar conversion"); 1823 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy, 1824 DstTy); 1825} 1826 1827Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) { 1828 assert(V1->getType() == V2->getType() && 1829 "Vector operands must be of the same type"); 1830 unsigned NumElements = 1831 cast<llvm::VectorType>(V1->getType())->getNumElements(); 1832 1833 va_list va; 1834 va_start(va, V2); 1835 1836 llvm::SmallVector<llvm::Constant*, 16> Args; 1837 for (unsigned i = 0; i < NumElements; i++) { 1838 int n = va_arg(va, int); 1839 assert(n >= 0 && n < (int)NumElements * 2 && 1840 "Vector shuffle index out of bounds!"); 1841 Args.push_back(llvm::ConstantInt::get( 1842 llvm::Type::getInt32Ty(VMContext), n)); 1843 } 1844 1845 const char *Name = va_arg(va, const char *); 1846 va_end(va); 1847 1848 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements); 1849 1850 return Builder.CreateShuffleVector(V1, V2, Mask, Name); 1851} 1852 1853llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals, 1854 unsigned NumVals, bool isSplat) { 1855 llvm::Value *Vec 1856 = llvm::UndefValue::get(llvm::VectorType::get(Vals[0]->getType(), NumVals)); 1857 1858 for (unsigned i = 0, e = NumVals; i != e; ++i) { 1859 llvm::Value *Val = isSplat ? Vals[0] : Vals[i]; 1860 llvm::Value *Idx = llvm::ConstantInt::get( 1861 llvm::Type::getInt32Ty(VMContext), i); 1862 Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp"); 1863 } 1864 1865 return Vec; 1866} 1867