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