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