CGExprScalar.cpp revision 5d46315ca3cbbfe0d0f5f65520b618fb05dd4446
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 "CodeGenModule.h" 16#include "clang/AST/ASTContext.h" 17#include "clang/AST/DeclObjC.h" 18#include "clang/AST/StmtVisitor.h" 19#include "clang/Basic/TargetInfo.h" 20#include "llvm/Constants.h" 21#include "llvm/Function.h" 22#include "llvm/GlobalVariable.h" 23#include "llvm/Intrinsics.h" 24#include "llvm/Support/Compiler.h" 25#include "llvm/Support/CFG.h" 26#include <cstdarg> 27 28using namespace clang; 29using namespace CodeGen; 30using llvm::Value; 31 32//===----------------------------------------------------------------------===// 33// Scalar Expression Emitter 34//===----------------------------------------------------------------------===// 35 36struct BinOpInfo { 37 Value *LHS; 38 Value *RHS; 39 QualType Ty; // Computation Type. 40 const BinaryOperator *E; 41}; 42 43namespace { 44class VISIBILITY_HIDDEN ScalarExprEmitter 45 : public StmtVisitor<ScalarExprEmitter, Value*> { 46 CodeGenFunction &CGF; 47 CGBuilderTy &Builder; 48 49public: 50 51 ScalarExprEmitter(CodeGenFunction &cgf) : CGF(cgf), 52 Builder(CGF.Builder) { 53 } 54 55 //===--------------------------------------------------------------------===// 56 // Utilities 57 //===--------------------------------------------------------------------===// 58 59 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); } 60 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); } 61 62 Value *EmitLoadOfLValue(LValue LV, QualType T) { 63 return CGF.EmitLoadOfLValue(LV, T).getScalarVal(); 64 } 65 66 /// EmitLoadOfLValue - Given an expression with complex type that represents a 67 /// value l-value, this method emits the address of the l-value, then loads 68 /// and returns the result. 69 Value *EmitLoadOfLValue(const Expr *E) { 70 // FIXME: Volatile 71 return EmitLoadOfLValue(EmitLValue(E), E->getType()); 72 } 73 74 /// EmitConversionToBool - Convert the specified expression value to a 75 /// boolean (i1) truth value. This is equivalent to "Val != 0". 76 Value *EmitConversionToBool(Value *Src, QualType DstTy); 77 78 /// EmitScalarConversion - Emit a conversion from the specified type to the 79 /// specified destination type, both of which are LLVM scalar types. 80 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy); 81 82 /// EmitComplexToScalarConversion - Emit a conversion from the specified 83 /// complex type to the specified destination type, where the destination 84 /// type is an LLVM scalar type. 85 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src, 86 QualType SrcTy, QualType DstTy); 87 88 //===--------------------------------------------------------------------===// 89 // Visitor Methods 90 //===--------------------------------------------------------------------===// 91 92 Value *VisitStmt(Stmt *S) { 93 S->dump(CGF.getContext().getSourceManager()); 94 assert(0 && "Stmt can't have complex result type!"); 95 return 0; 96 } 97 Value *VisitExpr(Expr *S); 98 Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); } 99 100 // Leaves. 101 Value *VisitIntegerLiteral(const IntegerLiteral *E) { 102 return llvm::ConstantInt::get(E->getValue()); 103 } 104 Value *VisitFloatingLiteral(const FloatingLiteral *E) { 105 return llvm::ConstantFP::get(E->getValue()); 106 } 107 Value *VisitCharacterLiteral(const CharacterLiteral *E) { 108 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()); 109 } 110 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 111 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()); 112 } 113 Value *VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) { 114 return llvm::Constant::getNullValue(ConvertType(E->getType())); 115 } 116 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) { 117 return llvm::ConstantInt::get(ConvertType(E->getType()), 118 CGF.getContext().typesAreCompatible( 119 E->getArgType1(), E->getArgType2())); 120 } 121 Value *VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E); 122 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) { 123 llvm::Value *V = 124 llvm::ConstantInt::get(llvm::Type::Int32Ty, 125 CGF.GetIDForAddrOfLabel(E->getLabel())); 126 127 return Builder.CreateIntToPtr(V, ConvertType(E->getType())); 128 } 129 130 // l-values. 131 Value *VisitDeclRefExpr(DeclRefExpr *E) { 132 if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(E->getDecl())) 133 return llvm::ConstantInt::get(EC->getInitVal()); 134 return EmitLoadOfLValue(E); 135 } 136 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) { 137 return CGF.EmitObjCSelectorExpr(E); 138 } 139 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) { 140 return CGF.EmitObjCProtocolExpr(E); 141 } 142 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { 143 return EmitLoadOfLValue(E); 144 } 145 Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) { 146 return EmitLoadOfLValue(E); 147 } 148 Value *VisitObjCKVCRefExpr(ObjCKVCRefExpr *E) { 149 return EmitLoadOfLValue(E); 150 } 151 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) { 152 return CGF.EmitObjCMessageExpr(E).getScalarVal(); 153 } 154 155 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E); 156 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E); 157 Value *VisitMemberExpr(Expr *E) { return EmitLoadOfLValue(E); } 158 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); } 159 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { 160 return EmitLoadOfLValue(E); 161 } 162 Value *VisitStringLiteral(Expr *E) { return EmitLValue(E).getAddress(); } 163 Value *VisitPredefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); } 164 165 Value *VisitInitListExpr(InitListExpr *E) { 166 unsigned NumInitElements = E->getNumInits(); 167 168 const llvm::VectorType *VType = 169 dyn_cast<llvm::VectorType>(ConvertType(E->getType())); 170 171 // We have a scalar in braces. Just use the first element. 172 if (!VType) 173 return Visit(E->getInit(0)); 174 175 if (E->hadDesignators()) { 176 CGF.ErrorUnsupported(E, "initializer list with designators"); 177 return llvm::UndefValue::get(CGF.ConvertType(E->getType())); 178 } 179 180 unsigned NumVectorElements = VType->getNumElements(); 181 const llvm::Type *ElementType = VType->getElementType(); 182 183 // Emit individual vector element stores. 184 llvm::Value *V = llvm::UndefValue::get(VType); 185 186 // Emit initializers 187 unsigned i; 188 for (i = 0; i < NumInitElements; ++i) { 189 Value *NewV = Visit(E->getInit(i)); 190 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i); 191 V = Builder.CreateInsertElement(V, NewV, Idx); 192 } 193 194 // Emit remaining default initializers 195 for (/* Do not initialize i*/; i < NumVectorElements; ++i) { 196 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i); 197 llvm::Value *NewV = llvm::Constant::getNullValue(ElementType); 198 V = Builder.CreateInsertElement(V, NewV, Idx); 199 } 200 201 return V; 202 } 203 204 Value *VisitImplicitCastExpr(const ImplicitCastExpr *E); 205 Value *VisitCastExpr(const CastExpr *E) { 206 return EmitCastExpr(E->getSubExpr(), E->getType()); 207 } 208 Value *EmitCastExpr(const Expr *E, QualType T); 209 210 Value *VisitCallExpr(const CallExpr *E) { 211 return CGF.EmitCallExpr(E).getScalarVal(); 212 } 213 214 Value *VisitStmtExpr(const StmtExpr *E); 215 216 // Unary Operators. 217 Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre); 218 Value *VisitUnaryPostDec(const UnaryOperator *E) { 219 return VisitPrePostIncDec(E, false, false); 220 } 221 Value *VisitUnaryPostInc(const UnaryOperator *E) { 222 return VisitPrePostIncDec(E, true, false); 223 } 224 Value *VisitUnaryPreDec(const UnaryOperator *E) { 225 return VisitPrePostIncDec(E, false, true); 226 } 227 Value *VisitUnaryPreInc(const UnaryOperator *E) { 228 return VisitPrePostIncDec(E, true, true); 229 } 230 Value *VisitUnaryAddrOf(const UnaryOperator *E) { 231 return EmitLValue(E->getSubExpr()).getAddress(); 232 } 233 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); } 234 Value *VisitUnaryPlus(const UnaryOperator *E) { 235 return Visit(E->getSubExpr()); 236 } 237 Value *VisitUnaryMinus (const UnaryOperator *E); 238 Value *VisitUnaryNot (const UnaryOperator *E); 239 Value *VisitUnaryLNot (const UnaryOperator *E); 240 Value *VisitUnaryReal (const UnaryOperator *E); 241 Value *VisitUnaryImag (const UnaryOperator *E); 242 Value *VisitUnaryExtension(const UnaryOperator *E) { 243 return Visit(E->getSubExpr()); 244 } 245 Value *VisitUnaryOffsetOf(const UnaryOperator *E); 246 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) { 247 return Visit(DAE->getExpr()); 248 } 249 250 // Binary Operators. 251 Value *EmitMul(const BinOpInfo &Ops) { 252 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul"); 253 } 254 Value *EmitDiv(const BinOpInfo &Ops); 255 Value *EmitRem(const BinOpInfo &Ops); 256 Value *EmitAdd(const BinOpInfo &Ops); 257 Value *EmitSub(const BinOpInfo &Ops); 258 Value *EmitShl(const BinOpInfo &Ops); 259 Value *EmitShr(const BinOpInfo &Ops); 260 Value *EmitAnd(const BinOpInfo &Ops) { 261 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and"); 262 } 263 Value *EmitXor(const BinOpInfo &Ops) { 264 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor"); 265 } 266 Value *EmitOr (const BinOpInfo &Ops) { 267 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or"); 268 } 269 270 BinOpInfo EmitBinOps(const BinaryOperator *E); 271 Value *EmitCompoundAssign(const CompoundAssignOperator *E, 272 Value *(ScalarExprEmitter::*F)(const BinOpInfo &)); 273 274 // Binary operators and binary compound assignment operators. 275#define HANDLEBINOP(OP) \ 276 Value *VisitBin ## OP(const BinaryOperator *E) { \ 277 return Emit ## OP(EmitBinOps(E)); \ 278 } \ 279 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \ 280 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \ 281 } 282 HANDLEBINOP(Mul); 283 HANDLEBINOP(Div); 284 HANDLEBINOP(Rem); 285 HANDLEBINOP(Add); 286 HANDLEBINOP(Sub); 287 HANDLEBINOP(Shl); 288 HANDLEBINOP(Shr); 289 HANDLEBINOP(And); 290 HANDLEBINOP(Xor); 291 HANDLEBINOP(Or); 292#undef HANDLEBINOP 293 294 // Comparisons. 295 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc, 296 unsigned SICmpOpc, unsigned FCmpOpc); 297#define VISITCOMP(CODE, UI, SI, FP) \ 298 Value *VisitBin##CODE(const BinaryOperator *E) { \ 299 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \ 300 llvm::FCmpInst::FP); } 301 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT); 302 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT); 303 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE); 304 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE); 305 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ); 306 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE); 307#undef VISITCOMP 308 309 Value *VisitBinAssign (const BinaryOperator *E); 310 311 Value *VisitBinLAnd (const BinaryOperator *E); 312 Value *VisitBinLOr (const BinaryOperator *E); 313 Value *VisitBinComma (const BinaryOperator *E); 314 315 // Other Operators. 316 Value *VisitConditionalOperator(const ConditionalOperator *CO); 317 Value *VisitChooseExpr(ChooseExpr *CE); 318 Value *VisitOverloadExpr(OverloadExpr *OE); 319 Value *VisitVAArgExpr(VAArgExpr *VE); 320 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) { 321 return CGF.EmitObjCStringLiteral(E); 322 } 323 Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E); 324}; 325} // end anonymous namespace. 326 327//===----------------------------------------------------------------------===// 328// Utilities 329//===----------------------------------------------------------------------===// 330 331/// EmitConversionToBool - Convert the specified expression value to a 332/// boolean (i1) truth value. This is equivalent to "Val != 0". 333Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) { 334 assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs"); 335 336 if (SrcType->isRealFloatingType()) { 337 // Compare against 0.0 for fp scalars. 338 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType()); 339 return Builder.CreateFCmpUNE(Src, Zero, "tobool"); 340 } 341 342 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) && 343 "Unknown scalar type to convert"); 344 345 // Because of the type rules of C, we often end up computing a logical value, 346 // then zero extending it to int, then wanting it as a logical value again. 347 // Optimize this common case. 348 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) { 349 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) { 350 Value *Result = ZI->getOperand(0); 351 // If there aren't any more uses, zap the instruction to save space. 352 // Note that there can be more uses, for example if this 353 // is the result of an assignment. 354 if (ZI->use_empty()) 355 ZI->eraseFromParent(); 356 return Result; 357 } 358 } 359 360 // Compare against an integer or pointer null. 361 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType()); 362 return Builder.CreateICmpNE(Src, Zero, "tobool"); 363} 364 365/// EmitScalarConversion - Emit a conversion from the specified type to the 366/// specified destination type, both of which are LLVM scalar types. 367Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType, 368 QualType DstType) { 369 SrcType = CGF.getContext().getCanonicalType(SrcType); 370 DstType = CGF.getContext().getCanonicalType(DstType); 371 if (SrcType == DstType) return Src; 372 373 if (DstType->isVoidType()) return 0; 374 375 // Handle conversions to bool first, they are special: comparisons against 0. 376 if (DstType->isBooleanType()) 377 return EmitConversionToBool(Src, SrcType); 378 379 const llvm::Type *DstTy = ConvertType(DstType); 380 381 // Ignore conversions like int -> uint. 382 if (Src->getType() == DstTy) 383 return Src; 384 385 // Handle pointer conversions next: pointers can only be converted 386 // to/from other pointers and integers. Check for pointer types in 387 // terms of LLVM, as some native types (like Obj-C id) may map to a 388 // pointer type. 389 if (isa<llvm::PointerType>(DstTy)) { 390 // The source value may be an integer, or a pointer. 391 if (isa<llvm::PointerType>(Src->getType())) 392 return Builder.CreateBitCast(Src, DstTy, "conv"); 393 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?"); 394 return Builder.CreateIntToPtr(Src, DstTy, "conv"); 395 } 396 397 if (isa<llvm::PointerType>(Src->getType())) { 398 // Must be an ptr to int cast. 399 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?"); 400 return Builder.CreatePtrToInt(Src, DstTy, "conv"); 401 } 402 403 // A scalar can be splatted to an extended vector of the same element type 404 if (DstType->isExtVectorType() && !isa<VectorType>(SrcType) && 405 cast<llvm::VectorType>(DstTy)->getElementType() == Src->getType()) 406 return CGF.EmitVector(&Src, DstType->getAsVectorType()->getNumElements(), 407 true); 408 409 // Allow bitcast from vector to integer/fp of the same size. 410 if (isa<llvm::VectorType>(Src->getType()) || 411 isa<llvm::VectorType>(DstTy)) 412 return Builder.CreateBitCast(Src, DstTy, "conv"); 413 414 // Finally, we have the arithmetic types: real int/float. 415 if (isa<llvm::IntegerType>(Src->getType())) { 416 bool InputSigned = SrcType->isSignedIntegerType(); 417 if (isa<llvm::IntegerType>(DstTy)) 418 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv"); 419 else if (InputSigned) 420 return Builder.CreateSIToFP(Src, DstTy, "conv"); 421 else 422 return Builder.CreateUIToFP(Src, DstTy, "conv"); 423 } 424 425 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion"); 426 if (isa<llvm::IntegerType>(DstTy)) { 427 if (DstType->isSignedIntegerType()) 428 return Builder.CreateFPToSI(Src, DstTy, "conv"); 429 else 430 return Builder.CreateFPToUI(Src, DstTy, "conv"); 431 } 432 433 assert(DstTy->isFloatingPoint() && "Unknown real conversion"); 434 if (DstTy->getTypeID() < Src->getType()->getTypeID()) 435 return Builder.CreateFPTrunc(Src, DstTy, "conv"); 436 else 437 return Builder.CreateFPExt(Src, DstTy, "conv"); 438} 439 440/// EmitComplexToScalarConversion - Emit a conversion from the specified 441/// complex type to the specified destination type, where the destination 442/// type is an LLVM scalar type. 443Value *ScalarExprEmitter:: 444EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src, 445 QualType SrcTy, QualType DstTy) { 446 // Get the source element type. 447 SrcTy = SrcTy->getAsComplexType()->getElementType(); 448 449 // Handle conversions to bool first, they are special: comparisons against 0. 450 if (DstTy->isBooleanType()) { 451 // Complex != 0 -> (Real != 0) | (Imag != 0) 452 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy); 453 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy); 454 return Builder.CreateOr(Src.first, Src.second, "tobool"); 455 } 456 457 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type, 458 // the imaginary part of the complex value is discarded and the value of the 459 // real part is converted according to the conversion rules for the 460 // corresponding real type. 461 return EmitScalarConversion(Src.first, SrcTy, DstTy); 462} 463 464 465//===----------------------------------------------------------------------===// 466// Visitor Methods 467//===----------------------------------------------------------------------===// 468 469Value *ScalarExprEmitter::VisitExpr(Expr *E) { 470 CGF.ErrorUnsupported(E, "scalar expression"); 471 if (E->getType()->isVoidType()) 472 return 0; 473 return llvm::UndefValue::get(CGF.ConvertType(E->getType())); 474} 475 476Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) { 477 llvm::SmallVector<llvm::Constant*, 32> indices; 478 for (unsigned i = 2; i < E->getNumSubExprs(); i++) { 479 indices.push_back(cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i)))); 480 } 481 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0)); 482 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1)); 483 Value* SV = llvm::ConstantVector::get(indices.begin(), indices.size()); 484 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle"); 485} 486 487Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) { 488 // Emit subscript expressions in rvalue context's. For most cases, this just 489 // loads the lvalue formed by the subscript expr. However, we have to be 490 // careful, because the base of a vector subscript is occasionally an rvalue, 491 // so we can't get it as an lvalue. 492 if (!E->getBase()->getType()->isVectorType()) 493 return EmitLoadOfLValue(E); 494 495 // Handle the vector case. The base must be a vector, the index must be an 496 // integer value. 497 Value *Base = Visit(E->getBase()); 498 Value *Idx = Visit(E->getIdx()); 499 500 // FIXME: Convert Idx to i32 type. 501 return Builder.CreateExtractElement(Base, Idx, "vecext"); 502} 503 504/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but 505/// also handle things like function to pointer-to-function decay, and array to 506/// pointer decay. 507Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) { 508 const Expr *Op = E->getSubExpr(); 509 510 // If this is due to array->pointer conversion, emit the array expression as 511 // an l-value. 512 if (Op->getType()->isArrayType()) { 513 // FIXME: For now we assume that all source arrays map to LLVM arrays. This 514 // will not true when we add support for VLAs. 515 Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays. 516 517 if (!(isa<llvm::PointerType>(V->getType()) && 518 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType()) 519 ->getElementType()))) { 520 CGF.ErrorUnsupported(E, "variable-length array cast", true); 521 if (E->getType()->isVoidType()) 522 return 0; 523 return llvm::UndefValue::get(CGF.ConvertType(E->getType())); 524 } 525 V = Builder.CreateStructGEP(V, 0, "arraydecay"); 526 527 // The resultant pointer type can be implicitly casted to other pointer 528 // types as well (e.g. void*) and can be implicitly converted to integer. 529 const llvm::Type *DestTy = ConvertType(E->getType()); 530 if (V->getType() != DestTy) { 531 if (isa<llvm::PointerType>(DestTy)) 532 V = Builder.CreateBitCast(V, DestTy, "ptrconv"); 533 else { 534 assert(isa<llvm::IntegerType>(DestTy) && "Unknown array decay"); 535 V = Builder.CreatePtrToInt(V, DestTy, "ptrconv"); 536 } 537 } 538 return V; 539 540 } else if (E->getType()->isReferenceType()) { 541 return EmitLValue(Op).getAddress(); 542 } 543 544 return EmitCastExpr(Op, E->getType()); 545} 546 547 548// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts 549// have to handle a more broad range of conversions than explicit casts, as they 550// handle things like function to ptr-to-function decay etc. 551Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) { 552 // Handle cases where the source is an non-complex type. 553 554 if (!CGF.hasAggregateLLVMType(E->getType())) { 555 Value *Src = Visit(const_cast<Expr*>(E)); 556 557 // Use EmitScalarConversion to perform the conversion. 558 return EmitScalarConversion(Src, E->getType(), DestTy); 559 } 560 561 if (E->getType()->isAnyComplexType()) { 562 // Handle cases where the source is a complex type. 563 return EmitComplexToScalarConversion(CGF.EmitComplexExpr(E), E->getType(), 564 DestTy); 565 } 566 567 // Okay, this is a cast from an aggregate. It must be a cast to void. Just 568 // evaluate the result and return. 569 CGF.EmitAggExpr(E, 0, false); 570 return 0; 571} 572 573Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) { 574 return CGF.EmitCompoundStmt(*E->getSubStmt(), 575 !E->getType()->isVoidType()).getScalarVal(); 576} 577 578 579//===----------------------------------------------------------------------===// 580// Unary Operators 581//===----------------------------------------------------------------------===// 582 583Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E, 584 bool isInc, bool isPre) { 585 LValue LV = EmitLValue(E->getSubExpr()); 586 // FIXME: Handle volatile! 587 Value *InVal = CGF.EmitLoadOfLValue(LV, // false 588 E->getSubExpr()->getType()).getScalarVal(); 589 590 int AmountVal = isInc ? 1 : -1; 591 592 Value *NextVal; 593 if (isa<llvm::PointerType>(InVal->getType())) { 594 // FIXME: This isn't right for VLAs. 595 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal); 596 NextVal = Builder.CreateGEP(InVal, NextVal, "ptrincdec"); 597 } else { 598 // Add the inc/dec to the real part. 599 if (isa<llvm::IntegerType>(InVal->getType())) 600 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal); 601 else if (InVal->getType() == llvm::Type::FloatTy) 602 NextVal = 603 llvm::ConstantFP::get(llvm::APFloat(static_cast<float>(AmountVal))); 604 else if (InVal->getType() == llvm::Type::DoubleTy) 605 NextVal = 606 llvm::ConstantFP::get(llvm::APFloat(static_cast<double>(AmountVal))); 607 else { 608 llvm::APFloat F(static_cast<float>(AmountVal)); 609 bool ignored; 610 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero, 611 &ignored); 612 NextVal = llvm::ConstantFP::get(F); 613 } 614 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec"); 615 } 616 617 // Store the updated result through the lvalue. 618 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV, 619 E->getSubExpr()->getType()); 620 621 // If this is a postinc, return the value read from memory, otherwise use the 622 // updated value. 623 return isPre ? NextVal : InVal; 624} 625 626 627Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) { 628 Value *Op = Visit(E->getSubExpr()); 629 return Builder.CreateNeg(Op, "neg"); 630} 631 632Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) { 633 Value *Op = Visit(E->getSubExpr()); 634 return Builder.CreateNot(Op, "neg"); 635} 636 637Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) { 638 // Compare operand to zero. 639 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr()); 640 641 // Invert value. 642 // TODO: Could dynamically modify easy computations here. For example, if 643 // the operand is an icmp ne, turn into icmp eq. 644 BoolVal = Builder.CreateNot(BoolVal, "lnot"); 645 646 // ZExt result to int. 647 return Builder.CreateZExt(BoolVal, CGF.LLVMIntTy, "lnot.ext"); 648} 649 650/// VisitSizeOfAlignOfExpr - Return the size or alignment of the type of 651/// argument of the sizeof expression as an integer. 652Value * 653ScalarExprEmitter::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) { 654 QualType RetType = E->getType(); 655 assert(RetType->isIntegerType() && "Result type must be an integer!"); 656 uint32_t ResultWidth = 657 static_cast<uint32_t>(CGF.getContext().getTypeSize(RetType)); 658 659 QualType TypeToSize = E->getTypeOfArgument(); 660 // sizeof(void) and __alignof__(void) = 1 as a gcc extension. Also 661 // for function types. 662 // FIXME: what is alignof a function type in gcc? 663 if (TypeToSize->isVoidType() || TypeToSize->isFunctionType()) 664 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, 1)); 665 666 if (const VariableArrayType *VAT = 667 CGF.getContext().getAsVariableArrayType(TypeToSize)) { 668 if (E->isSizeOf()) 669 return CGF.GetVLASize(VAT); 670 else 671 assert(0 && "alignof VLAs not implemented yet"); 672 } 673 674 std::pair<uint64_t, unsigned> Info = CGF.getContext().getTypeInfo(TypeToSize); 675 676 uint64_t Val = E->isSizeOf() ? Info.first : Info.second; 677 Val /= 8; // Return size in bytes, not bits. 678 679 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val)); 680} 681 682Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) { 683 Expr *Op = E->getSubExpr(); 684 if (Op->getType()->isAnyComplexType()) 685 return CGF.EmitComplexExpr(Op).first; 686 return Visit(Op); 687} 688Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) { 689 Expr *Op = E->getSubExpr(); 690 if (Op->getType()->isAnyComplexType()) 691 return CGF.EmitComplexExpr(Op).second; 692 693 // __imag on a scalar returns zero. Emit it the subexpr to ensure side 694 // effects are evaluated. 695 CGF.EmitScalarExpr(Op); 696 return llvm::Constant::getNullValue(ConvertType(E->getType())); 697} 698 699Value *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E) 700{ 701 int64_t Val = E->evaluateOffsetOf(CGF.getContext()); 702 703 assert(E->getType()->isIntegerType() && "Result type must be an integer!"); 704 705 uint32_t ResultWidth = 706 static_cast<uint32_t>(CGF.getContext().getTypeSize(E->getType())); 707 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val)); 708} 709 710//===----------------------------------------------------------------------===// 711// Binary Operators 712//===----------------------------------------------------------------------===// 713 714BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) { 715 BinOpInfo Result; 716 Result.LHS = Visit(E->getLHS()); 717 Result.RHS = Visit(E->getRHS()); 718 Result.Ty = E->getType(); 719 Result.E = E; 720 return Result; 721} 722 723Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E, 724 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) { 725 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType(); 726 727 BinOpInfo OpInfo; 728 729 // Load the LHS and RHS operands. 730 LValue LHSLV = EmitLValue(E->getLHS()); 731 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy); 732 733 // Determine the computation type. If the RHS is complex, then this is one of 734 // the add/sub/mul/div operators. All of these operators can be computed in 735 // with just their real component even though the computation domain really is 736 // complex. 737 QualType ComputeType = E->getComputationType(); 738 739 // If the computation type is complex, then the RHS is complex. Emit the RHS. 740 if (const ComplexType *CT = ComputeType->getAsComplexType()) { 741 ComputeType = CT->getElementType(); 742 743 // Emit the RHS, only keeping the real component. 744 OpInfo.RHS = CGF.EmitComplexExpr(E->getRHS()).first; 745 RHSTy = RHSTy->getAsComplexType()->getElementType(); 746 } else { 747 // Otherwise the RHS is a simple scalar value. 748 OpInfo.RHS = Visit(E->getRHS()); 749 } 750 751 QualType LComputeTy, RComputeTy, ResultTy; 752 753 // Compound assignment does not contain enough information about all 754 // the types involved for pointer arithmetic cases. Figure it out 755 // here for now. 756 if (E->getLHS()->getType()->isPointerType()) { 757 // Pointer arithmetic cases: ptr +=,-= int and ptr -= ptr, 758 assert((E->getOpcode() == BinaryOperator::AddAssign || 759 E->getOpcode() == BinaryOperator::SubAssign) && 760 "Invalid compound assignment operator on pointer type."); 761 LComputeTy = E->getLHS()->getType(); 762 763 if (E->getRHS()->getType()->isPointerType()) { 764 // Degenerate case of (ptr -= ptr) allowed by GCC implicit cast 765 // extension, the conversion from the pointer difference back to 766 // the LHS type is handled at the end. 767 assert(E->getOpcode() == BinaryOperator::SubAssign && 768 "Invalid compound assignment operator on pointer type."); 769 RComputeTy = E->getLHS()->getType(); 770 ResultTy = CGF.getContext().getPointerDiffType(); 771 } else { 772 RComputeTy = E->getRHS()->getType(); 773 ResultTy = LComputeTy; 774 } 775 } else if (E->getRHS()->getType()->isPointerType()) { 776 // Degenerate case of (int += ptr) allowed by GCC implicit cast 777 // extension. 778 assert(E->getOpcode() == BinaryOperator::AddAssign && 779 "Invalid compound assignment operator on pointer type."); 780 LComputeTy = E->getLHS()->getType(); 781 RComputeTy = E->getRHS()->getType(); 782 ResultTy = RComputeTy; 783 } else { 784 LComputeTy = RComputeTy = ResultTy = ComputeType; 785 } 786 787 // Convert the LHS/RHS values to the computation type. 788 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, LComputeTy); 789 OpInfo.RHS = EmitScalarConversion(OpInfo.RHS, RHSTy, RComputeTy); 790 OpInfo.Ty = ResultTy; 791 OpInfo.E = E; 792 793 // Expand the binary operator. 794 Value *Result = (this->*Func)(OpInfo); 795 796 // Convert the result back to the LHS type. 797 Result = EmitScalarConversion(Result, ResultTy, LHSTy); 798 799 // Store the result value into the LHS lvalue. Bit-fields are 800 // handled specially because the result is altered by the store, 801 // i.e., [C99 6.5.16p1] 'An assignment expression has the value of 802 // the left operand after the assignment...'. 803 if (LHSLV.isBitfield()) 804 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy, 805 &Result); 806 else 807 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy); 808 809 return Result; 810} 811 812 813Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) { 814 if (Ops.LHS->getType()->isFPOrFPVector()) 815 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div"); 816 else if (Ops.Ty->isUnsignedIntegerType()) 817 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div"); 818 else 819 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div"); 820} 821 822Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) { 823 // Rem in C can't be a floating point type: C99 6.5.5p2. 824 if (Ops.Ty->isUnsignedIntegerType()) 825 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem"); 826 else 827 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem"); 828} 829 830 831Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) { 832 if (!Ops.Ty->isPointerType()) 833 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add"); 834 835 // FIXME: What about a pointer to a VLA? 836 Value *Ptr, *Idx; 837 Expr *IdxExp; 838 if (isa<llvm::PointerType>(Ops.LHS->getType())) { // pointer + int 839 Ptr = Ops.LHS; 840 Idx = Ops.RHS; 841 IdxExp = Ops.E->getRHS(); 842 } else { // int + pointer 843 Ptr = Ops.RHS; 844 Idx = Ops.LHS; 845 IdxExp = Ops.E->getLHS(); 846 } 847 848 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth(); 849 if (Width < CGF.LLVMPointerWidth) { 850 // Zero or sign extend the pointer value based on whether the index is 851 // signed or not. 852 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth); 853 if (IdxExp->getType()->isSignedIntegerType()) 854 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext"); 855 else 856 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext"); 857 } 858 859 return Builder.CreateGEP(Ptr, Idx, "add.ptr"); 860} 861 862Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) { 863 if (!isa<llvm::PointerType>(Ops.LHS->getType())) 864 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub"); 865 866 if (!isa<llvm::PointerType>(Ops.RHS->getType())) { 867 // pointer - int 868 Value *Idx = Ops.RHS; 869 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth(); 870 if (Width < CGF.LLVMPointerWidth) { 871 // Zero or sign extend the pointer value based on whether the index is 872 // signed or not. 873 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth); 874 if (Ops.E->getRHS()->getType()->isSignedIntegerType()) 875 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext"); 876 else 877 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext"); 878 } 879 Idx = Builder.CreateNeg(Idx, "sub.ptr.neg"); 880 881 // FIXME: The pointer could point to a VLA. 882 // The GNU void* - int case is automatically handled here because 883 // our LLVM type for void* is i8*. 884 return Builder.CreateGEP(Ops.LHS, Idx, "sub.ptr"); 885 } else { 886 // pointer - pointer 887 Value *LHS = Ops.LHS; 888 Value *RHS = Ops.RHS; 889 890 const QualType LHSType = Ops.E->getLHS()->getType(); 891 const QualType LHSElementType = LHSType->getAsPointerType()->getPointeeType(); 892 uint64_t ElementSize; 893 894 // Handle GCC extension for pointer arithmetic on void* types. 895 if (LHSElementType->isVoidType()) { 896 ElementSize = 1; 897 } else { 898 ElementSize = CGF.getContext().getTypeSize(LHSElementType) / 8; 899 } 900 901 const llvm::Type *ResultType = ConvertType(Ops.Ty); 902 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast"); 903 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast"); 904 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub"); 905 906 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no 907 // remainder. As such, we handle common power-of-two cases here to generate 908 // better code. See PR2247. 909 if (llvm::isPowerOf2_64(ElementSize)) { 910 Value *ShAmt = 911 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize)); 912 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr"); 913 } 914 915 // Otherwise, do a full sdiv. 916 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize); 917 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div"); 918 } 919} 920 921Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) { 922 // LLVM requires the LHS and RHS to be the same type: promote or truncate the 923 // RHS to the same size as the LHS. 924 Value *RHS = Ops.RHS; 925 if (Ops.LHS->getType() != RHS->getType()) 926 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom"); 927 928 return Builder.CreateShl(Ops.LHS, RHS, "shl"); 929} 930 931Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) { 932 // LLVM requires the LHS and RHS to be the same type: promote or truncate the 933 // RHS to the same size as the LHS. 934 Value *RHS = Ops.RHS; 935 if (Ops.LHS->getType() != RHS->getType()) 936 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom"); 937 938 if (Ops.Ty->isUnsignedIntegerType()) 939 return Builder.CreateLShr(Ops.LHS, RHS, "shr"); 940 return Builder.CreateAShr(Ops.LHS, RHS, "shr"); 941} 942 943Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc, 944 unsigned SICmpOpc, unsigned FCmpOpc) { 945 Value *Result; 946 QualType LHSTy = E->getLHS()->getType(); 947 if (!LHSTy->isAnyComplexType() && !LHSTy->isVectorType()) { 948 Value *LHS = Visit(E->getLHS()); 949 Value *RHS = Visit(E->getRHS()); 950 951 if (LHS->getType()->isFloatingPoint()) { 952 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc, 953 LHS, RHS, "cmp"); 954 } else if (LHSTy->isSignedIntegerType()) { 955 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc, 956 LHS, RHS, "cmp"); 957 } else { 958 // Unsigned integers and pointers. 959 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc, 960 LHS, RHS, "cmp"); 961 } 962 } else if (LHSTy->isVectorType()) { 963 Value *LHS = Visit(E->getLHS()); 964 Value *RHS = Visit(E->getRHS()); 965 966 if (LHS->getType()->isFPOrFPVector()) { 967 Result = Builder.CreateVFCmp((llvm::CmpInst::Predicate)FCmpOpc, 968 LHS, RHS, "cmp"); 969 } else if (LHSTy->isUnsignedIntegerType()) { 970 Result = Builder.CreateVICmp((llvm::CmpInst::Predicate)UICmpOpc, 971 LHS, RHS, "cmp"); 972 } else { 973 // Signed integers and pointers. 974 Result = Builder.CreateVICmp((llvm::CmpInst::Predicate)SICmpOpc, 975 LHS, RHS, "cmp"); 976 } 977 return Result; 978 } else { 979 // Complex Comparison: can only be an equality comparison. 980 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS()); 981 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS()); 982 983 QualType CETy = LHSTy->getAsComplexType()->getElementType(); 984 985 Value *ResultR, *ResultI; 986 if (CETy->isRealFloatingType()) { 987 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc, 988 LHS.first, RHS.first, "cmp.r"); 989 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc, 990 LHS.second, RHS.second, "cmp.i"); 991 } else { 992 // Complex comparisons can only be equality comparisons. As such, signed 993 // and unsigned opcodes are the same. 994 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc, 995 LHS.first, RHS.first, "cmp.r"); 996 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc, 997 LHS.second, RHS.second, "cmp.i"); 998 } 999 1000 if (E->getOpcode() == BinaryOperator::EQ) { 1001 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri"); 1002 } else { 1003 assert(E->getOpcode() == BinaryOperator::NE && 1004 "Complex comparison other than == or != ?"); 1005 Result = Builder.CreateOr(ResultR, ResultI, "or.ri"); 1006 } 1007 } 1008 1009 // ZExt result to int. 1010 return Builder.CreateZExt(Result, CGF.LLVMIntTy, "cmp.ext"); 1011} 1012 1013Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) { 1014 LValue LHS = EmitLValue(E->getLHS()); 1015 Value *RHS = Visit(E->getRHS()); 1016 1017 // Store the value into the LHS. Bit-fields are handled specially 1018 // because the result is altered by the store, i.e., [C99 6.5.16p1] 1019 // 'An assignment expression has the value of the left operand after 1020 // the assignment...'. 1021 // FIXME: Volatility! 1022 if (LHS.isBitfield()) 1023 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType(), 1024 &RHS); 1025 else 1026 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType()); 1027 1028 // Return the RHS. 1029 return RHS; 1030} 1031 1032Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) { 1033 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0. 1034 // If we have 1 && X, just emit X without inserting the control flow. 1035 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) { 1036 if (Cond == 1) { // If we have 1 && X, just emit X. 1037 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 1038 // ZExt result to int. 1039 return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "land.ext"); 1040 } 1041 1042 // 0 && RHS: If it is safe, just elide the RHS, and return 0. 1043 if (!CGF.ContainsLabel(E->getRHS())) 1044 return llvm::Constant::getNullValue(CGF.LLVMIntTy); 1045 } 1046 1047 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end"); 1048 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs"); 1049 1050 // Branch on the LHS first. If it is false, go to the failure (cont) block. 1051 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock); 1052 1053 // Any edges into the ContBlock are now from an (indeterminate number of) 1054 // edges from this first condition. All of these values will be false. Start 1055 // setting up the PHI node in the Cont Block for this. 1056 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::Int1Ty, "", ContBlock); 1057 PN->reserveOperandSpace(2); // Normal case, two inputs. 1058 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock); 1059 PI != PE; ++PI) 1060 PN->addIncoming(llvm::ConstantInt::getFalse(), *PI); 1061 1062 CGF.EmitBlock(RHSBlock); 1063 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 1064 1065 // Reaquire the RHS block, as there may be subblocks inserted. 1066 RHSBlock = Builder.GetInsertBlock(); 1067 1068 // Emit an unconditional branch from this block to ContBlock. Insert an entry 1069 // into the phi node for the edge with the value of RHSCond. 1070 CGF.EmitBlock(ContBlock); 1071 PN->addIncoming(RHSCond, RHSBlock); 1072 1073 // ZExt result to int. 1074 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext"); 1075} 1076 1077Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) { 1078 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1. 1079 // If we have 0 || X, just emit X without inserting the control flow. 1080 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) { 1081 if (Cond == -1) { // If we have 0 || X, just emit X. 1082 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 1083 // ZExt result to int. 1084 return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "lor.ext"); 1085 } 1086 1087 // 1 || RHS: If it is safe, just elide the RHS, and return 1. 1088 if (!CGF.ContainsLabel(E->getRHS())) 1089 return llvm::ConstantInt::get(CGF.LLVMIntTy, 1); 1090 } 1091 1092 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end"); 1093 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs"); 1094 1095 // Branch on the LHS first. If it is true, go to the success (cont) block. 1096 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock); 1097 1098 // Any edges into the ContBlock are now from an (indeterminate number of) 1099 // edges from this first condition. All of these values will be true. Start 1100 // setting up the PHI node in the Cont Block for this. 1101 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::Int1Ty, "", ContBlock); 1102 PN->reserveOperandSpace(2); // Normal case, two inputs. 1103 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock); 1104 PI != PE; ++PI) 1105 PN->addIncoming(llvm::ConstantInt::getTrue(), *PI); 1106 1107 // Emit the RHS condition as a bool value. 1108 CGF.EmitBlock(RHSBlock); 1109 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 1110 1111 // Reaquire the RHS block, as there may be subblocks inserted. 1112 RHSBlock = Builder.GetInsertBlock(); 1113 1114 // Emit an unconditional branch from this block to ContBlock. Insert an entry 1115 // into the phi node for the edge with the value of RHSCond. 1116 CGF.EmitBlock(ContBlock); 1117 PN->addIncoming(RHSCond, RHSBlock); 1118 1119 // ZExt result to int. 1120 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext"); 1121} 1122 1123Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) { 1124 CGF.EmitStmt(E->getLHS()); 1125 CGF.EnsureInsertPoint(); 1126 return Visit(E->getRHS()); 1127} 1128 1129//===----------------------------------------------------------------------===// 1130// Other Operators 1131//===----------------------------------------------------------------------===// 1132 1133/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified 1134/// expression is cheap enough and side-effect-free enough to evaluate 1135/// unconditionally instead of conditionally. This is used to convert control 1136/// flow into selects in some cases. 1137static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E) { 1138 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 1139 return isCheapEnoughToEvaluateUnconditionally(PE->getSubExpr()); 1140 1141 // TODO: Allow anything we can constant fold to an integer or fp constant. 1142 if (isa<IntegerLiteral>(E) || isa<CharacterLiteral>(E) || 1143 isa<FloatingLiteral>(E)) 1144 return true; 1145 1146 // Non-volatile automatic variables too, to get "cond ? X : Y" where 1147 // X and Y are local variables. 1148 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 1149 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) 1150 if (VD->hasLocalStorage() && !VD->getType().isVolatileQualified()) 1151 return true; 1152 1153 return false; 1154} 1155 1156 1157Value *ScalarExprEmitter:: 1158VisitConditionalOperator(const ConditionalOperator *E) { 1159 // If the condition constant folds and can be elided, try to avoid emitting 1160 // the condition and the dead arm. 1161 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getCond())){ 1162 Expr *Live = E->getLHS(), *Dead = E->getRHS(); 1163 if (Cond == -1) 1164 std::swap(Live, Dead); 1165 1166 // If the dead side doesn't have labels we need, and if the Live side isn't 1167 // the gnu missing ?: extension (which we could handle, but don't bother 1168 // to), just emit the Live part. 1169 if ((!Dead || !CGF.ContainsLabel(Dead)) && // No labels in dead part 1170 Live) // Live part isn't missing. 1171 return Visit(Live); 1172 } 1173 1174 1175 // If this is a really simple expression (like x ? 4 : 5), emit this as a 1176 // select instead of as control flow. We can only do this if it is cheap and 1177 // safe to evaluate the LHS and RHS unconditionally. 1178 if (E->getLHS() && isCheapEnoughToEvaluateUnconditionally(E->getLHS()) && 1179 isCheapEnoughToEvaluateUnconditionally(E->getRHS())) { 1180 llvm::Value *CondV = CGF.EvaluateExprAsBool(E->getCond()); 1181 llvm::Value *LHS = Visit(E->getLHS()); 1182 llvm::Value *RHS = Visit(E->getRHS()); 1183 return Builder.CreateSelect(CondV, LHS, RHS, "cond"); 1184 } 1185 1186 1187 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true"); 1188 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false"); 1189 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end"); 1190 Value *CondVal = 0; 1191 1192 // If we have the GNU missing condition extension, evaluate the conditional 1193 // and then convert it to bool the hard way. We do this explicitly 1194 // because we need the unconverted value for the missing middle value of 1195 // the ?:. 1196 if (E->getLHS() == 0) { 1197 CondVal = CGF.EmitScalarExpr(E->getCond()); 1198 Value *CondBoolVal = 1199 CGF.EmitScalarConversion(CondVal, E->getCond()->getType(), 1200 CGF.getContext().BoolTy); 1201 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock); 1202 } else { 1203 // Otherwise, just use EmitBranchOnBoolExpr to get small and simple code for 1204 // the branch on bool. 1205 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock); 1206 } 1207 1208 CGF.EmitBlock(LHSBlock); 1209 1210 // Handle the GNU extension for missing LHS. 1211 Value *LHS; 1212 if (E->getLHS()) 1213 LHS = Visit(E->getLHS()); 1214 else // Perform promotions, to handle cases like "short ?: int" 1215 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType()); 1216 1217 LHSBlock = Builder.GetInsertBlock(); 1218 CGF.EmitBranch(ContBlock); 1219 1220 CGF.EmitBlock(RHSBlock); 1221 1222 Value *RHS = Visit(E->getRHS()); 1223 RHSBlock = Builder.GetInsertBlock(); 1224 CGF.EmitBranch(ContBlock); 1225 1226 CGF.EmitBlock(ContBlock); 1227 1228 if (!LHS || !RHS) { 1229 assert(E->getType()->isVoidType() && "Non-void value should have a value"); 1230 return 0; 1231 } 1232 1233 // Create a PHI node for the real part. 1234 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond"); 1235 PN->reserveOperandSpace(2); 1236 PN->addIncoming(LHS, LHSBlock); 1237 PN->addIncoming(RHS, RHSBlock); 1238 return PN; 1239} 1240 1241Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) { 1242 // Emit the LHS or RHS as appropriate. 1243 return 1244 Visit(E->isConditionTrue(CGF.getContext()) ? E->getLHS() : E->getRHS()); 1245} 1246 1247Value *ScalarExprEmitter::VisitOverloadExpr(OverloadExpr *E) { 1248 return CGF.EmitCallExpr(E->getFn(), E->arg_begin(), 1249 E->arg_end(CGF.getContext())).getScalarVal(); 1250} 1251 1252Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) { 1253 llvm::Value *ArgValue = EmitLValue(VE->getSubExpr()).getAddress(); 1254 1255 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType()); 1256 1257 // If EmitVAArg fails, we fall back to the LLVM instruction. 1258 if (!ArgPtr) 1259 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType())); 1260 1261 // FIXME: volatile? 1262 return Builder.CreateLoad(ArgPtr); 1263} 1264 1265Value *ScalarExprEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { 1266 std::string str; 1267 CGF.getContext().getObjCEncodingForType(E->getEncodedType(), str); 1268 1269 llvm::Constant *C = llvm::ConstantArray::get(str); 1270 C = new llvm::GlobalVariable(C->getType(), true, 1271 llvm::GlobalValue::InternalLinkage, 1272 C, ".str", &CGF.CGM.getModule()); 1273 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty); 1274 llvm::Constant *Zeros[] = { Zero, Zero }; 1275 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2); 1276 1277 return C; 1278} 1279 1280//===----------------------------------------------------------------------===// 1281// Entry Point into this File 1282//===----------------------------------------------------------------------===// 1283 1284/// EmitComplexExpr - Emit the computation of the specified expression of 1285/// complex type, ignoring the result. 1286Value *CodeGenFunction::EmitScalarExpr(const Expr *E) { 1287 assert(E && !hasAggregateLLVMType(E->getType()) && 1288 "Invalid scalar expression to emit"); 1289 1290 return ScalarExprEmitter(*this).Visit(const_cast<Expr*>(E)); 1291} 1292 1293/// EmitScalarConversion - Emit a conversion from the specified type to the 1294/// specified destination type, both of which are LLVM scalar types. 1295Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy, 1296 QualType DstTy) { 1297 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) && 1298 "Invalid scalar expression to emit"); 1299 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy); 1300} 1301 1302/// EmitComplexToScalarConversion - Emit a conversion from the specified 1303/// complex type to the specified destination type, where the destination 1304/// type is an LLVM scalar type. 1305Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src, 1306 QualType SrcTy, 1307 QualType DstTy) { 1308 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) && 1309 "Invalid complex -> scalar conversion"); 1310 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy, 1311 DstTy); 1312} 1313 1314Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) { 1315 assert(V1->getType() == V2->getType() && 1316 "Vector operands must be of the same type"); 1317 unsigned NumElements = 1318 cast<llvm::VectorType>(V1->getType())->getNumElements(); 1319 1320 va_list va; 1321 va_start(va, V2); 1322 1323 llvm::SmallVector<llvm::Constant*, 16> Args; 1324 for (unsigned i = 0; i < NumElements; i++) { 1325 int n = va_arg(va, int); 1326 assert(n >= 0 && n < (int)NumElements * 2 && 1327 "Vector shuffle index out of bounds!"); 1328 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, n)); 1329 } 1330 1331 const char *Name = va_arg(va, const char *); 1332 va_end(va); 1333 1334 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements); 1335 1336 return Builder.CreateShuffleVector(V1, V2, Mask, Name); 1337} 1338 1339llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals, 1340 unsigned NumVals, bool isSplat) { 1341 llvm::Value *Vec 1342 = llvm::UndefValue::get(llvm::VectorType::get(Vals[0]->getType(), NumVals)); 1343 1344 for (unsigned i = 0, e = NumVals; i != e; ++i) { 1345 llvm::Value *Val = isSplat ? Vals[0] : Vals[i]; 1346 llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i); 1347 Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp"); 1348 } 1349 1350 return Vec; 1351} 1352