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