1 //===--- CGExpr.cpp - Emit LLVM Code from Expressions ---------------------===// 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 as LLVM code. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CodeGenFunction.h" 15 #include "CGCXXABI.h" 16 #include "CGCall.h" 17 #include "CGDebugInfo.h" 18 #include "CGObjCRuntime.h" 19 #include "CGRecordLayout.h" 20 #include "CodeGenModule.h" 21 #include "TargetInfo.h" 22 #include "clang/AST/ASTContext.h" 23 #include "clang/AST/DeclObjC.h" 24 #include "clang/Frontend/CodeGenOptions.h" 25 #include "llvm/ADT/Hashing.h" 26 #include "llvm/IR/DataLayout.h" 27 #include "llvm/IR/Intrinsics.h" 28 #include "llvm/IR/LLVMContext.h" 29 #include "llvm/IR/MDBuilder.h" 30 #include "llvm/Support/ConvertUTF.h" 31 32 using namespace clang; 33 using namespace CodeGen; 34 35 //===--------------------------------------------------------------------===// 36 // Miscellaneous Helper Methods 37 //===--------------------------------------------------------------------===// 38 39 llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) { 40 unsigned addressSpace = 41 cast<llvm::PointerType>(value->getType())->getAddressSpace(); 42 43 llvm::PointerType *destType = Int8PtrTy; 44 if (addressSpace) 45 destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace); 46 47 if (value->getType() == destType) return value; 48 return Builder.CreateBitCast(value, destType); 49 } 50 51 /// CreateTempAlloca - This creates a alloca and inserts it into the entry 52 /// block. 53 llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty, 54 const Twine &Name) { 55 if (!Builder.isNamePreserving()) 56 return new llvm::AllocaInst(Ty, 0, "", AllocaInsertPt); 57 return new llvm::AllocaInst(Ty, 0, Name, AllocaInsertPt); 58 } 59 60 void CodeGenFunction::InitTempAlloca(llvm::AllocaInst *Var, 61 llvm::Value *Init) { 62 llvm::StoreInst *Store = new llvm::StoreInst(Init, Var); 63 llvm::BasicBlock *Block = AllocaInsertPt->getParent(); 64 Block->getInstList().insertAfter(&*AllocaInsertPt, Store); 65 } 66 67 llvm::AllocaInst *CodeGenFunction::CreateIRTemp(QualType Ty, 68 const Twine &Name) { 69 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertType(Ty), Name); 70 // FIXME: Should we prefer the preferred type alignment here? 71 CharUnits Align = getContext().getTypeAlignInChars(Ty); 72 Alloc->setAlignment(Align.getQuantity()); 73 return Alloc; 74 } 75 76 llvm::AllocaInst *CodeGenFunction::CreateMemTemp(QualType Ty, 77 const Twine &Name) { 78 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty), Name); 79 // FIXME: Should we prefer the preferred type alignment here? 80 CharUnits Align = getContext().getTypeAlignInChars(Ty); 81 Alloc->setAlignment(Align.getQuantity()); 82 return Alloc; 83 } 84 85 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified 86 /// expression and compare the result against zero, returning an Int1Ty value. 87 llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) { 88 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) { 89 llvm::Value *MemPtr = EmitScalarExpr(E); 90 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT); 91 } 92 93 QualType BoolTy = getContext().BoolTy; 94 if (!E->getType()->isAnyComplexType()) 95 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy); 96 97 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(),BoolTy); 98 } 99 100 /// EmitIgnoredExpr - Emit code to compute the specified expression, 101 /// ignoring the result. 102 void CodeGenFunction::EmitIgnoredExpr(const Expr *E) { 103 if (E->isRValue()) 104 return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true); 105 106 // Just emit it as an l-value and drop the result. 107 EmitLValue(E); 108 } 109 110 /// EmitAnyExpr - Emit code to compute the specified expression which 111 /// can have any type. The result is returned as an RValue struct. 112 /// If this is an aggregate expression, AggSlot indicates where the 113 /// result should be returned. 114 RValue CodeGenFunction::EmitAnyExpr(const Expr *E, 115 AggValueSlot aggSlot, 116 bool ignoreResult) { 117 if (!hasAggregateLLVMType(E->getType())) 118 return RValue::get(EmitScalarExpr(E, ignoreResult)); 119 else if (E->getType()->isAnyComplexType()) 120 return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult)); 121 122 if (!ignoreResult && aggSlot.isIgnored()) 123 aggSlot = CreateAggTemp(E->getType(), "agg-temp"); 124 EmitAggExpr(E, aggSlot); 125 return aggSlot.asRValue(); 126 } 127 128 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will 129 /// always be accessible even if no aggregate location is provided. 130 RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) { 131 AggValueSlot AggSlot = AggValueSlot::ignored(); 132 133 if (hasAggregateLLVMType(E->getType()) && 134 !E->getType()->isAnyComplexType()) 135 AggSlot = CreateAggTemp(E->getType(), "agg.tmp"); 136 return EmitAnyExpr(E, AggSlot); 137 } 138 139 /// EmitAnyExprToMem - Evaluate an expression into a given memory 140 /// location. 141 void CodeGenFunction::EmitAnyExprToMem(const Expr *E, 142 llvm::Value *Location, 143 Qualifiers Quals, 144 bool IsInit) { 145 // FIXME: This function should take an LValue as an argument. 146 if (E->getType()->isAnyComplexType()) { 147 EmitComplexExprIntoAddr(E, Location, Quals.hasVolatile()); 148 } else if (hasAggregateLLVMType(E->getType())) { 149 CharUnits Alignment = getContext().getTypeAlignInChars(E->getType()); 150 EmitAggExpr(E, AggValueSlot::forAddr(Location, Alignment, Quals, 151 AggValueSlot::IsDestructed_t(IsInit), 152 AggValueSlot::DoesNotNeedGCBarriers, 153 AggValueSlot::IsAliased_t(!IsInit))); 154 } else { 155 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false)); 156 LValue LV = MakeAddrLValue(Location, E->getType()); 157 EmitStoreThroughLValue(RV, LV); 158 } 159 } 160 161 static llvm::Value * 162 CreateReferenceTemporary(CodeGenFunction &CGF, QualType Type, 163 const NamedDecl *InitializedDecl) { 164 if (const VarDecl *VD = dyn_cast_or_null<VarDecl>(InitializedDecl)) { 165 if (VD->hasGlobalStorage()) { 166 SmallString<256> Name; 167 llvm::raw_svector_ostream Out(Name); 168 CGF.CGM.getCXXABI().getMangleContext().mangleReferenceTemporary(VD, Out); 169 Out.flush(); 170 171 llvm::Type *RefTempTy = CGF.ConvertTypeForMem(Type); 172 173 // Create the reference temporary. 174 llvm::GlobalValue *RefTemp = 175 new llvm::GlobalVariable(CGF.CGM.getModule(), 176 RefTempTy, /*isConstant=*/false, 177 llvm::GlobalValue::InternalLinkage, 178 llvm::Constant::getNullValue(RefTempTy), 179 Name.str()); 180 return RefTemp; 181 } 182 } 183 184 return CGF.CreateMemTemp(Type, "ref.tmp"); 185 } 186 187 static llvm::Value * 188 EmitExprForReferenceBinding(CodeGenFunction &CGF, const Expr *E, 189 llvm::Value *&ReferenceTemporary, 190 const CXXDestructorDecl *&ReferenceTemporaryDtor, 191 QualType &ObjCARCReferenceLifetimeType, 192 const NamedDecl *InitializedDecl) { 193 const MaterializeTemporaryExpr *M = NULL; 194 E = E->findMaterializedTemporary(M); 195 // Objective-C++ ARC: 196 // If we are binding a reference to a temporary that has ownership, we 197 // need to perform retain/release operations on the temporary. 198 if (M && CGF.getLangOpts().ObjCAutoRefCount && 199 M->getType()->isObjCLifetimeType() && 200 (M->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 201 M->getType().getObjCLifetime() == Qualifiers::OCL_Weak || 202 M->getType().getObjCLifetime() == Qualifiers::OCL_Autoreleasing)) 203 ObjCARCReferenceLifetimeType = M->getType(); 204 205 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(E)) { 206 CGF.enterFullExpression(EWC); 207 CodeGenFunction::RunCleanupsScope Scope(CGF); 208 209 return EmitExprForReferenceBinding(CGF, EWC->getSubExpr(), 210 ReferenceTemporary, 211 ReferenceTemporaryDtor, 212 ObjCARCReferenceLifetimeType, 213 InitializedDecl); 214 } 215 216 RValue RV; 217 if (E->isGLValue()) { 218 // Emit the expression as an lvalue. 219 LValue LV = CGF.EmitLValue(E); 220 221 if (LV.isSimple()) 222 return LV.getAddress(); 223 224 // We have to load the lvalue. 225 RV = CGF.EmitLoadOfLValue(LV); 226 } else { 227 if (!ObjCARCReferenceLifetimeType.isNull()) { 228 ReferenceTemporary = CreateReferenceTemporary(CGF, 229 ObjCARCReferenceLifetimeType, 230 InitializedDecl); 231 232 233 LValue RefTempDst = CGF.MakeAddrLValue(ReferenceTemporary, 234 ObjCARCReferenceLifetimeType); 235 236 CGF.EmitScalarInit(E, dyn_cast_or_null<ValueDecl>(InitializedDecl), 237 RefTempDst, false); 238 239 bool ExtendsLifeOfTemporary = false; 240 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(InitializedDecl)) { 241 if (Var->extendsLifetimeOfTemporary()) 242 ExtendsLifeOfTemporary = true; 243 } else if (InitializedDecl && isa<FieldDecl>(InitializedDecl)) { 244 ExtendsLifeOfTemporary = true; 245 } 246 247 if (!ExtendsLifeOfTemporary) { 248 // Since the lifetime of this temporary isn't going to be extended, 249 // we need to clean it up ourselves at the end of the full expression. 250 switch (ObjCARCReferenceLifetimeType.getObjCLifetime()) { 251 case Qualifiers::OCL_None: 252 case Qualifiers::OCL_ExplicitNone: 253 case Qualifiers::OCL_Autoreleasing: 254 break; 255 256 case Qualifiers::OCL_Strong: { 257 assert(!ObjCARCReferenceLifetimeType->isArrayType()); 258 CleanupKind cleanupKind = CGF.getARCCleanupKind(); 259 CGF.pushDestroy(cleanupKind, 260 ReferenceTemporary, 261 ObjCARCReferenceLifetimeType, 262 CodeGenFunction::destroyARCStrongImprecise, 263 cleanupKind & EHCleanup); 264 break; 265 } 266 267 case Qualifiers::OCL_Weak: 268 assert(!ObjCARCReferenceLifetimeType->isArrayType()); 269 CGF.pushDestroy(NormalAndEHCleanup, 270 ReferenceTemporary, 271 ObjCARCReferenceLifetimeType, 272 CodeGenFunction::destroyARCWeak, 273 /*useEHCleanupForArray*/ true); 274 break; 275 } 276 277 ObjCARCReferenceLifetimeType = QualType(); 278 } 279 280 return ReferenceTemporary; 281 } 282 283 SmallVector<SubobjectAdjustment, 2> Adjustments; 284 E = E->skipRValueSubobjectAdjustments(Adjustments); 285 if (const OpaqueValueExpr *opaque = dyn_cast<OpaqueValueExpr>(E)) 286 if (opaque->getType()->isRecordType()) 287 return CGF.EmitOpaqueValueLValue(opaque).getAddress(); 288 289 // Create a reference temporary if necessary. 290 AggValueSlot AggSlot = AggValueSlot::ignored(); 291 if (CGF.hasAggregateLLVMType(E->getType()) && 292 !E->getType()->isAnyComplexType()) { 293 ReferenceTemporary = CreateReferenceTemporary(CGF, E->getType(), 294 InitializedDecl); 295 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(E->getType()); 296 AggValueSlot::IsDestructed_t isDestructed 297 = AggValueSlot::IsDestructed_t(InitializedDecl != 0); 298 AggSlot = AggValueSlot::forAddr(ReferenceTemporary, Alignment, 299 Qualifiers(), isDestructed, 300 AggValueSlot::DoesNotNeedGCBarriers, 301 AggValueSlot::IsNotAliased); 302 } 303 304 if (InitializedDecl) { 305 // Get the destructor for the reference temporary. 306 if (const RecordType *RT = 307 E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) { 308 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 309 if (!ClassDecl->hasTrivialDestructor()) 310 ReferenceTemporaryDtor = ClassDecl->getDestructor(); 311 } 312 } 313 314 RV = CGF.EmitAnyExpr(E, AggSlot); 315 316 // Check if need to perform derived-to-base casts and/or field accesses, to 317 // get from the temporary object we created (and, potentially, for which we 318 // extended the lifetime) to the subobject we're binding the reference to. 319 if (!Adjustments.empty()) { 320 llvm::Value *Object = RV.getAggregateAddr(); 321 for (unsigned I = Adjustments.size(); I != 0; --I) { 322 SubobjectAdjustment &Adjustment = Adjustments[I-1]; 323 switch (Adjustment.Kind) { 324 case SubobjectAdjustment::DerivedToBaseAdjustment: 325 Object = 326 CGF.GetAddressOfBaseClass(Object, 327 Adjustment.DerivedToBase.DerivedClass, 328 Adjustment.DerivedToBase.BasePath->path_begin(), 329 Adjustment.DerivedToBase.BasePath->path_end(), 330 /*NullCheckValue=*/false); 331 break; 332 333 case SubobjectAdjustment::FieldAdjustment: { 334 LValue LV = CGF.MakeAddrLValue(Object, E->getType()); 335 LV = CGF.EmitLValueForField(LV, Adjustment.Field); 336 if (LV.isSimple()) { 337 Object = LV.getAddress(); 338 break; 339 } 340 341 // For non-simple lvalues, we actually have to create a copy of 342 // the object we're binding to. 343 QualType T = Adjustment.Field->getType().getNonReferenceType() 344 .getUnqualifiedType(); 345 Object = CreateReferenceTemporary(CGF, T, InitializedDecl); 346 LValue TempLV = CGF.MakeAddrLValue(Object, 347 Adjustment.Field->getType()); 348 CGF.EmitStoreThroughLValue(CGF.EmitLoadOfLValue(LV), TempLV); 349 break; 350 } 351 352 case SubobjectAdjustment::MemberPointerAdjustment: { 353 llvm::Value *Ptr = CGF.EmitScalarExpr(Adjustment.Ptr.RHS); 354 Object = CGF.CGM.getCXXABI().EmitMemberDataPointerAddress( 355 CGF, Object, Ptr, Adjustment.Ptr.MPT); 356 break; 357 } 358 } 359 } 360 361 return Object; 362 } 363 } 364 365 if (RV.isAggregate()) 366 return RV.getAggregateAddr(); 367 368 // Create a temporary variable that we can bind the reference to. 369 ReferenceTemporary = CreateReferenceTemporary(CGF, E->getType(), 370 InitializedDecl); 371 372 373 unsigned Alignment = 374 CGF.getContext().getTypeAlignInChars(E->getType()).getQuantity(); 375 if (RV.isScalar()) 376 CGF.EmitStoreOfScalar(RV.getScalarVal(), ReferenceTemporary, 377 /*Volatile=*/false, Alignment, E->getType()); 378 else 379 CGF.StoreComplexToAddr(RV.getComplexVal(), ReferenceTemporary, 380 /*Volatile=*/false); 381 return ReferenceTemporary; 382 } 383 384 RValue 385 CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E, 386 const NamedDecl *InitializedDecl) { 387 llvm::Value *ReferenceTemporary = 0; 388 const CXXDestructorDecl *ReferenceTemporaryDtor = 0; 389 QualType ObjCARCReferenceLifetimeType; 390 llvm::Value *Value = EmitExprForReferenceBinding(*this, E, ReferenceTemporary, 391 ReferenceTemporaryDtor, 392 ObjCARCReferenceLifetimeType, 393 InitializedDecl); 394 if (SanitizePerformTypeCheck && !E->getType()->isFunctionType()) { 395 // C++11 [dcl.ref]p5 (as amended by core issue 453): 396 // If a glvalue to which a reference is directly bound designates neither 397 // an existing object or function of an appropriate type nor a region of 398 // storage of suitable size and alignment to contain an object of the 399 // reference's type, the behavior is undefined. 400 QualType Ty = E->getType(); 401 EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty); 402 } 403 if (!ReferenceTemporaryDtor && ObjCARCReferenceLifetimeType.isNull()) 404 return RValue::get(Value); 405 406 // Make sure to call the destructor for the reference temporary. 407 const VarDecl *VD = dyn_cast_or_null<VarDecl>(InitializedDecl); 408 if (VD && VD->hasGlobalStorage()) { 409 if (ReferenceTemporaryDtor) { 410 llvm::Constant *CleanupFn; 411 llvm::Constant *CleanupArg; 412 if (E->getType()->isArrayType()) { 413 CleanupFn = CodeGenFunction(CGM).generateDestroyHelper( 414 cast<llvm::Constant>(ReferenceTemporary), E->getType(), 415 destroyCXXObject, getLangOpts().Exceptions); 416 CleanupArg = llvm::Constant::getNullValue(Int8PtrTy); 417 } else { 418 CleanupFn = 419 CGM.GetAddrOfCXXDestructor(ReferenceTemporaryDtor, Dtor_Complete); 420 CleanupArg = cast<llvm::Constant>(ReferenceTemporary); 421 } 422 CGM.getCXXABI().registerGlobalDtor(*this, CleanupFn, CleanupArg); 423 } else { 424 assert(!ObjCARCReferenceLifetimeType.isNull()); 425 // Note: We intentionally do not register a global "destructor" to 426 // release the object. 427 } 428 429 return RValue::get(Value); 430 } 431 432 if (ReferenceTemporaryDtor) { 433 if (E->getType()->isArrayType()) 434 pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(), 435 destroyCXXObject, getLangOpts().Exceptions); 436 else 437 PushDestructorCleanup(ReferenceTemporaryDtor, ReferenceTemporary); 438 } else { 439 switch (ObjCARCReferenceLifetimeType.getObjCLifetime()) { 440 case Qualifiers::OCL_None: 441 llvm_unreachable( 442 "Not a reference temporary that needs to be deallocated"); 443 case Qualifiers::OCL_ExplicitNone: 444 case Qualifiers::OCL_Autoreleasing: 445 // Nothing to do. 446 break; 447 448 case Qualifiers::OCL_Strong: { 449 bool precise = VD && VD->hasAttr<ObjCPreciseLifetimeAttr>(); 450 CleanupKind cleanupKind = getARCCleanupKind(); 451 pushDestroy(cleanupKind, ReferenceTemporary, ObjCARCReferenceLifetimeType, 452 precise ? destroyARCStrongPrecise : destroyARCStrongImprecise, 453 cleanupKind & EHCleanup); 454 break; 455 } 456 457 case Qualifiers::OCL_Weak: { 458 // __weak objects always get EH cleanups; otherwise, exceptions 459 // could cause really nasty crashes instead of mere leaks. 460 pushDestroy(NormalAndEHCleanup, ReferenceTemporary, 461 ObjCARCReferenceLifetimeType, destroyARCWeak, true); 462 break; 463 } 464 } 465 } 466 467 return RValue::get(Value); 468 } 469 470 471 /// getAccessedFieldNo - Given an encoded value and a result number, return the 472 /// input field number being accessed. 473 unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx, 474 const llvm::Constant *Elts) { 475 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx)) 476 ->getZExtValue(); 477 } 478 479 /// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h. 480 static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low, 481 llvm::Value *High) { 482 llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL); 483 llvm::Value *K47 = Builder.getInt64(47); 484 llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul); 485 llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0); 486 llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul); 487 llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0); 488 return Builder.CreateMul(B1, KMul); 489 } 490 491 void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, 492 llvm::Value *Address, 493 QualType Ty, CharUnits Alignment) { 494 if (!SanitizePerformTypeCheck) 495 return; 496 497 // Don't check pointers outside the default address space. The null check 498 // isn't correct, the object-size check isn't supported by LLVM, and we can't 499 // communicate the addresses to the runtime handler for the vptr check. 500 if (Address->getType()->getPointerAddressSpace()) 501 return; 502 503 llvm::Value *Cond = 0; 504 505 if (SanOpts->Null) { 506 // The glvalue must not be an empty glvalue. 507 Cond = Builder.CreateICmpNE( 508 Address, llvm::Constant::getNullValue(Address->getType())); 509 } 510 511 if (SanOpts->ObjectSize && !Ty->isIncompleteType()) { 512 uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity(); 513 514 // The glvalue must refer to a large enough storage region. 515 // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation 516 // to check this. 517 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, IntPtrTy); 518 llvm::Value *Min = Builder.getFalse(); 519 llvm::Value *CastAddr = Builder.CreateBitCast(Address, Int8PtrTy); 520 llvm::Value *LargeEnough = 521 Builder.CreateICmpUGE(Builder.CreateCall2(F, CastAddr, Min), 522 llvm::ConstantInt::get(IntPtrTy, Size)); 523 Cond = Cond ? Builder.CreateAnd(Cond, LargeEnough) : LargeEnough; 524 } 525 526 uint64_t AlignVal = 0; 527 528 if (SanOpts->Alignment) { 529 AlignVal = Alignment.getQuantity(); 530 if (!Ty->isIncompleteType() && !AlignVal) 531 AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity(); 532 533 // The glvalue must be suitably aligned. 534 if (AlignVal) { 535 llvm::Value *Align = 536 Builder.CreateAnd(Builder.CreatePtrToInt(Address, IntPtrTy), 537 llvm::ConstantInt::get(IntPtrTy, AlignVal - 1)); 538 llvm::Value *Aligned = 539 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0)); 540 Cond = Cond ? Builder.CreateAnd(Cond, Aligned) : Aligned; 541 } 542 } 543 544 if (Cond) { 545 llvm::Constant *StaticData[] = { 546 EmitCheckSourceLocation(Loc), 547 EmitCheckTypeDescriptor(Ty), 548 llvm::ConstantInt::get(SizeTy, AlignVal), 549 llvm::ConstantInt::get(Int8Ty, TCK) 550 }; 551 EmitCheck(Cond, "type_mismatch", StaticData, Address, CRK_Recoverable); 552 } 553 554 // If possible, check that the vptr indicates that there is a subobject of 555 // type Ty at offset zero within this object. 556 // 557 // C++11 [basic.life]p5,6: 558 // [For storage which does not refer to an object within its lifetime] 559 // The program has undefined behavior if: 560 // -- the [pointer or glvalue] is used to access a non-static data member 561 // or call a non-static member function 562 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 563 if (SanOpts->Vptr && 564 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall) && 565 RD && RD->hasDefinition() && RD->isDynamicClass()) { 566 // Compute a hash of the mangled name of the type. 567 // 568 // FIXME: This is not guaranteed to be deterministic! Move to a 569 // fingerprinting mechanism once LLVM provides one. For the time 570 // being the implementation happens to be deterministic. 571 SmallString<64> MangledName; 572 llvm::raw_svector_ostream Out(MangledName); 573 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(), 574 Out); 575 llvm::hash_code TypeHash = hash_value(Out.str()); 576 577 // Load the vptr, and compute hash_16_bytes(TypeHash, vptr). 578 llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash); 579 llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0); 580 llvm::Value *VPtrAddr = Builder.CreateBitCast(Address, VPtrTy); 581 llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr); 582 llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty); 583 584 llvm::Value *Hash = emitHash16Bytes(Builder, Low, High); 585 Hash = Builder.CreateTrunc(Hash, IntPtrTy); 586 587 // Look the hash up in our cache. 588 const int CacheSize = 128; 589 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize); 590 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable, 591 "__ubsan_vptr_type_cache"); 592 llvm::Value *Slot = Builder.CreateAnd(Hash, 593 llvm::ConstantInt::get(IntPtrTy, 594 CacheSize-1)); 595 llvm::Value *Indices[] = { Builder.getInt32(0), Slot }; 596 llvm::Value *CacheVal = 597 Builder.CreateLoad(Builder.CreateInBoundsGEP(Cache, Indices)); 598 599 // If the hash isn't in the cache, call a runtime handler to perform the 600 // hard work of checking whether the vptr is for an object of the right 601 // type. This will either fill in the cache and return, or produce a 602 // diagnostic. 603 llvm::Constant *StaticData[] = { 604 EmitCheckSourceLocation(Loc), 605 EmitCheckTypeDescriptor(Ty), 606 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()), 607 llvm::ConstantInt::get(Int8Ty, TCK) 608 }; 609 llvm::Value *DynamicData[] = { Address, Hash }; 610 EmitCheck(Builder.CreateICmpEQ(CacheVal, Hash), 611 "dynamic_type_cache_miss", StaticData, DynamicData, 612 CRK_AlwaysRecoverable); 613 } 614 } 615 616 617 CodeGenFunction::ComplexPairTy CodeGenFunction:: 618 EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV, 619 bool isInc, bool isPre) { 620 ComplexPairTy InVal = LoadComplexFromAddr(LV.getAddress(), 621 LV.isVolatileQualified()); 622 623 llvm::Value *NextVal; 624 if (isa<llvm::IntegerType>(InVal.first->getType())) { 625 uint64_t AmountVal = isInc ? 1 : -1; 626 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true); 627 628 // Add the inc/dec to the real part. 629 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec"); 630 } else { 631 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType(); 632 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1); 633 if (!isInc) 634 FVal.changeSign(); 635 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal); 636 637 // Add the inc/dec to the real part. 638 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec"); 639 } 640 641 ComplexPairTy IncVal(NextVal, InVal.second); 642 643 // Store the updated result through the lvalue. 644 StoreComplexToAddr(IncVal, LV.getAddress(), LV.isVolatileQualified()); 645 646 // If this is a postinc, return the value read from memory, otherwise use the 647 // updated value. 648 return isPre ? IncVal : InVal; 649 } 650 651 652 //===----------------------------------------------------------------------===// 653 // LValue Expression Emission 654 //===----------------------------------------------------------------------===// 655 656 RValue CodeGenFunction::GetUndefRValue(QualType Ty) { 657 if (Ty->isVoidType()) 658 return RValue::get(0); 659 660 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) { 661 llvm::Type *EltTy = ConvertType(CTy->getElementType()); 662 llvm::Value *U = llvm::UndefValue::get(EltTy); 663 return RValue::getComplex(std::make_pair(U, U)); 664 } 665 666 // If this is a use of an undefined aggregate type, the aggregate must have an 667 // identifiable address. Just because the contents of the value are undefined 668 // doesn't mean that the address can't be taken and compared. 669 if (hasAggregateLLVMType(Ty)) { 670 llvm::Value *DestPtr = CreateMemTemp(Ty, "undef.agg.tmp"); 671 return RValue::getAggregate(DestPtr); 672 } 673 674 return RValue::get(llvm::UndefValue::get(ConvertType(Ty))); 675 } 676 677 RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E, 678 const char *Name) { 679 ErrorUnsupported(E, Name); 680 return GetUndefRValue(E->getType()); 681 } 682 683 LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E, 684 const char *Name) { 685 ErrorUnsupported(E, Name); 686 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType())); 687 return MakeAddrLValue(llvm::UndefValue::get(Ty), E->getType()); 688 } 689 690 LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) { 691 LValue LV = EmitLValue(E); 692 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple()) 693 EmitTypeCheck(TCK, E->getExprLoc(), LV.getAddress(), 694 E->getType(), LV.getAlignment()); 695 return LV; 696 } 697 698 /// EmitLValue - Emit code to compute a designator that specifies the location 699 /// of the expression. 700 /// 701 /// This can return one of two things: a simple address or a bitfield reference. 702 /// In either case, the LLVM Value* in the LValue structure is guaranteed to be 703 /// an LLVM pointer type. 704 /// 705 /// If this returns a bitfield reference, nothing about the pointee type of the 706 /// LLVM value is known: For example, it may not be a pointer to an integer. 707 /// 708 /// If this returns a normal address, and if the lvalue's C type is fixed size, 709 /// this method guarantees that the returned pointer type will point to an LLVM 710 /// type of the same size of the lvalue's type. If the lvalue has a variable 711 /// length type, this is not possible. 712 /// 713 LValue CodeGenFunction::EmitLValue(const Expr *E) { 714 switch (E->getStmtClass()) { 715 default: return EmitUnsupportedLValue(E, "l-value expression"); 716 717 case Expr::ObjCPropertyRefExprClass: 718 llvm_unreachable("cannot emit a property reference directly"); 719 720 case Expr::ObjCSelectorExprClass: 721 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E)); 722 case Expr::ObjCIsaExprClass: 723 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E)); 724 case Expr::BinaryOperatorClass: 725 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E)); 726 case Expr::CompoundAssignOperatorClass: 727 if (!E->getType()->isAnyComplexType()) 728 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E)); 729 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E)); 730 case Expr::CallExprClass: 731 case Expr::CXXMemberCallExprClass: 732 case Expr::CXXOperatorCallExprClass: 733 case Expr::UserDefinedLiteralClass: 734 return EmitCallExprLValue(cast<CallExpr>(E)); 735 case Expr::VAArgExprClass: 736 return EmitVAArgExprLValue(cast<VAArgExpr>(E)); 737 case Expr::DeclRefExprClass: 738 return EmitDeclRefLValue(cast<DeclRefExpr>(E)); 739 case Expr::ParenExprClass: 740 return EmitLValue(cast<ParenExpr>(E)->getSubExpr()); 741 case Expr::GenericSelectionExprClass: 742 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr()); 743 case Expr::PredefinedExprClass: 744 return EmitPredefinedLValue(cast<PredefinedExpr>(E)); 745 case Expr::StringLiteralClass: 746 return EmitStringLiteralLValue(cast<StringLiteral>(E)); 747 case Expr::ObjCEncodeExprClass: 748 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E)); 749 case Expr::PseudoObjectExprClass: 750 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E)); 751 case Expr::InitListExprClass: 752 return EmitInitListLValue(cast<InitListExpr>(E)); 753 case Expr::CXXTemporaryObjectExprClass: 754 case Expr::CXXConstructExprClass: 755 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E)); 756 case Expr::CXXBindTemporaryExprClass: 757 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E)); 758 case Expr::CXXUuidofExprClass: 759 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E)); 760 case Expr::LambdaExprClass: 761 return EmitLambdaLValue(cast<LambdaExpr>(E)); 762 763 case Expr::ExprWithCleanupsClass: { 764 const ExprWithCleanups *cleanups = cast<ExprWithCleanups>(E); 765 enterFullExpression(cleanups); 766 RunCleanupsScope Scope(*this); 767 return EmitLValue(cleanups->getSubExpr()); 768 } 769 770 case Expr::CXXScalarValueInitExprClass: 771 return EmitNullInitializationLValue(cast<CXXScalarValueInitExpr>(E)); 772 case Expr::CXXDefaultArgExprClass: 773 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr()); 774 case Expr::CXXTypeidExprClass: 775 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E)); 776 777 case Expr::ObjCMessageExprClass: 778 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E)); 779 case Expr::ObjCIvarRefExprClass: 780 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E)); 781 case Expr::StmtExprClass: 782 return EmitStmtExprLValue(cast<StmtExpr>(E)); 783 case Expr::UnaryOperatorClass: 784 return EmitUnaryOpLValue(cast<UnaryOperator>(E)); 785 case Expr::ArraySubscriptExprClass: 786 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E)); 787 case Expr::ExtVectorElementExprClass: 788 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E)); 789 case Expr::MemberExprClass: 790 return EmitMemberExpr(cast<MemberExpr>(E)); 791 case Expr::CompoundLiteralExprClass: 792 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E)); 793 case Expr::ConditionalOperatorClass: 794 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E)); 795 case Expr::BinaryConditionalOperatorClass: 796 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E)); 797 case Expr::ChooseExprClass: 798 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr(getContext())); 799 case Expr::OpaqueValueExprClass: 800 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E)); 801 case Expr::SubstNonTypeTemplateParmExprClass: 802 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement()); 803 case Expr::ImplicitCastExprClass: 804 case Expr::CStyleCastExprClass: 805 case Expr::CXXFunctionalCastExprClass: 806 case Expr::CXXStaticCastExprClass: 807 case Expr::CXXDynamicCastExprClass: 808 case Expr::CXXReinterpretCastExprClass: 809 case Expr::CXXConstCastExprClass: 810 case Expr::ObjCBridgedCastExprClass: 811 return EmitCastLValue(cast<CastExpr>(E)); 812 813 case Expr::MaterializeTemporaryExprClass: 814 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E)); 815 } 816 } 817 818 /// Given an object of the given canonical type, can we safely copy a 819 /// value out of it based on its initializer? 820 static bool isConstantEmittableObjectType(QualType type) { 821 assert(type.isCanonical()); 822 assert(!type->isReferenceType()); 823 824 // Must be const-qualified but non-volatile. 825 Qualifiers qs = type.getLocalQualifiers(); 826 if (!qs.hasConst() || qs.hasVolatile()) return false; 827 828 // Otherwise, all object types satisfy this except C++ classes with 829 // mutable subobjects or non-trivial copy/destroy behavior. 830 if (const RecordType *RT = dyn_cast<RecordType>(type)) 831 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) 832 if (RD->hasMutableFields() || !RD->isTrivial()) 833 return false; 834 835 return true; 836 } 837 838 /// Can we constant-emit a load of a reference to a variable of the 839 /// given type? This is different from predicates like 840 /// Decl::isUsableInConstantExpressions because we do want it to apply 841 /// in situations that don't necessarily satisfy the language's rules 842 /// for this (e.g. C++'s ODR-use rules). For example, we want to able 843 /// to do this with const float variables even if those variables 844 /// aren't marked 'constexpr'. 845 enum ConstantEmissionKind { 846 CEK_None, 847 CEK_AsReferenceOnly, 848 CEK_AsValueOrReference, 849 CEK_AsValueOnly 850 }; 851 static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) { 852 type = type.getCanonicalType(); 853 if (const ReferenceType *ref = dyn_cast<ReferenceType>(type)) { 854 if (isConstantEmittableObjectType(ref->getPointeeType())) 855 return CEK_AsValueOrReference; 856 return CEK_AsReferenceOnly; 857 } 858 if (isConstantEmittableObjectType(type)) 859 return CEK_AsValueOnly; 860 return CEK_None; 861 } 862 863 /// Try to emit a reference to the given value without producing it as 864 /// an l-value. This is actually more than an optimization: we can't 865 /// produce an l-value for variables that we never actually captured 866 /// in a block or lambda, which means const int variables or constexpr 867 /// literals or similar. 868 CodeGenFunction::ConstantEmission 869 CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) { 870 ValueDecl *value = refExpr->getDecl(); 871 872 // The value needs to be an enum constant or a constant variable. 873 ConstantEmissionKind CEK; 874 if (isa<ParmVarDecl>(value)) { 875 CEK = CEK_None; 876 } else if (VarDecl *var = dyn_cast<VarDecl>(value)) { 877 CEK = checkVarTypeForConstantEmission(var->getType()); 878 } else if (isa<EnumConstantDecl>(value)) { 879 CEK = CEK_AsValueOnly; 880 } else { 881 CEK = CEK_None; 882 } 883 if (CEK == CEK_None) return ConstantEmission(); 884 885 Expr::EvalResult result; 886 bool resultIsReference; 887 QualType resultType; 888 889 // It's best to evaluate all the way as an r-value if that's permitted. 890 if (CEK != CEK_AsReferenceOnly && 891 refExpr->EvaluateAsRValue(result, getContext())) { 892 resultIsReference = false; 893 resultType = refExpr->getType(); 894 895 // Otherwise, try to evaluate as an l-value. 896 } else if (CEK != CEK_AsValueOnly && 897 refExpr->EvaluateAsLValue(result, getContext())) { 898 resultIsReference = true; 899 resultType = value->getType(); 900 901 // Failure. 902 } else { 903 return ConstantEmission(); 904 } 905 906 // In any case, if the initializer has side-effects, abandon ship. 907 if (result.HasSideEffects) 908 return ConstantEmission(); 909 910 // Emit as a constant. 911 llvm::Constant *C = CGM.EmitConstantValue(result.Val, resultType, this); 912 913 // Make sure we emit a debug reference to the global variable. 914 // This should probably fire even for 915 if (isa<VarDecl>(value)) { 916 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value))) 917 EmitDeclRefExprDbgValue(refExpr, C); 918 } else { 919 assert(isa<EnumConstantDecl>(value)); 920 EmitDeclRefExprDbgValue(refExpr, C); 921 } 922 923 // If we emitted a reference constant, we need to dereference that. 924 if (resultIsReference) 925 return ConstantEmission::forReference(C); 926 927 return ConstantEmission::forValue(C); 928 } 929 930 llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue) { 931 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(), 932 lvalue.getAlignment().getQuantity(), 933 lvalue.getType(), lvalue.getTBAAInfo()); 934 } 935 936 static bool hasBooleanRepresentation(QualType Ty) { 937 if (Ty->isBooleanType()) 938 return true; 939 940 if (const EnumType *ET = Ty->getAs<EnumType>()) 941 return ET->getDecl()->getIntegerType()->isBooleanType(); 942 943 if (const AtomicType *AT = Ty->getAs<AtomicType>()) 944 return hasBooleanRepresentation(AT->getValueType()); 945 946 return false; 947 } 948 949 static bool getRangeForType(CodeGenFunction &CGF, QualType Ty, 950 llvm::APInt &Min, llvm::APInt &End, 951 bool StrictEnums) { 952 const EnumType *ET = Ty->getAs<EnumType>(); 953 bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums && 954 ET && !ET->getDecl()->isFixed(); 955 bool IsBool = hasBooleanRepresentation(Ty); 956 if (!IsBool && !IsRegularCPlusPlusEnum) 957 return false; 958 959 if (IsBool) { 960 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0); 961 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2); 962 } else { 963 const EnumDecl *ED = ET->getDecl(); 964 llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType()); 965 unsigned Bitwidth = LTy->getScalarSizeInBits(); 966 unsigned NumNegativeBits = ED->getNumNegativeBits(); 967 unsigned NumPositiveBits = ED->getNumPositiveBits(); 968 969 if (NumNegativeBits) { 970 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1); 971 assert(NumBits <= Bitwidth); 972 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1); 973 Min = -End; 974 } else { 975 assert(NumPositiveBits <= Bitwidth); 976 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits; 977 Min = llvm::APInt(Bitwidth, 0); 978 } 979 } 980 return true; 981 } 982 983 llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) { 984 llvm::APInt Min, End; 985 if (!getRangeForType(*this, Ty, Min, End, 986 CGM.getCodeGenOpts().StrictEnums)) 987 return 0; 988 989 llvm::MDBuilder MDHelper(getLLVMContext()); 990 return MDHelper.createRange(Min, End); 991 } 992 993 llvm::Value *CodeGenFunction::EmitLoadOfScalar(llvm::Value *Addr, bool Volatile, 994 unsigned Alignment, QualType Ty, 995 llvm::MDNode *TBAAInfo) { 996 997 // For better performance, handle vector loads differently. 998 if (Ty->isVectorType()) { 999 llvm::Value *V; 1000 const llvm::Type *EltTy = 1001 cast<llvm::PointerType>(Addr->getType())->getElementType(); 1002 1003 const llvm::VectorType *VTy = cast<llvm::VectorType>(EltTy); 1004 1005 // Handle vectors of size 3, like size 4 for better performance. 1006 if (VTy->getNumElements() == 3) { 1007 1008 // Bitcast to vec4 type. 1009 llvm::VectorType *vec4Ty = llvm::VectorType::get(VTy->getElementType(), 1010 4); 1011 llvm::PointerType *ptVec4Ty = 1012 llvm::PointerType::get(vec4Ty, 1013 (cast<llvm::PointerType>( 1014 Addr->getType()))->getAddressSpace()); 1015 llvm::Value *Cast = Builder.CreateBitCast(Addr, ptVec4Ty, 1016 "castToVec4"); 1017 // Now load value. 1018 llvm::Value *LoadVal = Builder.CreateLoad(Cast, Volatile, "loadVec4"); 1019 1020 // Shuffle vector to get vec3. 1021 llvm::Constant *Mask[] = { 1022 llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 0), 1023 llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 1), 1024 llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 2) 1025 }; 1026 1027 llvm::Value *MaskV = llvm::ConstantVector::get(Mask); 1028 V = Builder.CreateShuffleVector(LoadVal, 1029 llvm::UndefValue::get(vec4Ty), 1030 MaskV, "extractVec"); 1031 return EmitFromMemory(V, Ty); 1032 } 1033 } 1034 1035 llvm::LoadInst *Load = Builder.CreateLoad(Addr); 1036 if (Volatile) 1037 Load->setVolatile(true); 1038 if (Alignment) 1039 Load->setAlignment(Alignment); 1040 if (TBAAInfo) 1041 CGM.DecorateInstruction(Load, TBAAInfo); 1042 // If this is an atomic type, all normal reads must be atomic 1043 if (Ty->isAtomicType()) 1044 Load->setAtomic(llvm::SequentiallyConsistent); 1045 1046 if ((SanOpts->Bool && hasBooleanRepresentation(Ty)) || 1047 (SanOpts->Enum && Ty->getAs<EnumType>())) { 1048 llvm::APInt Min, End; 1049 if (getRangeForType(*this, Ty, Min, End, true)) { 1050 --End; 1051 llvm::Value *Check; 1052 if (!Min) 1053 Check = Builder.CreateICmpULE( 1054 Load, llvm::ConstantInt::get(getLLVMContext(), End)); 1055 else { 1056 llvm::Value *Upper = Builder.CreateICmpSLE( 1057 Load, llvm::ConstantInt::get(getLLVMContext(), End)); 1058 llvm::Value *Lower = Builder.CreateICmpSGE( 1059 Load, llvm::ConstantInt::get(getLLVMContext(), Min)); 1060 Check = Builder.CreateAnd(Upper, Lower); 1061 } 1062 // FIXME: Provide a SourceLocation. 1063 EmitCheck(Check, "load_invalid_value", EmitCheckTypeDescriptor(Ty), 1064 EmitCheckValue(Load), CRK_Recoverable); 1065 } 1066 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0) 1067 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty)) 1068 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo); 1069 1070 return EmitFromMemory(Load, Ty); 1071 } 1072 1073 llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) { 1074 // Bool has a different representation in memory than in registers. 1075 if (hasBooleanRepresentation(Ty)) { 1076 // This should really always be an i1, but sometimes it's already 1077 // an i8, and it's awkward to track those cases down. 1078 if (Value->getType()->isIntegerTy(1)) 1079 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool"); 1080 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) && 1081 "wrong value rep of bool"); 1082 } 1083 1084 return Value; 1085 } 1086 1087 llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) { 1088 // Bool has a different representation in memory than in registers. 1089 if (hasBooleanRepresentation(Ty)) { 1090 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) && 1091 "wrong value rep of bool"); 1092 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool"); 1093 } 1094 1095 return Value; 1096 } 1097 1098 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr, 1099 bool Volatile, unsigned Alignment, 1100 QualType Ty, 1101 llvm::MDNode *TBAAInfo, 1102 bool isInit) { 1103 1104 // Handle vectors differently to get better performance. 1105 if (Ty->isVectorType()) { 1106 llvm::Type *SrcTy = Value->getType(); 1107 llvm::VectorType *VecTy = cast<llvm::VectorType>(SrcTy); 1108 // Handle vec3 special. 1109 if (VecTy->getNumElements() == 3) { 1110 llvm::LLVMContext &VMContext = getLLVMContext(); 1111 1112 // Our source is a vec3, do a shuffle vector to make it a vec4. 1113 SmallVector<llvm::Constant*, 4> Mask; 1114 Mask.push_back(llvm::ConstantInt::get( 1115 llvm::Type::getInt32Ty(VMContext), 1116 0)); 1117 Mask.push_back(llvm::ConstantInt::get( 1118 llvm::Type::getInt32Ty(VMContext), 1119 1)); 1120 Mask.push_back(llvm::ConstantInt::get( 1121 llvm::Type::getInt32Ty(VMContext), 1122 2)); 1123 Mask.push_back(llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext))); 1124 1125 llvm::Value *MaskV = llvm::ConstantVector::get(Mask); 1126 Value = Builder.CreateShuffleVector(Value, 1127 llvm::UndefValue::get(VecTy), 1128 MaskV, "extractVec"); 1129 SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4); 1130 } 1131 llvm::PointerType *DstPtr = cast<llvm::PointerType>(Addr->getType()); 1132 if (DstPtr->getElementType() != SrcTy) { 1133 llvm::Type *MemTy = 1134 llvm::PointerType::get(SrcTy, DstPtr->getAddressSpace()); 1135 Addr = Builder.CreateBitCast(Addr, MemTy, "storetmp"); 1136 } 1137 } 1138 1139 Value = EmitToMemory(Value, Ty); 1140 1141 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile); 1142 if (Alignment) 1143 Store->setAlignment(Alignment); 1144 if (TBAAInfo) 1145 CGM.DecorateInstruction(Store, TBAAInfo); 1146 if (!isInit && Ty->isAtomicType()) 1147 Store->setAtomic(llvm::SequentiallyConsistent); 1148 } 1149 1150 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue, 1151 bool isInit) { 1152 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(), 1153 lvalue.getAlignment().getQuantity(), lvalue.getType(), 1154 lvalue.getTBAAInfo(), isInit); 1155 } 1156 1157 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this 1158 /// method emits the address of the lvalue, then loads the result as an rvalue, 1159 /// returning the rvalue. 1160 RValue CodeGenFunction::EmitLoadOfLValue(LValue LV) { 1161 if (LV.isObjCWeak()) { 1162 // load of a __weak object. 1163 llvm::Value *AddrWeakObj = LV.getAddress(); 1164 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this, 1165 AddrWeakObj)); 1166 } 1167 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) { 1168 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress()); 1169 Object = EmitObjCConsumeObject(LV.getType(), Object); 1170 return RValue::get(Object); 1171 } 1172 1173 if (LV.isSimple()) { 1174 assert(!LV.getType()->isFunctionType()); 1175 1176 // Everything needs a load. 1177 return RValue::get(EmitLoadOfScalar(LV)); 1178 } 1179 1180 if (LV.isVectorElt()) { 1181 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddr(), 1182 LV.isVolatileQualified()); 1183 Load->setAlignment(LV.getAlignment().getQuantity()); 1184 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(), 1185 "vecext")); 1186 } 1187 1188 // If this is a reference to a subset of the elements of a vector, either 1189 // shuffle the input or extract/insert them as appropriate. 1190 if (LV.isExtVectorElt()) 1191 return EmitLoadOfExtVectorElementLValue(LV); 1192 1193 assert(LV.isBitField() && "Unknown LValue type!"); 1194 return EmitLoadOfBitfieldLValue(LV); 1195 } 1196 1197 RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV) { 1198 const CGBitFieldInfo &Info = LV.getBitFieldInfo(); 1199 1200 // Get the output type. 1201 llvm::Type *ResLTy = ConvertType(LV.getType()); 1202 1203 llvm::Value *Ptr = LV.getBitFieldAddr(); 1204 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), 1205 "bf.load"); 1206 cast<llvm::LoadInst>(Val)->setAlignment(Info.StorageAlignment); 1207 1208 if (Info.IsSigned) { 1209 assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize); 1210 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size; 1211 if (HighBits) 1212 Val = Builder.CreateShl(Val, HighBits, "bf.shl"); 1213 if (Info.Offset + HighBits) 1214 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr"); 1215 } else { 1216 if (Info.Offset) 1217 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr"); 1218 if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize) 1219 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize, 1220 Info.Size), 1221 "bf.clear"); 1222 } 1223 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast"); 1224 1225 return RValue::get(Val); 1226 } 1227 1228 // If this is a reference to a subset of the elements of a vector, create an 1229 // appropriate shufflevector. 1230 RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) { 1231 llvm::LoadInst *Load = Builder.CreateLoad(LV.getExtVectorAddr(), 1232 LV.isVolatileQualified()); 1233 Load->setAlignment(LV.getAlignment().getQuantity()); 1234 llvm::Value *Vec = Load; 1235 1236 const llvm::Constant *Elts = LV.getExtVectorElts(); 1237 1238 // If the result of the expression is a non-vector type, we must be extracting 1239 // a single element. Just codegen as an extractelement. 1240 const VectorType *ExprVT = LV.getType()->getAs<VectorType>(); 1241 if (!ExprVT) { 1242 unsigned InIdx = getAccessedFieldNo(0, Elts); 1243 llvm::Value *Elt = llvm::ConstantInt::get(Int32Ty, InIdx); 1244 return RValue::get(Builder.CreateExtractElement(Vec, Elt)); 1245 } 1246 1247 // Always use shuffle vector to try to retain the original program structure 1248 unsigned NumResultElts = ExprVT->getNumElements(); 1249 1250 SmallVector<llvm::Constant*, 4> Mask; 1251 for (unsigned i = 0; i != NumResultElts; ++i) 1252 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts))); 1253 1254 llvm::Value *MaskV = llvm::ConstantVector::get(Mask); 1255 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()), 1256 MaskV); 1257 return RValue::get(Vec); 1258 } 1259 1260 1261 1262 /// EmitStoreThroughLValue - Store the specified rvalue into the specified 1263 /// lvalue, where both are guaranteed to the have the same type, and that type 1264 /// is 'Ty'. 1265 void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit) { 1266 if (!Dst.isSimple()) { 1267 if (Dst.isVectorElt()) { 1268 // Read/modify/write the vector, inserting the new element. 1269 llvm::LoadInst *Load = Builder.CreateLoad(Dst.getVectorAddr(), 1270 Dst.isVolatileQualified()); 1271 Load->setAlignment(Dst.getAlignment().getQuantity()); 1272 llvm::Value *Vec = Load; 1273 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(), 1274 Dst.getVectorIdx(), "vecins"); 1275 llvm::StoreInst *Store = Builder.CreateStore(Vec, Dst.getVectorAddr(), 1276 Dst.isVolatileQualified()); 1277 Store->setAlignment(Dst.getAlignment().getQuantity()); 1278 return; 1279 } 1280 1281 // If this is an update of extended vector elements, insert them as 1282 // appropriate. 1283 if (Dst.isExtVectorElt()) 1284 return EmitStoreThroughExtVectorComponentLValue(Src, Dst); 1285 1286 assert(Dst.isBitField() && "Unknown LValue type"); 1287 return EmitStoreThroughBitfieldLValue(Src, Dst); 1288 } 1289 1290 // There's special magic for assigning into an ARC-qualified l-value. 1291 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) { 1292 switch (Lifetime) { 1293 case Qualifiers::OCL_None: 1294 llvm_unreachable("present but none"); 1295 1296 case Qualifiers::OCL_ExplicitNone: 1297 // nothing special 1298 break; 1299 1300 case Qualifiers::OCL_Strong: 1301 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true); 1302 return; 1303 1304 case Qualifiers::OCL_Weak: 1305 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true); 1306 return; 1307 1308 case Qualifiers::OCL_Autoreleasing: 1309 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(), 1310 Src.getScalarVal())); 1311 // fall into the normal path 1312 break; 1313 } 1314 } 1315 1316 if (Dst.isObjCWeak() && !Dst.isNonGC()) { 1317 // load of a __weak object. 1318 llvm::Value *LvalueDst = Dst.getAddress(); 1319 llvm::Value *src = Src.getScalarVal(); 1320 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst); 1321 return; 1322 } 1323 1324 if (Dst.isObjCStrong() && !Dst.isNonGC()) { 1325 // load of a __strong object. 1326 llvm::Value *LvalueDst = Dst.getAddress(); 1327 llvm::Value *src = Src.getScalarVal(); 1328 if (Dst.isObjCIvar()) { 1329 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL"); 1330 llvm::Type *ResultType = ConvertType(getContext().LongTy); 1331 llvm::Value *RHS = EmitScalarExpr(Dst.getBaseIvarExp()); 1332 llvm::Value *dst = RHS; 1333 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast"); 1334 llvm::Value *LHS = 1335 Builder.CreatePtrToInt(LvalueDst, ResultType, "sub.ptr.lhs.cast"); 1336 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset"); 1337 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst, 1338 BytesBetween); 1339 } else if (Dst.isGlobalObjCRef()) { 1340 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst, 1341 Dst.isThreadLocalRef()); 1342 } 1343 else 1344 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst); 1345 return; 1346 } 1347 1348 assert(Src.isScalar() && "Can't emit an agg store with this method"); 1349 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit); 1350 } 1351 1352 void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, 1353 llvm::Value **Result) { 1354 const CGBitFieldInfo &Info = Dst.getBitFieldInfo(); 1355 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType()); 1356 llvm::Value *Ptr = Dst.getBitFieldAddr(); 1357 1358 // Get the source value, truncated to the width of the bit-field. 1359 llvm::Value *SrcVal = Src.getScalarVal(); 1360 1361 // Cast the source to the storage type and shift it into place. 1362 SrcVal = Builder.CreateIntCast(SrcVal, 1363 Ptr->getType()->getPointerElementType(), 1364 /*IsSigned=*/false); 1365 llvm::Value *MaskedVal = SrcVal; 1366 1367 // See if there are other bits in the bitfield's storage we'll need to load 1368 // and mask together with source before storing. 1369 if (Info.StorageSize != Info.Size) { 1370 assert(Info.StorageSize > Info.Size && "Invalid bitfield size."); 1371 llvm::Value *Val = Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), 1372 "bf.load"); 1373 cast<llvm::LoadInst>(Val)->setAlignment(Info.StorageAlignment); 1374 1375 // Mask the source value as needed. 1376 if (!hasBooleanRepresentation(Dst.getType())) 1377 SrcVal = Builder.CreateAnd(SrcVal, 1378 llvm::APInt::getLowBitsSet(Info.StorageSize, 1379 Info.Size), 1380 "bf.value"); 1381 MaskedVal = SrcVal; 1382 if (Info.Offset) 1383 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl"); 1384 1385 // Mask out the original value. 1386 Val = Builder.CreateAnd(Val, 1387 ~llvm::APInt::getBitsSet(Info.StorageSize, 1388 Info.Offset, 1389 Info.Offset + Info.Size), 1390 "bf.clear"); 1391 1392 // Or together the unchanged values and the source value. 1393 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set"); 1394 } else { 1395 assert(Info.Offset == 0); 1396 } 1397 1398 // Write the new value back out. 1399 llvm::StoreInst *Store = Builder.CreateStore(SrcVal, Ptr, 1400 Dst.isVolatileQualified()); 1401 Store->setAlignment(Info.StorageAlignment); 1402 1403 // Return the new value of the bit-field, if requested. 1404 if (Result) { 1405 llvm::Value *ResultVal = MaskedVal; 1406 1407 // Sign extend the value if needed. 1408 if (Info.IsSigned) { 1409 assert(Info.Size <= Info.StorageSize); 1410 unsigned HighBits = Info.StorageSize - Info.Size; 1411 if (HighBits) { 1412 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl"); 1413 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr"); 1414 } 1415 } 1416 1417 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned, 1418 "bf.result.cast"); 1419 *Result = EmitFromMemory(ResultVal, Dst.getType()); 1420 } 1421 } 1422 1423 void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src, 1424 LValue Dst) { 1425 // This access turns into a read/modify/write of the vector. Load the input 1426 // value now. 1427 llvm::LoadInst *Load = Builder.CreateLoad(Dst.getExtVectorAddr(), 1428 Dst.isVolatileQualified()); 1429 Load->setAlignment(Dst.getAlignment().getQuantity()); 1430 llvm::Value *Vec = Load; 1431 const llvm::Constant *Elts = Dst.getExtVectorElts(); 1432 1433 llvm::Value *SrcVal = Src.getScalarVal(); 1434 1435 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) { 1436 unsigned NumSrcElts = VTy->getNumElements(); 1437 unsigned NumDstElts = 1438 cast<llvm::VectorType>(Vec->getType())->getNumElements(); 1439 if (NumDstElts == NumSrcElts) { 1440 // Use shuffle vector is the src and destination are the same number of 1441 // elements and restore the vector mask since it is on the side it will be 1442 // stored. 1443 SmallVector<llvm::Constant*, 4> Mask(NumDstElts); 1444 for (unsigned i = 0; i != NumSrcElts; ++i) 1445 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i); 1446 1447 llvm::Value *MaskV = llvm::ConstantVector::get(Mask); 1448 Vec = Builder.CreateShuffleVector(SrcVal, 1449 llvm::UndefValue::get(Vec->getType()), 1450 MaskV); 1451 } else if (NumDstElts > NumSrcElts) { 1452 // Extended the source vector to the same length and then shuffle it 1453 // into the destination. 1454 // FIXME: since we're shuffling with undef, can we just use the indices 1455 // into that? This could be simpler. 1456 SmallVector<llvm::Constant*, 4> ExtMask; 1457 for (unsigned i = 0; i != NumSrcElts; ++i) 1458 ExtMask.push_back(Builder.getInt32(i)); 1459 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty)); 1460 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask); 1461 llvm::Value *ExtSrcVal = 1462 Builder.CreateShuffleVector(SrcVal, 1463 llvm::UndefValue::get(SrcVal->getType()), 1464 ExtMaskV); 1465 // build identity 1466 SmallVector<llvm::Constant*, 4> Mask; 1467 for (unsigned i = 0; i != NumDstElts; ++i) 1468 Mask.push_back(Builder.getInt32(i)); 1469 1470 // modify when what gets shuffled in 1471 for (unsigned i = 0; i != NumSrcElts; ++i) 1472 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts); 1473 llvm::Value *MaskV = llvm::ConstantVector::get(Mask); 1474 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV); 1475 } else { 1476 // We should never shorten the vector 1477 llvm_unreachable("unexpected shorten vector length"); 1478 } 1479 } else { 1480 // If the Src is a scalar (not a vector) it must be updating one element. 1481 unsigned InIdx = getAccessedFieldNo(0, Elts); 1482 llvm::Value *Elt = llvm::ConstantInt::get(Int32Ty, InIdx); 1483 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt); 1484 } 1485 1486 llvm::StoreInst *Store = Builder.CreateStore(Vec, Dst.getExtVectorAddr(), 1487 Dst.isVolatileQualified()); 1488 Store->setAlignment(Dst.getAlignment().getQuantity()); 1489 } 1490 1491 // setObjCGCLValueClass - sets class of he lvalue for the purpose of 1492 // generating write-barries API. It is currently a global, ivar, 1493 // or neither. 1494 static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E, 1495 LValue &LV, 1496 bool IsMemberAccess=false) { 1497 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC) 1498 return; 1499 1500 if (isa<ObjCIvarRefExpr>(E)) { 1501 QualType ExpTy = E->getType(); 1502 if (IsMemberAccess && ExpTy->isPointerType()) { 1503 // If ivar is a structure pointer, assigning to field of 1504 // this struct follows gcc's behavior and makes it a non-ivar 1505 // writer-barrier conservatively. 1506 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType(); 1507 if (ExpTy->isRecordType()) { 1508 LV.setObjCIvar(false); 1509 return; 1510 } 1511 } 1512 LV.setObjCIvar(true); 1513 ObjCIvarRefExpr *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr*>(E)); 1514 LV.setBaseIvarExp(Exp->getBase()); 1515 LV.setObjCArray(E->getType()->isArrayType()); 1516 return; 1517 } 1518 1519 if (const DeclRefExpr *Exp = dyn_cast<DeclRefExpr>(E)) { 1520 if (const VarDecl *VD = dyn_cast<VarDecl>(Exp->getDecl())) { 1521 if (VD->hasGlobalStorage()) { 1522 LV.setGlobalObjCRef(true); 1523 LV.setThreadLocalRef(VD->isThreadSpecified()); 1524 } 1525 } 1526 LV.setObjCArray(E->getType()->isArrayType()); 1527 return; 1528 } 1529 1530 if (const UnaryOperator *Exp = dyn_cast<UnaryOperator>(E)) { 1531 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess); 1532 return; 1533 } 1534 1535 if (const ParenExpr *Exp = dyn_cast<ParenExpr>(E)) { 1536 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess); 1537 if (LV.isObjCIvar()) { 1538 // If cast is to a structure pointer, follow gcc's behavior and make it 1539 // a non-ivar write-barrier. 1540 QualType ExpTy = E->getType(); 1541 if (ExpTy->isPointerType()) 1542 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType(); 1543 if (ExpTy->isRecordType()) 1544 LV.setObjCIvar(false); 1545 } 1546 return; 1547 } 1548 1549 if (const GenericSelectionExpr *Exp = dyn_cast<GenericSelectionExpr>(E)) { 1550 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV); 1551 return; 1552 } 1553 1554 if (const ImplicitCastExpr *Exp = dyn_cast<ImplicitCastExpr>(E)) { 1555 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess); 1556 return; 1557 } 1558 1559 if (const CStyleCastExpr *Exp = dyn_cast<CStyleCastExpr>(E)) { 1560 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess); 1561 return; 1562 } 1563 1564 if (const ObjCBridgedCastExpr *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) { 1565 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess); 1566 return; 1567 } 1568 1569 if (const ArraySubscriptExpr *Exp = dyn_cast<ArraySubscriptExpr>(E)) { 1570 setObjCGCLValueClass(Ctx, Exp->getBase(), LV); 1571 if (LV.isObjCIvar() && !LV.isObjCArray()) 1572 // Using array syntax to assigning to what an ivar points to is not 1573 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0; 1574 LV.setObjCIvar(false); 1575 else if (LV.isGlobalObjCRef() && !LV.isObjCArray()) 1576 // Using array syntax to assigning to what global points to is not 1577 // same as assigning to the global itself. {id *G;} G[i] = 0; 1578 LV.setGlobalObjCRef(false); 1579 return; 1580 } 1581 1582 if (const MemberExpr *Exp = dyn_cast<MemberExpr>(E)) { 1583 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true); 1584 // We don't know if member is an 'ivar', but this flag is looked at 1585 // only in the context of LV.isObjCIvar(). 1586 LV.setObjCArray(E->getType()->isArrayType()); 1587 return; 1588 } 1589 } 1590 1591 static llvm::Value * 1592 EmitBitCastOfLValueToProperType(CodeGenFunction &CGF, 1593 llvm::Value *V, llvm::Type *IRType, 1594 StringRef Name = StringRef()) { 1595 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace(); 1596 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name); 1597 } 1598 1599 static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF, 1600 const Expr *E, const VarDecl *VD) { 1601 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD); 1602 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType()); 1603 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy); 1604 CharUnits Alignment = CGF.getContext().getDeclAlign(VD); 1605 QualType T = E->getType(); 1606 LValue LV; 1607 if (VD->getType()->isReferenceType()) { 1608 llvm::LoadInst *LI = CGF.Builder.CreateLoad(V); 1609 LI->setAlignment(Alignment.getQuantity()); 1610 V = LI; 1611 LV = CGF.MakeNaturalAlignAddrLValue(V, T); 1612 } else { 1613 LV = CGF.MakeAddrLValue(V, E->getType(), Alignment); 1614 } 1615 setObjCGCLValueClass(CGF.getContext(), E, LV); 1616 return LV; 1617 } 1618 1619 static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF, 1620 const Expr *E, const FunctionDecl *FD) { 1621 llvm::Value *V = CGF.CGM.GetAddrOfFunction(FD); 1622 if (!FD->hasPrototype()) { 1623 if (const FunctionProtoType *Proto = 1624 FD->getType()->getAs<FunctionProtoType>()) { 1625 // Ugly case: for a K&R-style definition, the type of the definition 1626 // isn't the same as the type of a use. Correct for this with a 1627 // bitcast. 1628 QualType NoProtoType = 1629 CGF.getContext().getFunctionNoProtoType(Proto->getResultType()); 1630 NoProtoType = CGF.getContext().getPointerType(NoProtoType); 1631 V = CGF.Builder.CreateBitCast(V, CGF.ConvertType(NoProtoType)); 1632 } 1633 } 1634 CharUnits Alignment = CGF.getContext().getDeclAlign(FD); 1635 return CGF.MakeAddrLValue(V, E->getType(), Alignment); 1636 } 1637 1638 LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) { 1639 const NamedDecl *ND = E->getDecl(); 1640 CharUnits Alignment = getContext().getDeclAlign(ND); 1641 QualType T = E->getType(); 1642 1643 // A DeclRefExpr for a reference initialized by a constant expression can 1644 // appear without being odr-used. Directly emit the constant initializer. 1645 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) { 1646 const Expr *Init = VD->getAnyInitializer(VD); 1647 if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() && 1648 VD->isUsableInConstantExpressions(getContext()) && 1649 VD->checkInitIsICE()) { 1650 llvm::Constant *Val = 1651 CGM.EmitConstantValue(*VD->evaluateValue(), VD->getType(), this); 1652 assert(Val && "failed to emit reference constant expression"); 1653 // FIXME: Eventually we will want to emit vector element references. 1654 return MakeAddrLValue(Val, T, Alignment); 1655 } 1656 } 1657 1658 // FIXME: We should be able to assert this for FunctionDecls as well! 1659 // FIXME: We should be able to assert this for all DeclRefExprs, not just 1660 // those with a valid source location. 1661 assert((ND->isUsed(false) || !isa<VarDecl>(ND) || 1662 !E->getLocation().isValid()) && 1663 "Should not use decl without marking it used!"); 1664 1665 if (ND->hasAttr<WeakRefAttr>()) { 1666 const ValueDecl *VD = cast<ValueDecl>(ND); 1667 llvm::Constant *Aliasee = CGM.GetWeakRefReference(VD); 1668 return MakeAddrLValue(Aliasee, T, Alignment); 1669 } 1670 1671 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) { 1672 // Check if this is a global variable. 1673 if (VD->hasLinkage() || VD->isStaticDataMember()) 1674 return EmitGlobalVarDeclLValue(*this, E, VD); 1675 1676 bool isBlockVariable = VD->hasAttr<BlocksAttr>(); 1677 1678 bool NonGCable = VD->hasLocalStorage() && 1679 !VD->getType()->isReferenceType() && 1680 !isBlockVariable; 1681 1682 llvm::Value *V = LocalDeclMap.lookup(VD); 1683 if (!V && VD->isStaticLocal()) 1684 V = CGM.getStaticLocalDeclAddress(VD); 1685 1686 // Use special handling for lambdas. 1687 if (!V) { 1688 if (FieldDecl *FD = LambdaCaptureFields.lookup(VD)) { 1689 QualType LambdaTagType = getContext().getTagDeclType(FD->getParent()); 1690 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, 1691 LambdaTagType); 1692 return EmitLValueForField(LambdaLV, FD); 1693 } 1694 1695 assert(isa<BlockDecl>(CurCodeDecl) && E->refersToEnclosingLocal()); 1696 return MakeAddrLValue(GetAddrOfBlockDecl(VD, isBlockVariable), 1697 T, Alignment); 1698 } 1699 1700 assert(V && "DeclRefExpr not entered in LocalDeclMap?"); 1701 1702 if (isBlockVariable) 1703 V = BuildBlockByrefAddress(V, VD); 1704 1705 LValue LV; 1706 if (VD->getType()->isReferenceType()) { 1707 llvm::LoadInst *LI = Builder.CreateLoad(V); 1708 LI->setAlignment(Alignment.getQuantity()); 1709 V = LI; 1710 LV = MakeNaturalAlignAddrLValue(V, T); 1711 } else { 1712 LV = MakeAddrLValue(V, T, Alignment); 1713 } 1714 1715 if (NonGCable) { 1716 LV.getQuals().removeObjCGCAttr(); 1717 LV.setNonGC(true); 1718 } 1719 setObjCGCLValueClass(getContext(), E, LV); 1720 return LV; 1721 } 1722 1723 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(ND)) 1724 return EmitFunctionDeclLValue(*this, E, fn); 1725 1726 llvm_unreachable("Unhandled DeclRefExpr"); 1727 } 1728 1729 LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) { 1730 // __extension__ doesn't affect lvalue-ness. 1731 if (E->getOpcode() == UO_Extension) 1732 return EmitLValue(E->getSubExpr()); 1733 1734 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType()); 1735 switch (E->getOpcode()) { 1736 default: llvm_unreachable("Unknown unary operator lvalue!"); 1737 case UO_Deref: { 1738 QualType T = E->getSubExpr()->getType()->getPointeeType(); 1739 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type"); 1740 1741 LValue LV = MakeNaturalAlignAddrLValue(EmitScalarExpr(E->getSubExpr()), T); 1742 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace()); 1743 1744 // We should not generate __weak write barrier on indirect reference 1745 // of a pointer to object; as in void foo (__weak id *param); *param = 0; 1746 // But, we continue to generate __strong write barrier on indirect write 1747 // into a pointer to object. 1748 if (getLangOpts().ObjC1 && 1749 getLangOpts().getGC() != LangOptions::NonGC && 1750 LV.isObjCWeak()) 1751 LV.setNonGC(!E->isOBJCGCCandidate(getContext())); 1752 return LV; 1753 } 1754 case UO_Real: 1755 case UO_Imag: { 1756 LValue LV = EmitLValue(E->getSubExpr()); 1757 assert(LV.isSimple() && "real/imag on non-ordinary l-value"); 1758 llvm::Value *Addr = LV.getAddress(); 1759 1760 // __real is valid on scalars. This is a faster way of testing that. 1761 // __imag can only produce an rvalue on scalars. 1762 if (E->getOpcode() == UO_Real && 1763 !cast<llvm::PointerType>(Addr->getType()) 1764 ->getElementType()->isStructTy()) { 1765 assert(E->getSubExpr()->getType()->isArithmeticType()); 1766 return LV; 1767 } 1768 1769 assert(E->getSubExpr()->getType()->isAnyComplexType()); 1770 1771 unsigned Idx = E->getOpcode() == UO_Imag; 1772 return MakeAddrLValue(Builder.CreateStructGEP(LV.getAddress(), 1773 Idx, "idx"), 1774 ExprTy); 1775 } 1776 case UO_PreInc: 1777 case UO_PreDec: { 1778 LValue LV = EmitLValue(E->getSubExpr()); 1779 bool isInc = E->getOpcode() == UO_PreInc; 1780 1781 if (E->getType()->isAnyComplexType()) 1782 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/); 1783 else 1784 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/); 1785 return LV; 1786 } 1787 } 1788 } 1789 1790 LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) { 1791 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E), 1792 E->getType()); 1793 } 1794 1795 LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) { 1796 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E), 1797 E->getType()); 1798 } 1799 1800 static llvm::Constant* 1801 GetAddrOfConstantWideString(StringRef Str, 1802 const char *GlobalName, 1803 ASTContext &Context, 1804 QualType Ty, SourceLocation Loc, 1805 CodeGenModule &CGM) { 1806 1807 StringLiteral *SL = StringLiteral::Create(Context, 1808 Str, 1809 StringLiteral::Wide, 1810 /*Pascal = */false, 1811 Ty, Loc); 1812 llvm::Constant *C = CGM.GetConstantArrayFromStringLiteral(SL); 1813 llvm::GlobalVariable *GV = 1814 new llvm::GlobalVariable(CGM.getModule(), C->getType(), 1815 !CGM.getLangOpts().WritableStrings, 1816 llvm::GlobalValue::PrivateLinkage, 1817 C, GlobalName); 1818 const unsigned WideAlignment = 1819 Context.getTypeAlignInChars(Ty).getQuantity(); 1820 GV->setAlignment(WideAlignment); 1821 return GV; 1822 } 1823 1824 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 1825 SmallString<32>& Target) { 1826 Target.resize(CharByteWidth * (Source.size() + 1)); 1827 char *ResultPtr = &Target[0]; 1828 const UTF8 *ErrorPtr; 1829 bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 1830 (void)success; 1831 assert(success); 1832 Target.resize(ResultPtr - &Target[0]); 1833 } 1834 1835 LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) { 1836 switch (E->getIdentType()) { 1837 default: 1838 return EmitUnsupportedLValue(E, "predefined expression"); 1839 1840 case PredefinedExpr::Func: 1841 case PredefinedExpr::Function: 1842 case PredefinedExpr::LFunction: 1843 case PredefinedExpr::PrettyFunction: { 1844 unsigned IdentType = E->getIdentType(); 1845 std::string GlobalVarName; 1846 1847 switch (IdentType) { 1848 default: llvm_unreachable("Invalid type"); 1849 case PredefinedExpr::Func: 1850 GlobalVarName = "__func__."; 1851 break; 1852 case PredefinedExpr::Function: 1853 GlobalVarName = "__FUNCTION__."; 1854 break; 1855 case PredefinedExpr::LFunction: 1856 GlobalVarName = "L__FUNCTION__."; 1857 break; 1858 case PredefinedExpr::PrettyFunction: 1859 GlobalVarName = "__PRETTY_FUNCTION__."; 1860 break; 1861 } 1862 1863 StringRef FnName = CurFn->getName(); 1864 if (FnName.startswith("\01")) 1865 FnName = FnName.substr(1); 1866 GlobalVarName += FnName; 1867 1868 const Decl *CurDecl = CurCodeDecl; 1869 if (CurDecl == 0) 1870 CurDecl = getContext().getTranslationUnitDecl(); 1871 1872 std::string FunctionName = 1873 (isa<BlockDecl>(CurDecl) 1874 ? FnName.str() 1875 : PredefinedExpr::ComputeName((PredefinedExpr::IdentType)IdentType, 1876 CurDecl)); 1877 1878 const Type* ElemType = E->getType()->getArrayElementTypeNoTypeQual(); 1879 llvm::Constant *C; 1880 if (ElemType->isWideCharType()) { 1881 SmallString<32> RawChars; 1882 ConvertUTF8ToWideString( 1883 getContext().getTypeSizeInChars(ElemType).getQuantity(), 1884 FunctionName, RawChars); 1885 C = GetAddrOfConstantWideString(RawChars, 1886 GlobalVarName.c_str(), 1887 getContext(), 1888 E->getType(), 1889 E->getLocation(), 1890 CGM); 1891 } else { 1892 C = CGM.GetAddrOfConstantCString(FunctionName, 1893 GlobalVarName.c_str(), 1894 1); 1895 } 1896 return MakeAddrLValue(C, E->getType()); 1897 } 1898 } 1899 } 1900 1901 /// Emit a type description suitable for use by a runtime sanitizer library. The 1902 /// format of a type descriptor is 1903 /// 1904 /// \code 1905 /// { i16 TypeKind, i16 TypeInfo } 1906 /// \endcode 1907 /// 1908 /// followed by an array of i8 containing the type name. TypeKind is 0 for an 1909 /// integer, 1 for a floating point value, and -1 for anything else. 1910 llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) { 1911 // FIXME: Only emit each type's descriptor once. 1912 uint16_t TypeKind = -1; 1913 uint16_t TypeInfo = 0; 1914 1915 if (T->isIntegerType()) { 1916 TypeKind = 0; 1917 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) | 1918 (T->isSignedIntegerType() ? 1 : 0); 1919 } else if (T->isFloatingType()) { 1920 TypeKind = 1; 1921 TypeInfo = getContext().getTypeSize(T); 1922 } 1923 1924 // Format the type name as if for a diagnostic, including quotes and 1925 // optionally an 'aka'. 1926 SmallString<32> Buffer; 1927 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype, 1928 (intptr_t)T.getAsOpaquePtr(), 1929 0, 0, 0, 0, 0, 0, Buffer, 1930 ArrayRef<intptr_t>()); 1931 1932 llvm::Constant *Components[] = { 1933 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo), 1934 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer) 1935 }; 1936 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components); 1937 1938 llvm::GlobalVariable *GV = 1939 new llvm::GlobalVariable(CGM.getModule(), Descriptor->getType(), 1940 /*isConstant=*/true, 1941 llvm::GlobalVariable::PrivateLinkage, 1942 Descriptor); 1943 GV->setUnnamedAddr(true); 1944 return GV; 1945 } 1946 1947 llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) { 1948 llvm::Type *TargetTy = IntPtrTy; 1949 1950 // Integers which fit in intptr_t are zero-extended and passed directly. 1951 if (V->getType()->isIntegerTy() && 1952 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth()) 1953 return Builder.CreateZExt(V, TargetTy); 1954 1955 // Pointers are passed directly, everything else is passed by address. 1956 if (!V->getType()->isPointerTy()) { 1957 llvm::Value *Ptr = Builder.CreateAlloca(V->getType()); 1958 Builder.CreateStore(V, Ptr); 1959 V = Ptr; 1960 } 1961 return Builder.CreatePtrToInt(V, TargetTy); 1962 } 1963 1964 /// \brief Emit a representation of a SourceLocation for passing to a handler 1965 /// in a sanitizer runtime library. The format for this data is: 1966 /// \code 1967 /// struct SourceLocation { 1968 /// const char *Filename; 1969 /// int32_t Line, Column; 1970 /// }; 1971 /// \endcode 1972 /// For an invalid SourceLocation, the Filename pointer is null. 1973 llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) { 1974 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc); 1975 1976 llvm::Constant *Data[] = { 1977 // FIXME: Only emit each file name once. 1978 PLoc.isValid() ? cast<llvm::Constant>( 1979 Builder.CreateGlobalStringPtr(PLoc.getFilename())) 1980 : llvm::Constant::getNullValue(Int8PtrTy), 1981 Builder.getInt32(PLoc.getLine()), 1982 Builder.getInt32(PLoc.getColumn()) 1983 }; 1984 1985 return llvm::ConstantStruct::getAnon(Data); 1986 } 1987 1988 void CodeGenFunction::EmitCheck(llvm::Value *Checked, StringRef CheckName, 1989 ArrayRef<llvm::Constant *> StaticArgs, 1990 ArrayRef<llvm::Value *> DynamicArgs, 1991 CheckRecoverableKind RecoverKind) { 1992 assert(SanOpts != &SanitizerOptions::Disabled); 1993 1994 if (CGM.getCodeGenOpts().SanitizeUndefinedTrapOnError) { 1995 assert (RecoverKind != CRK_AlwaysRecoverable && 1996 "Runtime call required for AlwaysRecoverable kind!"); 1997 return EmitTrapCheck(Checked); 1998 } 1999 2000 llvm::BasicBlock *Cont = createBasicBlock("cont"); 2001 2002 llvm::BasicBlock *Handler = createBasicBlock("handler." + CheckName); 2003 2004 llvm::Instruction *Branch = Builder.CreateCondBr(Checked, Cont, Handler); 2005 2006 // Give hint that we very much don't expect to execute the handler 2007 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp 2008 llvm::MDBuilder MDHelper(getLLVMContext()); 2009 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1); 2010 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node); 2011 2012 EmitBlock(Handler); 2013 2014 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs); 2015 llvm::GlobalValue *InfoPtr = 2016 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false, 2017 llvm::GlobalVariable::PrivateLinkage, Info); 2018 InfoPtr->setUnnamedAddr(true); 2019 2020 SmallVector<llvm::Value *, 4> Args; 2021 SmallVector<llvm::Type *, 4> ArgTypes; 2022 Args.reserve(DynamicArgs.size() + 1); 2023 ArgTypes.reserve(DynamicArgs.size() + 1); 2024 2025 // Handler functions take an i8* pointing to the (handler-specific) static 2026 // information block, followed by a sequence of intptr_t arguments 2027 // representing operand values. 2028 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy)); 2029 ArgTypes.push_back(Int8PtrTy); 2030 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) { 2031 Args.push_back(EmitCheckValue(DynamicArgs[i])); 2032 ArgTypes.push_back(IntPtrTy); 2033 } 2034 2035 bool Recover = (RecoverKind == CRK_AlwaysRecoverable) || 2036 ((RecoverKind == CRK_Recoverable) && 2037 CGM.getCodeGenOpts().SanitizeRecover); 2038 2039 llvm::FunctionType *FnType = 2040 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false); 2041 llvm::AttrBuilder B; 2042 if (!Recover) { 2043 B.addAttribute(llvm::Attribute::NoReturn) 2044 .addAttribute(llvm::Attribute::NoUnwind); 2045 } 2046 B.addAttribute(llvm::Attribute::UWTable); 2047 2048 // Checks that have two variants use a suffix to differentiate them 2049 bool NeedsAbortSuffix = (RecoverKind != CRK_Unrecoverable) && 2050 !CGM.getCodeGenOpts().SanitizeRecover; 2051 std::string FunctionName = ("__ubsan_handle_" + CheckName + 2052 (NeedsAbortSuffix? "_abort" : "")).str(); 2053 llvm::Value *Fn = 2054 CGM.CreateRuntimeFunction(FnType, FunctionName, 2055 llvm::AttributeSet::get(getLLVMContext(), 2056 llvm::AttributeSet::FunctionIndex, 2057 B)); 2058 llvm::CallInst *HandlerCall = Builder.CreateCall(Fn, Args); 2059 if (Recover) { 2060 Builder.CreateBr(Cont); 2061 } else { 2062 HandlerCall->setDoesNotReturn(); 2063 HandlerCall->setDoesNotThrow(); 2064 Builder.CreateUnreachable(); 2065 } 2066 2067 EmitBlock(Cont); 2068 } 2069 2070 void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) { 2071 llvm::BasicBlock *Cont = createBasicBlock("cont"); 2072 2073 // If we're optimizing, collapse all calls to trap down to just one per 2074 // function to save on code size. 2075 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) { 2076 TrapBB = createBasicBlock("trap"); 2077 Builder.CreateCondBr(Checked, Cont, TrapBB); 2078 EmitBlock(TrapBB); 2079 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::trap); 2080 llvm::CallInst *TrapCall = Builder.CreateCall(F); 2081 TrapCall->setDoesNotReturn(); 2082 TrapCall->setDoesNotThrow(); 2083 Builder.CreateUnreachable(); 2084 } else { 2085 Builder.CreateCondBr(Checked, Cont, TrapBB); 2086 } 2087 2088 EmitBlock(Cont); 2089 } 2090 2091 /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an 2092 /// array to pointer, return the array subexpression. 2093 static const Expr *isSimpleArrayDecayOperand(const Expr *E) { 2094 // If this isn't just an array->pointer decay, bail out. 2095 const CastExpr *CE = dyn_cast<CastExpr>(E); 2096 if (CE == 0 || CE->getCastKind() != CK_ArrayToPointerDecay) 2097 return 0; 2098 2099 // If this is a decay from variable width array, bail out. 2100 const Expr *SubExpr = CE->getSubExpr(); 2101 if (SubExpr->getType()->isVariableArrayType()) 2102 return 0; 2103 2104 return SubExpr; 2105 } 2106 2107 LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) { 2108 // The index must always be an integer, which is not an aggregate. Emit it. 2109 llvm::Value *Idx = EmitScalarExpr(E->getIdx()); 2110 QualType IdxTy = E->getIdx()->getType(); 2111 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType(); 2112 2113 // If the base is a vector type, then we are forming a vector element lvalue 2114 // with this subscript. 2115 if (E->getBase()->getType()->isVectorType()) { 2116 // Emit the vector as an lvalue to get its address. 2117 LValue LHS = EmitLValue(E->getBase()); 2118 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!"); 2119 Idx = Builder.CreateIntCast(Idx, Int32Ty, IdxSigned, "vidx"); 2120 return LValue::MakeVectorElt(LHS.getAddress(), Idx, 2121 E->getBase()->getType(), LHS.getAlignment()); 2122 } 2123 2124 // Extend or truncate the index type to 32 or 64-bits. 2125 if (Idx->getType() != IntPtrTy) 2126 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom"); 2127 2128 // We know that the pointer points to a type of the correct size, unless the 2129 // size is a VLA or Objective-C interface. 2130 llvm::Value *Address = 0; 2131 CharUnits ArrayAlignment; 2132 if (const VariableArrayType *vla = 2133 getContext().getAsVariableArrayType(E->getType())) { 2134 // The base must be a pointer, which is not an aggregate. Emit 2135 // it. It needs to be emitted first in case it's what captures 2136 // the VLA bounds. 2137 Address = EmitScalarExpr(E->getBase()); 2138 2139 // The element count here is the total number of non-VLA elements. 2140 llvm::Value *numElements = getVLASize(vla).first; 2141 2142 // Effectively, the multiply by the VLA size is part of the GEP. 2143 // GEP indexes are signed, and scaling an index isn't permitted to 2144 // signed-overflow, so we use the same semantics for our explicit 2145 // multiply. We suppress this if overflow is not undefined behavior. 2146 if (getLangOpts().isSignedOverflowDefined()) { 2147 Idx = Builder.CreateMul(Idx, numElements); 2148 Address = Builder.CreateGEP(Address, Idx, "arrayidx"); 2149 } else { 2150 Idx = Builder.CreateNSWMul(Idx, numElements); 2151 Address = Builder.CreateInBoundsGEP(Address, Idx, "arrayidx"); 2152 } 2153 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){ 2154 // Indexing over an interface, as in "NSString *P; P[4];" 2155 llvm::Value *InterfaceSize = 2156 llvm::ConstantInt::get(Idx->getType(), 2157 getContext().getTypeSizeInChars(OIT).getQuantity()); 2158 2159 Idx = Builder.CreateMul(Idx, InterfaceSize); 2160 2161 // The base must be a pointer, which is not an aggregate. Emit it. 2162 llvm::Value *Base = EmitScalarExpr(E->getBase()); 2163 Address = EmitCastToVoidPtr(Base); 2164 Address = Builder.CreateGEP(Address, Idx, "arrayidx"); 2165 Address = Builder.CreateBitCast(Address, Base->getType()); 2166 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) { 2167 // If this is A[i] where A is an array, the frontend will have decayed the 2168 // base to be a ArrayToPointerDecay implicit cast. While correct, it is 2169 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a 2170 // "gep x, i" here. Emit one "gep A, 0, i". 2171 assert(Array->getType()->isArrayType() && 2172 "Array to pointer decay must have array source type!"); 2173 LValue ArrayLV = EmitLValue(Array); 2174 llvm::Value *ArrayPtr = ArrayLV.getAddress(); 2175 llvm::Value *Zero = llvm::ConstantInt::get(Int32Ty, 0); 2176 llvm::Value *Args[] = { Zero, Idx }; 2177 2178 // Propagate the alignment from the array itself to the result. 2179 ArrayAlignment = ArrayLV.getAlignment(); 2180 2181 if (getLangOpts().isSignedOverflowDefined()) 2182 Address = Builder.CreateGEP(ArrayPtr, Args, "arrayidx"); 2183 else 2184 Address = Builder.CreateInBoundsGEP(ArrayPtr, Args, "arrayidx"); 2185 } else { 2186 // The base must be a pointer, which is not an aggregate. Emit it. 2187 llvm::Value *Base = EmitScalarExpr(E->getBase()); 2188 if (getLangOpts().isSignedOverflowDefined()) 2189 Address = Builder.CreateGEP(Base, Idx, "arrayidx"); 2190 else 2191 Address = Builder.CreateInBoundsGEP(Base, Idx, "arrayidx"); 2192 } 2193 2194 QualType T = E->getBase()->getType()->getPointeeType(); 2195 assert(!T.isNull() && 2196 "CodeGenFunction::EmitArraySubscriptExpr(): Illegal base type"); 2197 2198 2199 // Limit the alignment to that of the result type. 2200 LValue LV; 2201 if (!ArrayAlignment.isZero()) { 2202 CharUnits Align = getContext().getTypeAlignInChars(T); 2203 ArrayAlignment = std::min(Align, ArrayAlignment); 2204 LV = MakeAddrLValue(Address, T, ArrayAlignment); 2205 } else { 2206 LV = MakeNaturalAlignAddrLValue(Address, T); 2207 } 2208 2209 LV.getQuals().setAddressSpace(E->getBase()->getType().getAddressSpace()); 2210 2211 if (getLangOpts().ObjC1 && 2212 getLangOpts().getGC() != LangOptions::NonGC) { 2213 LV.setNonGC(!E->isOBJCGCCandidate(getContext())); 2214 setObjCGCLValueClass(getContext(), E, LV); 2215 } 2216 return LV; 2217 } 2218 2219 static 2220 llvm::Constant *GenerateConstantVector(CGBuilderTy &Builder, 2221 SmallVector<unsigned, 4> &Elts) { 2222 SmallVector<llvm::Constant*, 4> CElts; 2223 for (unsigned i = 0, e = Elts.size(); i != e; ++i) 2224 CElts.push_back(Builder.getInt32(Elts[i])); 2225 2226 return llvm::ConstantVector::get(CElts); 2227 } 2228 2229 LValue CodeGenFunction:: 2230 EmitExtVectorElementExpr(const ExtVectorElementExpr *E) { 2231 // Emit the base vector as an l-value. 2232 LValue Base; 2233 2234 // ExtVectorElementExpr's base can either be a vector or pointer to vector. 2235 if (E->isArrow()) { 2236 // If it is a pointer to a vector, emit the address and form an lvalue with 2237 // it. 2238 llvm::Value *Ptr = EmitScalarExpr(E->getBase()); 2239 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>(); 2240 Base = MakeAddrLValue(Ptr, PT->getPointeeType()); 2241 Base.getQuals().removeObjCGCAttr(); 2242 } else if (E->getBase()->isGLValue()) { 2243 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x), 2244 // emit the base as an lvalue. 2245 assert(E->getBase()->getType()->isVectorType()); 2246 Base = EmitLValue(E->getBase()); 2247 } else { 2248 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such. 2249 assert(E->getBase()->getType()->isVectorType() && 2250 "Result must be a vector"); 2251 llvm::Value *Vec = EmitScalarExpr(E->getBase()); 2252 2253 // Store the vector to memory (because LValue wants an address). 2254 llvm::Value *VecMem = CreateMemTemp(E->getBase()->getType()); 2255 Builder.CreateStore(Vec, VecMem); 2256 Base = MakeAddrLValue(VecMem, E->getBase()->getType()); 2257 } 2258 2259 QualType type = 2260 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers()); 2261 2262 // Encode the element access list into a vector of unsigned indices. 2263 SmallVector<unsigned, 4> Indices; 2264 E->getEncodedElementAccess(Indices); 2265 2266 if (Base.isSimple()) { 2267 llvm::Constant *CV = GenerateConstantVector(Builder, Indices); 2268 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type, 2269 Base.getAlignment()); 2270 } 2271 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!"); 2272 2273 llvm::Constant *BaseElts = Base.getExtVectorElts(); 2274 SmallVector<llvm::Constant *, 4> CElts; 2275 2276 for (unsigned i = 0, e = Indices.size(); i != e; ++i) 2277 CElts.push_back(BaseElts->getAggregateElement(Indices[i])); 2278 llvm::Constant *CV = llvm::ConstantVector::get(CElts); 2279 return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV, type, 2280 Base.getAlignment()); 2281 } 2282 2283 LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) { 2284 Expr *BaseExpr = E->getBase(); 2285 2286 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar. 2287 LValue BaseLV; 2288 if (E->isArrow()) { 2289 llvm::Value *Ptr = EmitScalarExpr(BaseExpr); 2290 QualType PtrTy = BaseExpr->getType()->getPointeeType(); 2291 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Ptr, PtrTy); 2292 BaseLV = MakeNaturalAlignAddrLValue(Ptr, PtrTy); 2293 } else 2294 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess); 2295 2296 NamedDecl *ND = E->getMemberDecl(); 2297 if (FieldDecl *Field = dyn_cast<FieldDecl>(ND)) { 2298 LValue LV = EmitLValueForField(BaseLV, Field); 2299 setObjCGCLValueClass(getContext(), E, LV); 2300 return LV; 2301 } 2302 2303 if (VarDecl *VD = dyn_cast<VarDecl>(ND)) 2304 return EmitGlobalVarDeclLValue(*this, E, VD); 2305 2306 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) 2307 return EmitFunctionDeclLValue(*this, E, FD); 2308 2309 llvm_unreachable("Unhandled member declaration!"); 2310 } 2311 2312 LValue CodeGenFunction::EmitLValueForField(LValue base, 2313 const FieldDecl *field) { 2314 if (field->isBitField()) { 2315 const CGRecordLayout &RL = 2316 CGM.getTypes().getCGRecordLayout(field->getParent()); 2317 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field); 2318 llvm::Value *Addr = base.getAddress(); 2319 unsigned Idx = RL.getLLVMFieldNo(field); 2320 if (Idx != 0) 2321 // For structs, we GEP to the field that the record layout suggests. 2322 Addr = Builder.CreateStructGEP(Addr, Idx, field->getName()); 2323 // Get the access type. 2324 llvm::Type *PtrTy = llvm::Type::getIntNPtrTy( 2325 getLLVMContext(), Info.StorageSize, 2326 CGM.getContext().getTargetAddressSpace(base.getType())); 2327 if (Addr->getType() != PtrTy) 2328 Addr = Builder.CreateBitCast(Addr, PtrTy); 2329 2330 QualType fieldType = 2331 field->getType().withCVRQualifiers(base.getVRQualifiers()); 2332 return LValue::MakeBitfield(Addr, Info, fieldType, base.getAlignment()); 2333 } 2334 2335 const RecordDecl *rec = field->getParent(); 2336 QualType type = field->getType(); 2337 CharUnits alignment = getContext().getDeclAlign(field); 2338 2339 // FIXME: It should be impossible to have an LValue without alignment for a 2340 // complete type. 2341 if (!base.getAlignment().isZero()) 2342 alignment = std::min(alignment, base.getAlignment()); 2343 2344 bool mayAlias = rec->hasAttr<MayAliasAttr>(); 2345 2346 llvm::Value *addr = base.getAddress(); 2347 unsigned cvr = base.getVRQualifiers(); 2348 if (rec->isUnion()) { 2349 // For unions, there is no pointer adjustment. 2350 assert(!type->isReferenceType() && "union has reference member"); 2351 } else { 2352 // For structs, we GEP to the field that the record layout suggests. 2353 unsigned idx = CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field); 2354 addr = Builder.CreateStructGEP(addr, idx, field->getName()); 2355 2356 // If this is a reference field, load the reference right now. 2357 if (const ReferenceType *refType = type->getAs<ReferenceType>()) { 2358 llvm::LoadInst *load = Builder.CreateLoad(addr, "ref"); 2359 if (cvr & Qualifiers::Volatile) load->setVolatile(true); 2360 load->setAlignment(alignment.getQuantity()); 2361 2362 if (CGM.shouldUseTBAA()) { 2363 llvm::MDNode *tbaa; 2364 if (mayAlias) 2365 tbaa = CGM.getTBAAInfo(getContext().CharTy); 2366 else 2367 tbaa = CGM.getTBAAInfo(type); 2368 CGM.DecorateInstruction(load, tbaa); 2369 } 2370 2371 addr = load; 2372 mayAlias = false; 2373 type = refType->getPointeeType(); 2374 if (type->isIncompleteType()) 2375 alignment = CharUnits(); 2376 else 2377 alignment = getContext().getTypeAlignInChars(type); 2378 cvr = 0; // qualifiers don't recursively apply to referencee 2379 } 2380 } 2381 2382 // Make sure that the address is pointing to the right type. This is critical 2383 // for both unions and structs. A union needs a bitcast, a struct element 2384 // will need a bitcast if the LLVM type laid out doesn't match the desired 2385 // type. 2386 addr = EmitBitCastOfLValueToProperType(*this, addr, 2387 CGM.getTypes().ConvertTypeForMem(type), 2388 field->getName()); 2389 2390 if (field->hasAttr<AnnotateAttr>()) 2391 addr = EmitFieldAnnotations(field, addr); 2392 2393 LValue LV = MakeAddrLValue(addr, type, alignment); 2394 LV.getQuals().addCVRQualifiers(cvr); 2395 2396 // __weak attribute on a field is ignored. 2397 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak) 2398 LV.getQuals().removeObjCGCAttr(); 2399 2400 // Fields of may_alias structs act like 'char' for TBAA purposes. 2401 // FIXME: this should get propagated down through anonymous structs 2402 // and unions. 2403 if (mayAlias && LV.getTBAAInfo()) 2404 LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy)); 2405 2406 return LV; 2407 } 2408 2409 LValue 2410 CodeGenFunction::EmitLValueForFieldInitialization(LValue Base, 2411 const FieldDecl *Field) { 2412 QualType FieldType = Field->getType(); 2413 2414 if (!FieldType->isReferenceType()) 2415 return EmitLValueForField(Base, Field); 2416 2417 const CGRecordLayout &RL = 2418 CGM.getTypes().getCGRecordLayout(Field->getParent()); 2419 unsigned idx = RL.getLLVMFieldNo(Field); 2420 llvm::Value *V = Builder.CreateStructGEP(Base.getAddress(), idx); 2421 assert(!FieldType.getObjCGCAttr() && "fields cannot have GC attrs"); 2422 2423 // Make sure that the address is pointing to the right type. This is critical 2424 // for both unions and structs. A union needs a bitcast, a struct element 2425 // will need a bitcast if the LLVM type laid out doesn't match the desired 2426 // type. 2427 llvm::Type *llvmType = ConvertTypeForMem(FieldType); 2428 V = EmitBitCastOfLValueToProperType(*this, V, llvmType, Field->getName()); 2429 2430 CharUnits Alignment = getContext().getDeclAlign(Field); 2431 2432 // FIXME: It should be impossible to have an LValue without alignment for a 2433 // complete type. 2434 if (!Base.getAlignment().isZero()) 2435 Alignment = std::min(Alignment, Base.getAlignment()); 2436 2437 return MakeAddrLValue(V, FieldType, Alignment); 2438 } 2439 2440 LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){ 2441 if (E->isFileScope()) { 2442 llvm::Value *GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E); 2443 return MakeAddrLValue(GlobalPtr, E->getType()); 2444 } 2445 if (E->getType()->isVariablyModifiedType()) 2446 // make sure to emit the VLA size. 2447 EmitVariablyModifiedType(E->getType()); 2448 2449 llvm::Value *DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral"); 2450 const Expr *InitExpr = E->getInitializer(); 2451 LValue Result = MakeAddrLValue(DeclPtr, E->getType()); 2452 2453 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(), 2454 /*Init*/ true); 2455 2456 return Result; 2457 } 2458 2459 LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) { 2460 if (!E->isGLValue()) 2461 // Initializing an aggregate temporary in C++11: T{...}. 2462 return EmitAggExprToLValue(E); 2463 2464 // An lvalue initializer list must be initializing a reference. 2465 assert(E->getNumInits() == 1 && "reference init with multiple values"); 2466 return EmitLValue(E->getInit(0)); 2467 } 2468 2469 LValue CodeGenFunction:: 2470 EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) { 2471 if (!expr->isGLValue()) { 2472 // ?: here should be an aggregate. 2473 assert((hasAggregateLLVMType(expr->getType()) && 2474 !expr->getType()->isAnyComplexType()) && 2475 "Unexpected conditional operator!"); 2476 return EmitAggExprToLValue(expr); 2477 } 2478 2479 OpaqueValueMapping binding(*this, expr); 2480 2481 const Expr *condExpr = expr->getCond(); 2482 bool CondExprBool; 2483 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) { 2484 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr(); 2485 if (!CondExprBool) std::swap(live, dead); 2486 2487 if (!ContainsLabel(dead)) 2488 return EmitLValue(live); 2489 } 2490 2491 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true"); 2492 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false"); 2493 llvm::BasicBlock *contBlock = createBasicBlock("cond.end"); 2494 2495 ConditionalEvaluation eval(*this); 2496 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock); 2497 2498 // Any temporaries created here are conditional. 2499 EmitBlock(lhsBlock); 2500 eval.begin(*this); 2501 LValue lhs = EmitLValue(expr->getTrueExpr()); 2502 eval.end(*this); 2503 2504 if (!lhs.isSimple()) 2505 return EmitUnsupportedLValue(expr, "conditional operator"); 2506 2507 lhsBlock = Builder.GetInsertBlock(); 2508 Builder.CreateBr(contBlock); 2509 2510 // Any temporaries created here are conditional. 2511 EmitBlock(rhsBlock); 2512 eval.begin(*this); 2513 LValue rhs = EmitLValue(expr->getFalseExpr()); 2514 eval.end(*this); 2515 if (!rhs.isSimple()) 2516 return EmitUnsupportedLValue(expr, "conditional operator"); 2517 rhsBlock = Builder.GetInsertBlock(); 2518 2519 EmitBlock(contBlock); 2520 2521 llvm::PHINode *phi = Builder.CreatePHI(lhs.getAddress()->getType(), 2, 2522 "cond-lvalue"); 2523 phi->addIncoming(lhs.getAddress(), lhsBlock); 2524 phi->addIncoming(rhs.getAddress(), rhsBlock); 2525 return MakeAddrLValue(phi, expr->getType()); 2526 } 2527 2528 /// EmitCastLValue - Casts are never lvalues unless that cast is to a reference 2529 /// type. If the cast is to a reference, we can have the usual lvalue result, 2530 /// otherwise if a cast is needed by the code generator in an lvalue context, 2531 /// then it must mean that we need the address of an aggregate in order to 2532 /// access one of its members. This can happen for all the reasons that casts 2533 /// are permitted with aggregate result, including noop aggregate casts, and 2534 /// cast from scalar to union. 2535 LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) { 2536 switch (E->getCastKind()) { 2537 case CK_ToVoid: 2538 return EmitUnsupportedLValue(E, "unexpected cast lvalue"); 2539 2540 case CK_Dependent: 2541 llvm_unreachable("dependent cast kind in IR gen!"); 2542 2543 case CK_BuiltinFnToFnPtr: 2544 llvm_unreachable("builtin functions are handled elsewhere"); 2545 2546 // These two casts are currently treated as no-ops, although they could 2547 // potentially be real operations depending on the target's ABI. 2548 case CK_NonAtomicToAtomic: 2549 case CK_AtomicToNonAtomic: 2550 2551 case CK_NoOp: 2552 case CK_LValueToRValue: 2553 if (!E->getSubExpr()->Classify(getContext()).isPRValue() 2554 || E->getType()->isRecordType()) 2555 return EmitLValue(E->getSubExpr()); 2556 // Fall through to synthesize a temporary. 2557 2558 case CK_BitCast: 2559 case CK_ArrayToPointerDecay: 2560 case CK_FunctionToPointerDecay: 2561 case CK_NullToMemberPointer: 2562 case CK_NullToPointer: 2563 case CK_IntegralToPointer: 2564 case CK_PointerToIntegral: 2565 case CK_PointerToBoolean: 2566 case CK_VectorSplat: 2567 case CK_IntegralCast: 2568 case CK_IntegralToBoolean: 2569 case CK_IntegralToFloating: 2570 case CK_FloatingToIntegral: 2571 case CK_FloatingToBoolean: 2572 case CK_FloatingCast: 2573 case CK_FloatingRealToComplex: 2574 case CK_FloatingComplexToReal: 2575 case CK_FloatingComplexToBoolean: 2576 case CK_FloatingComplexCast: 2577 case CK_FloatingComplexToIntegralComplex: 2578 case CK_IntegralRealToComplex: 2579 case CK_IntegralComplexToReal: 2580 case CK_IntegralComplexToBoolean: 2581 case CK_IntegralComplexCast: 2582 case CK_IntegralComplexToFloatingComplex: 2583 case CK_DerivedToBaseMemberPointer: 2584 case CK_BaseToDerivedMemberPointer: 2585 case CK_MemberPointerToBoolean: 2586 case CK_ReinterpretMemberPointer: 2587 case CK_AnyPointerToBlockPointerCast: 2588 case CK_ARCProduceObject: 2589 case CK_ARCConsumeObject: 2590 case CK_ARCReclaimReturnedObject: 2591 case CK_ARCExtendBlockObject: 2592 case CK_CopyAndAutoreleaseBlockObject: { 2593 // These casts only produce lvalues when we're binding a reference to a 2594 // temporary realized from a (converted) pure rvalue. Emit the expression 2595 // as a value, copy it into a temporary, and return an lvalue referring to 2596 // that temporary. 2597 llvm::Value *V = CreateMemTemp(E->getType(), "ref.temp"); 2598 EmitAnyExprToMem(E, V, E->getType().getQualifiers(), false); 2599 return MakeAddrLValue(V, E->getType()); 2600 } 2601 2602 case CK_Dynamic: { 2603 LValue LV = EmitLValue(E->getSubExpr()); 2604 llvm::Value *V = LV.getAddress(); 2605 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(E); 2606 return MakeAddrLValue(EmitDynamicCast(V, DCE), E->getType()); 2607 } 2608 2609 case CK_ConstructorConversion: 2610 case CK_UserDefinedConversion: 2611 case CK_CPointerToObjCPointerCast: 2612 case CK_BlockPointerToObjCPointerCast: 2613 return EmitLValue(E->getSubExpr()); 2614 2615 case CK_UncheckedDerivedToBase: 2616 case CK_DerivedToBase: { 2617 const RecordType *DerivedClassTy = 2618 E->getSubExpr()->getType()->getAs<RecordType>(); 2619 CXXRecordDecl *DerivedClassDecl = 2620 cast<CXXRecordDecl>(DerivedClassTy->getDecl()); 2621 2622 LValue LV = EmitLValue(E->getSubExpr()); 2623 llvm::Value *This = LV.getAddress(); 2624 2625 // Perform the derived-to-base conversion 2626 llvm::Value *Base = 2627 GetAddressOfBaseClass(This, DerivedClassDecl, 2628 E->path_begin(), E->path_end(), 2629 /*NullCheckValue=*/false); 2630 2631 return MakeAddrLValue(Base, E->getType()); 2632 } 2633 case CK_ToUnion: 2634 return EmitAggExprToLValue(E); 2635 case CK_BaseToDerived: { 2636 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>(); 2637 CXXRecordDecl *DerivedClassDecl = 2638 cast<CXXRecordDecl>(DerivedClassTy->getDecl()); 2639 2640 LValue LV = EmitLValue(E->getSubExpr()); 2641 2642 // Perform the base-to-derived conversion 2643 llvm::Value *Derived = 2644 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl, 2645 E->path_begin(), E->path_end(), 2646 /*NullCheckValue=*/false); 2647 2648 return MakeAddrLValue(Derived, E->getType()); 2649 } 2650 case CK_LValueBitCast: { 2651 // This must be a reinterpret_cast (or c-style equivalent). 2652 const ExplicitCastExpr *CE = cast<ExplicitCastExpr>(E); 2653 2654 LValue LV = EmitLValue(E->getSubExpr()); 2655 llvm::Value *V = Builder.CreateBitCast(LV.getAddress(), 2656 ConvertType(CE->getTypeAsWritten())); 2657 return MakeAddrLValue(V, E->getType()); 2658 } 2659 case CK_ObjCObjectLValueCast: { 2660 LValue LV = EmitLValue(E->getSubExpr()); 2661 QualType ToType = getContext().getLValueReferenceType(E->getType()); 2662 llvm::Value *V = Builder.CreateBitCast(LV.getAddress(), 2663 ConvertType(ToType)); 2664 return MakeAddrLValue(V, E->getType()); 2665 } 2666 case CK_ZeroToOCLEvent: 2667 llvm_unreachable("NULL to OpenCL event lvalue cast is not valid"); 2668 } 2669 2670 llvm_unreachable("Unhandled lvalue cast kind?"); 2671 } 2672 2673 LValue CodeGenFunction::EmitNullInitializationLValue( 2674 const CXXScalarValueInitExpr *E) { 2675 QualType Ty = E->getType(); 2676 LValue LV = MakeAddrLValue(CreateMemTemp(Ty), Ty); 2677 EmitNullInitialization(LV.getAddress(), Ty); 2678 return LV; 2679 } 2680 2681 LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) { 2682 assert(OpaqueValueMappingData::shouldBindAsLValue(e)); 2683 return getOpaqueLValueMapping(e); 2684 } 2685 2686 LValue CodeGenFunction::EmitMaterializeTemporaryExpr( 2687 const MaterializeTemporaryExpr *E) { 2688 RValue RV = EmitReferenceBindingToExpr(E, /*InitializedDecl=*/0); 2689 return MakeAddrLValue(RV.getScalarVal(), E->getType()); 2690 } 2691 2692 RValue CodeGenFunction::EmitRValueForField(LValue LV, 2693 const FieldDecl *FD) { 2694 QualType FT = FD->getType(); 2695 LValue FieldLV = EmitLValueForField(LV, FD); 2696 if (FT->isAnyComplexType()) 2697 return RValue::getComplex( 2698 LoadComplexFromAddr(FieldLV.getAddress(), 2699 FieldLV.isVolatileQualified())); 2700 else if (CodeGenFunction::hasAggregateLLVMType(FT)) 2701 return FieldLV.asAggregateRValue(); 2702 2703 return EmitLoadOfLValue(FieldLV); 2704 } 2705 2706 //===--------------------------------------------------------------------===// 2707 // Expression Emission 2708 //===--------------------------------------------------------------------===// 2709 2710 RValue CodeGenFunction::EmitCallExpr(const CallExpr *E, 2711 ReturnValueSlot ReturnValue) { 2712 if (CGDebugInfo *DI = getDebugInfo()) 2713 DI->EmitLocation(Builder, E->getLocStart()); 2714 2715 // Builtins never have block type. 2716 if (E->getCallee()->getType()->isBlockPointerType()) 2717 return EmitBlockCallExpr(E, ReturnValue); 2718 2719 if (const CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(E)) 2720 return EmitCXXMemberCallExpr(CE, ReturnValue); 2721 2722 if (const CUDAKernelCallExpr *CE = dyn_cast<CUDAKernelCallExpr>(E)) 2723 return EmitCUDAKernelCallExpr(CE, ReturnValue); 2724 2725 const Decl *TargetDecl = E->getCalleeDecl(); 2726 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) { 2727 if (unsigned builtinID = FD->getBuiltinID()) 2728 return EmitBuiltinExpr(FD, builtinID, E); 2729 } 2730 2731 if (const CXXOperatorCallExpr *CE = dyn_cast<CXXOperatorCallExpr>(E)) 2732 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl)) 2733 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue); 2734 2735 if (const CXXPseudoDestructorExpr *PseudoDtor 2736 = dyn_cast<CXXPseudoDestructorExpr>(E->getCallee()->IgnoreParens())) { 2737 QualType DestroyedType = PseudoDtor->getDestroyedType(); 2738 if (getLangOpts().ObjCAutoRefCount && 2739 DestroyedType->isObjCLifetimeType() && 2740 (DestroyedType.getObjCLifetime() == Qualifiers::OCL_Strong || 2741 DestroyedType.getObjCLifetime() == Qualifiers::OCL_Weak)) { 2742 // Automatic Reference Counting: 2743 // If the pseudo-expression names a retainable object with weak or 2744 // strong lifetime, the object shall be released. 2745 Expr *BaseExpr = PseudoDtor->getBase(); 2746 llvm::Value *BaseValue = NULL; 2747 Qualifiers BaseQuals; 2748 2749 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar. 2750 if (PseudoDtor->isArrow()) { 2751 BaseValue = EmitScalarExpr(BaseExpr); 2752 const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>(); 2753 BaseQuals = PTy->getPointeeType().getQualifiers(); 2754 } else { 2755 LValue BaseLV = EmitLValue(BaseExpr); 2756 BaseValue = BaseLV.getAddress(); 2757 QualType BaseTy = BaseExpr->getType(); 2758 BaseQuals = BaseTy.getQualifiers(); 2759 } 2760 2761 switch (PseudoDtor->getDestroyedType().getObjCLifetime()) { 2762 case Qualifiers::OCL_None: 2763 case Qualifiers::OCL_ExplicitNone: 2764 case Qualifiers::OCL_Autoreleasing: 2765 break; 2766 2767 case Qualifiers::OCL_Strong: 2768 EmitARCRelease(Builder.CreateLoad(BaseValue, 2769 PseudoDtor->getDestroyedType().isVolatileQualified()), 2770 /*precise*/ true); 2771 break; 2772 2773 case Qualifiers::OCL_Weak: 2774 EmitARCDestroyWeak(BaseValue); 2775 break; 2776 } 2777 } else { 2778 // C++ [expr.pseudo]p1: 2779 // The result shall only be used as the operand for the function call 2780 // operator (), and the result of such a call has type void. The only 2781 // effect is the evaluation of the postfix-expression before the dot or 2782 // arrow. 2783 EmitScalarExpr(E->getCallee()); 2784 } 2785 2786 return RValue::get(0); 2787 } 2788 2789 llvm::Value *Callee = EmitScalarExpr(E->getCallee()); 2790 return EmitCall(E->getCallee()->getType(), Callee, ReturnValue, 2791 E->arg_begin(), E->arg_end(), TargetDecl); 2792 } 2793 2794 LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) { 2795 // Comma expressions just emit their LHS then their RHS as an l-value. 2796 if (E->getOpcode() == BO_Comma) { 2797 EmitIgnoredExpr(E->getLHS()); 2798 EnsureInsertPoint(); 2799 return EmitLValue(E->getRHS()); 2800 } 2801 2802 if (E->getOpcode() == BO_PtrMemD || 2803 E->getOpcode() == BO_PtrMemI) 2804 return EmitPointerToDataMemberBinaryExpr(E); 2805 2806 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value"); 2807 2808 // Note that in all of these cases, __block variables need the RHS 2809 // evaluated first just in case the variable gets moved by the RHS. 2810 2811 if (!hasAggregateLLVMType(E->getType())) { 2812 switch (E->getLHS()->getType().getObjCLifetime()) { 2813 case Qualifiers::OCL_Strong: 2814 return EmitARCStoreStrong(E, /*ignored*/ false).first; 2815 2816 case Qualifiers::OCL_Autoreleasing: 2817 return EmitARCStoreAutoreleasing(E).first; 2818 2819 // No reason to do any of these differently. 2820 case Qualifiers::OCL_None: 2821 case Qualifiers::OCL_ExplicitNone: 2822 case Qualifiers::OCL_Weak: 2823 break; 2824 } 2825 2826 RValue RV = EmitAnyExpr(E->getRHS()); 2827 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store); 2828 EmitStoreThroughLValue(RV, LV); 2829 return LV; 2830 } 2831 2832 if (E->getType()->isAnyComplexType()) 2833 return EmitComplexAssignmentLValue(E); 2834 2835 return EmitAggExprToLValue(E); 2836 } 2837 2838 LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) { 2839 RValue RV = EmitCallExpr(E); 2840 2841 if (!RV.isScalar()) 2842 return MakeAddrLValue(RV.getAggregateAddr(), E->getType()); 2843 2844 assert(E->getCallReturnType()->isReferenceType() && 2845 "Can't have a scalar return unless the return type is a " 2846 "reference type!"); 2847 2848 return MakeAddrLValue(RV.getScalarVal(), E->getType()); 2849 } 2850 2851 LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) { 2852 // FIXME: This shouldn't require another copy. 2853 return EmitAggExprToLValue(E); 2854 } 2855 2856 LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) { 2857 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor() 2858 && "binding l-value to type which needs a temporary"); 2859 AggValueSlot Slot = CreateAggTemp(E->getType()); 2860 EmitCXXConstructExpr(E, Slot); 2861 return MakeAddrLValue(Slot.getAddr(), E->getType()); 2862 } 2863 2864 LValue 2865 CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) { 2866 return MakeAddrLValue(EmitCXXTypeidExpr(E), E->getType()); 2867 } 2868 2869 llvm::Value *CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) { 2870 return CGM.GetAddrOfUuidDescriptor(E); 2871 } 2872 2873 LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) { 2874 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType()); 2875 } 2876 2877 LValue 2878 CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) { 2879 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue"); 2880 Slot.setExternallyDestructed(); 2881 EmitAggExpr(E->getSubExpr(), Slot); 2882 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddr()); 2883 return MakeAddrLValue(Slot.getAddr(), E->getType()); 2884 } 2885 2886 LValue 2887 CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) { 2888 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue"); 2889 EmitLambdaExpr(E, Slot); 2890 return MakeAddrLValue(Slot.getAddr(), E->getType()); 2891 } 2892 2893 LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) { 2894 RValue RV = EmitObjCMessageExpr(E); 2895 2896 if (!RV.isScalar()) 2897 return MakeAddrLValue(RV.getAggregateAddr(), E->getType()); 2898 2899 assert(E->getMethodDecl()->getResultType()->isReferenceType() && 2900 "Can't have a scalar return unless the return type is a " 2901 "reference type!"); 2902 2903 return MakeAddrLValue(RV.getScalarVal(), E->getType()); 2904 } 2905 2906 LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) { 2907 llvm::Value *V = 2908 CGM.getObjCRuntime().GetSelector(Builder, E->getSelector(), true); 2909 return MakeAddrLValue(V, E->getType()); 2910 } 2911 2912 llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface, 2913 const ObjCIvarDecl *Ivar) { 2914 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar); 2915 } 2916 2917 LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy, 2918 llvm::Value *BaseValue, 2919 const ObjCIvarDecl *Ivar, 2920 unsigned CVRQualifiers) { 2921 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue, 2922 Ivar, CVRQualifiers); 2923 } 2924 2925 LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) { 2926 // FIXME: A lot of the code below could be shared with EmitMemberExpr. 2927 llvm::Value *BaseValue = 0; 2928 const Expr *BaseExpr = E->getBase(); 2929 Qualifiers BaseQuals; 2930 QualType ObjectTy; 2931 if (E->isArrow()) { 2932 BaseValue = EmitScalarExpr(BaseExpr); 2933 ObjectTy = BaseExpr->getType()->getPointeeType(); 2934 BaseQuals = ObjectTy.getQualifiers(); 2935 } else { 2936 LValue BaseLV = EmitLValue(BaseExpr); 2937 // FIXME: this isn't right for bitfields. 2938 BaseValue = BaseLV.getAddress(); 2939 ObjectTy = BaseExpr->getType(); 2940 BaseQuals = ObjectTy.getQualifiers(); 2941 } 2942 2943 LValue LV = 2944 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(), 2945 BaseQuals.getCVRQualifiers()); 2946 setObjCGCLValueClass(getContext(), E, LV); 2947 return LV; 2948 } 2949 2950 LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) { 2951 // Can only get l-value for message expression returning aggregate type 2952 RValue RV = EmitAnyExprToTemp(E); 2953 return MakeAddrLValue(RV.getAggregateAddr(), E->getType()); 2954 } 2955 2956 RValue CodeGenFunction::EmitCall(QualType CalleeType, llvm::Value *Callee, 2957 ReturnValueSlot ReturnValue, 2958 CallExpr::const_arg_iterator ArgBeg, 2959 CallExpr::const_arg_iterator ArgEnd, 2960 const Decl *TargetDecl) { 2961 // Get the actual function type. The callee type will always be a pointer to 2962 // function type or a block pointer type. 2963 assert(CalleeType->isFunctionPointerType() && 2964 "Call must have function pointer type!"); 2965 2966 CalleeType = getContext().getCanonicalType(CalleeType); 2967 2968 const FunctionType *FnType 2969 = cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType()); 2970 2971 CallArgList Args; 2972 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), ArgBeg, ArgEnd); 2973 2974 const CGFunctionInfo &FnInfo = 2975 CGM.getTypes().arrangeFreeFunctionCall(Args, FnType); 2976 2977 // C99 6.5.2.2p6: 2978 // If the expression that denotes the called function has a type 2979 // that does not include a prototype, [the default argument 2980 // promotions are performed]. If the number of arguments does not 2981 // equal the number of parameters, the behavior is undefined. If 2982 // the function is defined with a type that includes a prototype, 2983 // and either the prototype ends with an ellipsis (, ...) or the 2984 // types of the arguments after promotion are not compatible with 2985 // the types of the parameters, the behavior is undefined. If the 2986 // function is defined with a type that does not include a 2987 // prototype, and the types of the arguments after promotion are 2988 // not compatible with those of the parameters after promotion, 2989 // the behavior is undefined [except in some trivial cases]. 2990 // That is, in the general case, we should assume that a call 2991 // through an unprototyped function type works like a *non-variadic* 2992 // call. The way we make this work is to cast to the exact type 2993 // of the promoted arguments. 2994 if (isa<FunctionNoProtoType>(FnType)) { 2995 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo); 2996 CalleeTy = CalleeTy->getPointerTo(); 2997 Callee = Builder.CreateBitCast(Callee, CalleeTy, "callee.knr.cast"); 2998 } 2999 3000 return EmitCall(FnInfo, Callee, ReturnValue, Args, TargetDecl); 3001 } 3002 3003 LValue CodeGenFunction:: 3004 EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) { 3005 llvm::Value *BaseV; 3006 if (E->getOpcode() == BO_PtrMemI) 3007 BaseV = EmitScalarExpr(E->getLHS()); 3008 else 3009 BaseV = EmitLValue(E->getLHS()).getAddress(); 3010 3011 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS()); 3012 3013 const MemberPointerType *MPT 3014 = E->getRHS()->getType()->getAs<MemberPointerType>(); 3015 3016 llvm::Value *AddV = 3017 CGM.getCXXABI().EmitMemberDataPointerAddress(*this, BaseV, OffsetV, MPT); 3018 3019 return MakeAddrLValue(AddV, MPT->getPointeeType()); 3020 } 3021 3022 static void 3023 EmitAtomicOp(CodeGenFunction &CGF, AtomicExpr *E, llvm::Value *Dest, 3024 llvm::Value *Ptr, llvm::Value *Val1, llvm::Value *Val2, 3025 uint64_t Size, unsigned Align, llvm::AtomicOrdering Order) { 3026 llvm::AtomicRMWInst::BinOp Op = llvm::AtomicRMWInst::Add; 3027 llvm::Instruction::BinaryOps PostOp = (llvm::Instruction::BinaryOps)0; 3028 3029 switch (E->getOp()) { 3030 case AtomicExpr::AO__c11_atomic_init: 3031 llvm_unreachable("Already handled!"); 3032 3033 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 3034 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 3035 case AtomicExpr::AO__atomic_compare_exchange: 3036 case AtomicExpr::AO__atomic_compare_exchange_n: { 3037 // Note that cmpxchg only supports specifying one ordering and 3038 // doesn't support weak cmpxchg, at least at the moment. 3039 llvm::LoadInst *LoadVal1 = CGF.Builder.CreateLoad(Val1); 3040 LoadVal1->setAlignment(Align); 3041 llvm::LoadInst *LoadVal2 = CGF.Builder.CreateLoad(Val2); 3042 LoadVal2->setAlignment(Align); 3043 llvm::AtomicCmpXchgInst *CXI = 3044 CGF.Builder.CreateAtomicCmpXchg(Ptr, LoadVal1, LoadVal2, Order); 3045 CXI->setVolatile(E->isVolatile()); 3046 llvm::StoreInst *StoreVal1 = CGF.Builder.CreateStore(CXI, Val1); 3047 StoreVal1->setAlignment(Align); 3048 llvm::Value *Cmp = CGF.Builder.CreateICmpEQ(CXI, LoadVal1); 3049 CGF.EmitStoreOfScalar(Cmp, CGF.MakeAddrLValue(Dest, E->getType())); 3050 return; 3051 } 3052 3053 case AtomicExpr::AO__c11_atomic_load: 3054 case AtomicExpr::AO__atomic_load_n: 3055 case AtomicExpr::AO__atomic_load: { 3056 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Ptr); 3057 Load->setAtomic(Order); 3058 Load->setAlignment(Size); 3059 Load->setVolatile(E->isVolatile()); 3060 llvm::StoreInst *StoreDest = CGF.Builder.CreateStore(Load, Dest); 3061 StoreDest->setAlignment(Align); 3062 return; 3063 } 3064 3065 case AtomicExpr::AO__c11_atomic_store: 3066 case AtomicExpr::AO__atomic_store: 3067 case AtomicExpr::AO__atomic_store_n: { 3068 assert(!Dest && "Store does not return a value"); 3069 llvm::LoadInst *LoadVal1 = CGF.Builder.CreateLoad(Val1); 3070 LoadVal1->setAlignment(Align); 3071 llvm::StoreInst *Store = CGF.Builder.CreateStore(LoadVal1, Ptr); 3072 Store->setAtomic(Order); 3073 Store->setAlignment(Size); 3074 Store->setVolatile(E->isVolatile()); 3075 return; 3076 } 3077 3078 case AtomicExpr::AO__c11_atomic_exchange: 3079 case AtomicExpr::AO__atomic_exchange_n: 3080 case AtomicExpr::AO__atomic_exchange: 3081 Op = llvm::AtomicRMWInst::Xchg; 3082 break; 3083 3084 case AtomicExpr::AO__atomic_add_fetch: 3085 PostOp = llvm::Instruction::Add; 3086 // Fall through. 3087 case AtomicExpr::AO__c11_atomic_fetch_add: 3088 case AtomicExpr::AO__atomic_fetch_add: 3089 Op = llvm::AtomicRMWInst::Add; 3090 break; 3091 3092 case AtomicExpr::AO__atomic_sub_fetch: 3093 PostOp = llvm::Instruction::Sub; 3094 // Fall through. 3095 case AtomicExpr::AO__c11_atomic_fetch_sub: 3096 case AtomicExpr::AO__atomic_fetch_sub: 3097 Op = llvm::AtomicRMWInst::Sub; 3098 break; 3099 3100 case AtomicExpr::AO__atomic_and_fetch: 3101 PostOp = llvm::Instruction::And; 3102 // Fall through. 3103 case AtomicExpr::AO__c11_atomic_fetch_and: 3104 case AtomicExpr::AO__atomic_fetch_and: 3105 Op = llvm::AtomicRMWInst::And; 3106 break; 3107 3108 case AtomicExpr::AO__atomic_or_fetch: 3109 PostOp = llvm::Instruction::Or; 3110 // Fall through. 3111 case AtomicExpr::AO__c11_atomic_fetch_or: 3112 case AtomicExpr::AO__atomic_fetch_or: 3113 Op = llvm::AtomicRMWInst::Or; 3114 break; 3115 3116 case AtomicExpr::AO__atomic_xor_fetch: 3117 PostOp = llvm::Instruction::Xor; 3118 // Fall through. 3119 case AtomicExpr::AO__c11_atomic_fetch_xor: 3120 case AtomicExpr::AO__atomic_fetch_xor: 3121 Op = llvm::AtomicRMWInst::Xor; 3122 break; 3123 3124 case AtomicExpr::AO__atomic_nand_fetch: 3125 PostOp = llvm::Instruction::And; 3126 // Fall through. 3127 case AtomicExpr::AO__atomic_fetch_nand: 3128 Op = llvm::AtomicRMWInst::Nand; 3129 break; 3130 } 3131 3132 llvm::LoadInst *LoadVal1 = CGF.Builder.CreateLoad(Val1); 3133 LoadVal1->setAlignment(Align); 3134 llvm::AtomicRMWInst *RMWI = 3135 CGF.Builder.CreateAtomicRMW(Op, Ptr, LoadVal1, Order); 3136 RMWI->setVolatile(E->isVolatile()); 3137 3138 // For __atomic_*_fetch operations, perform the operation again to 3139 // determine the value which was written. 3140 llvm::Value *Result = RMWI; 3141 if (PostOp) 3142 Result = CGF.Builder.CreateBinOp(PostOp, RMWI, LoadVal1); 3143 if (E->getOp() == AtomicExpr::AO__atomic_nand_fetch) 3144 Result = CGF.Builder.CreateNot(Result); 3145 llvm::StoreInst *StoreDest = CGF.Builder.CreateStore(Result, Dest); 3146 StoreDest->setAlignment(Align); 3147 } 3148 3149 // This function emits any expression (scalar, complex, or aggregate) 3150 // into a temporary alloca. 3151 static llvm::Value * 3152 EmitValToTemp(CodeGenFunction &CGF, Expr *E) { 3153 llvm::Value *DeclPtr = CGF.CreateMemTemp(E->getType(), ".atomictmp"); 3154 CGF.EmitAnyExprToMem(E, DeclPtr, E->getType().getQualifiers(), 3155 /*Init*/ true); 3156 return DeclPtr; 3157 } 3158 3159 static RValue ConvertTempToRValue(CodeGenFunction &CGF, QualType Ty, 3160 llvm::Value *Dest) { 3161 if (Ty->isAnyComplexType()) 3162 return RValue::getComplex(CGF.LoadComplexFromAddr(Dest, false)); 3163 if (CGF.hasAggregateLLVMType(Ty)) 3164 return RValue::getAggregate(Dest); 3165 return RValue::get(CGF.EmitLoadOfScalar(CGF.MakeAddrLValue(Dest, Ty))); 3166 } 3167 3168 RValue CodeGenFunction::EmitAtomicExpr(AtomicExpr *E, llvm::Value *Dest) { 3169 QualType AtomicTy = E->getPtr()->getType()->getPointeeType(); 3170 QualType MemTy = AtomicTy; 3171 if (const AtomicType *AT = AtomicTy->getAs<AtomicType>()) 3172 MemTy = AT->getValueType(); 3173 CharUnits sizeChars = getContext().getTypeSizeInChars(AtomicTy); 3174 uint64_t Size = sizeChars.getQuantity(); 3175 CharUnits alignChars = getContext().getTypeAlignInChars(AtomicTy); 3176 unsigned Align = alignChars.getQuantity(); 3177 unsigned MaxInlineWidthInBits = 3178 getContext().getTargetInfo().getMaxAtomicInlineWidth(); 3179 bool UseLibcall = (Size != Align || 3180 getContext().toBits(sizeChars) > MaxInlineWidthInBits); 3181 3182 llvm::Value *Ptr, *Order, *OrderFail = 0, *Val1 = 0, *Val2 = 0; 3183 Ptr = EmitScalarExpr(E->getPtr()); 3184 3185 if (E->getOp() == AtomicExpr::AO__c11_atomic_init) { 3186 assert(!Dest && "Init does not return a value"); 3187 if (!hasAggregateLLVMType(E->getVal1()->getType())) { 3188 QualType PointeeType 3189 = E->getPtr()->getType()->getAs<PointerType>()->getPointeeType(); 3190 EmitScalarInit(EmitScalarExpr(E->getVal1()), 3191 LValue::MakeAddr(Ptr, PointeeType, alignChars, 3192 getContext())); 3193 } else if (E->getType()->isAnyComplexType()) { 3194 EmitComplexExprIntoAddr(E->getVal1(), Ptr, E->isVolatile()); 3195 } else { 3196 AggValueSlot Slot = AggValueSlot::forAddr(Ptr, alignChars, 3197 AtomicTy.getQualifiers(), 3198 AggValueSlot::IsNotDestructed, 3199 AggValueSlot::DoesNotNeedGCBarriers, 3200 AggValueSlot::IsNotAliased); 3201 EmitAggExpr(E->getVal1(), Slot); 3202 } 3203 return RValue::get(0); 3204 } 3205 3206 Order = EmitScalarExpr(E->getOrder()); 3207 3208 switch (E->getOp()) { 3209 case AtomicExpr::AO__c11_atomic_init: 3210 llvm_unreachable("Already handled!"); 3211 3212 case AtomicExpr::AO__c11_atomic_load: 3213 case AtomicExpr::AO__atomic_load_n: 3214 break; 3215 3216 case AtomicExpr::AO__atomic_load: 3217 Dest = EmitScalarExpr(E->getVal1()); 3218 break; 3219 3220 case AtomicExpr::AO__atomic_store: 3221 Val1 = EmitScalarExpr(E->getVal1()); 3222 break; 3223 3224 case AtomicExpr::AO__atomic_exchange: 3225 Val1 = EmitScalarExpr(E->getVal1()); 3226 Dest = EmitScalarExpr(E->getVal2()); 3227 break; 3228 3229 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 3230 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 3231 case AtomicExpr::AO__atomic_compare_exchange_n: 3232 case AtomicExpr::AO__atomic_compare_exchange: 3233 Val1 = EmitScalarExpr(E->getVal1()); 3234 if (E->getOp() == AtomicExpr::AO__atomic_compare_exchange) 3235 Val2 = EmitScalarExpr(E->getVal2()); 3236 else 3237 Val2 = EmitValToTemp(*this, E->getVal2()); 3238 OrderFail = EmitScalarExpr(E->getOrderFail()); 3239 // Evaluate and discard the 'weak' argument. 3240 if (E->getNumSubExprs() == 6) 3241 EmitScalarExpr(E->getWeak()); 3242 break; 3243 3244 case AtomicExpr::AO__c11_atomic_fetch_add: 3245 case AtomicExpr::AO__c11_atomic_fetch_sub: 3246 if (MemTy->isPointerType()) { 3247 // For pointer arithmetic, we're required to do a bit of math: 3248 // adding 1 to an int* is not the same as adding 1 to a uintptr_t. 3249 // ... but only for the C11 builtins. The GNU builtins expect the 3250 // user to multiply by sizeof(T). 3251 QualType Val1Ty = E->getVal1()->getType(); 3252 llvm::Value *Val1Scalar = EmitScalarExpr(E->getVal1()); 3253 CharUnits PointeeIncAmt = 3254 getContext().getTypeSizeInChars(MemTy->getPointeeType()); 3255 Val1Scalar = Builder.CreateMul(Val1Scalar, CGM.getSize(PointeeIncAmt)); 3256 Val1 = CreateMemTemp(Val1Ty, ".atomictmp"); 3257 EmitStoreOfScalar(Val1Scalar, MakeAddrLValue(Val1, Val1Ty)); 3258 break; 3259 } 3260 // Fall through. 3261 case AtomicExpr::AO__atomic_fetch_add: 3262 case AtomicExpr::AO__atomic_fetch_sub: 3263 case AtomicExpr::AO__atomic_add_fetch: 3264 case AtomicExpr::AO__atomic_sub_fetch: 3265 case AtomicExpr::AO__c11_atomic_store: 3266 case AtomicExpr::AO__c11_atomic_exchange: 3267 case AtomicExpr::AO__atomic_store_n: 3268 case AtomicExpr::AO__atomic_exchange_n: 3269 case AtomicExpr::AO__c11_atomic_fetch_and: 3270 case AtomicExpr::AO__c11_atomic_fetch_or: 3271 case AtomicExpr::AO__c11_atomic_fetch_xor: 3272 case AtomicExpr::AO__atomic_fetch_and: 3273 case AtomicExpr::AO__atomic_fetch_or: 3274 case AtomicExpr::AO__atomic_fetch_xor: 3275 case AtomicExpr::AO__atomic_fetch_nand: 3276 case AtomicExpr::AO__atomic_and_fetch: 3277 case AtomicExpr::AO__atomic_or_fetch: 3278 case AtomicExpr::AO__atomic_xor_fetch: 3279 case AtomicExpr::AO__atomic_nand_fetch: 3280 Val1 = EmitValToTemp(*this, E->getVal1()); 3281 break; 3282 } 3283 3284 if (!E->getType()->isVoidType() && !Dest) 3285 Dest = CreateMemTemp(E->getType(), ".atomicdst"); 3286 3287 // Use a library call. See: http://gcc.gnu.org/wiki/Atomic/GCCMM/LIbrary . 3288 if (UseLibcall) { 3289 3290 SmallVector<QualType, 5> Params; 3291 CallArgList Args; 3292 // Size is always the first parameter 3293 Args.add(RValue::get(llvm::ConstantInt::get(SizeTy, Size)), 3294 getContext().getSizeType()); 3295 // Atomic address is always the second parameter 3296 Args.add(RValue::get(EmitCastToVoidPtr(Ptr)), 3297 getContext().VoidPtrTy); 3298 3299 const char* LibCallName; 3300 QualType RetTy = getContext().VoidTy; 3301 switch (E->getOp()) { 3302 // There is only one libcall for compare an exchange, because there is no 3303 // optimisation benefit possible from a libcall version of a weak compare 3304 // and exchange. 3305 // bool __atomic_compare_exchange(size_t size, void *obj, void *expected, 3306 // void *desired, int success, int failure) 3307 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 3308 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 3309 case AtomicExpr::AO__atomic_compare_exchange: 3310 case AtomicExpr::AO__atomic_compare_exchange_n: 3311 LibCallName = "__atomic_compare_exchange"; 3312 RetTy = getContext().BoolTy; 3313 Args.add(RValue::get(EmitCastToVoidPtr(Val1)), 3314 getContext().VoidPtrTy); 3315 Args.add(RValue::get(EmitCastToVoidPtr(Val2)), 3316 getContext().VoidPtrTy); 3317 Args.add(RValue::get(Order), 3318 getContext().IntTy); 3319 Order = OrderFail; 3320 break; 3321 // void __atomic_exchange(size_t size, void *mem, void *val, void *return, 3322 // int order) 3323 case AtomicExpr::AO__c11_atomic_exchange: 3324 case AtomicExpr::AO__atomic_exchange_n: 3325 case AtomicExpr::AO__atomic_exchange: 3326 LibCallName = "__atomic_exchange"; 3327 Args.add(RValue::get(EmitCastToVoidPtr(Val1)), 3328 getContext().VoidPtrTy); 3329 Args.add(RValue::get(EmitCastToVoidPtr(Dest)), 3330 getContext().VoidPtrTy); 3331 break; 3332 // void __atomic_store(size_t size, void *mem, void *val, int order) 3333 case AtomicExpr::AO__c11_atomic_store: 3334 case AtomicExpr::AO__atomic_store: 3335 case AtomicExpr::AO__atomic_store_n: 3336 LibCallName = "__atomic_store"; 3337 Args.add(RValue::get(EmitCastToVoidPtr(Val1)), 3338 getContext().VoidPtrTy); 3339 break; 3340 // void __atomic_load(size_t size, void *mem, void *return, int order) 3341 case AtomicExpr::AO__c11_atomic_load: 3342 case AtomicExpr::AO__atomic_load: 3343 case AtomicExpr::AO__atomic_load_n: 3344 LibCallName = "__atomic_load"; 3345 Args.add(RValue::get(EmitCastToVoidPtr(Dest)), 3346 getContext().VoidPtrTy); 3347 break; 3348 #if 0 3349 // These are only defined for 1-16 byte integers. It is not clear what 3350 // their semantics would be on anything else... 3351 case AtomicExpr::Add: LibCallName = "__atomic_fetch_add_generic"; break; 3352 case AtomicExpr::Sub: LibCallName = "__atomic_fetch_sub_generic"; break; 3353 case AtomicExpr::And: LibCallName = "__atomic_fetch_and_generic"; break; 3354 case AtomicExpr::Or: LibCallName = "__atomic_fetch_or_generic"; break; 3355 case AtomicExpr::Xor: LibCallName = "__atomic_fetch_xor_generic"; break; 3356 #endif 3357 default: return EmitUnsupportedRValue(E, "atomic library call"); 3358 } 3359 // order is always the last parameter 3360 Args.add(RValue::get(Order), 3361 getContext().IntTy); 3362 3363 const CGFunctionInfo &FuncInfo = 3364 CGM.getTypes().arrangeFreeFunctionCall(RetTy, Args, 3365 FunctionType::ExtInfo(), RequiredArgs::All); 3366 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FuncInfo); 3367 llvm::Constant *Func = CGM.CreateRuntimeFunction(FTy, LibCallName); 3368 RValue Res = EmitCall(FuncInfo, Func, ReturnValueSlot(), Args); 3369 if (E->isCmpXChg()) 3370 return Res; 3371 if (E->getType()->isVoidType()) 3372 return RValue::get(0); 3373 return ConvertTempToRValue(*this, E->getType(), Dest); 3374 } 3375 3376 bool IsStore = E->getOp() == AtomicExpr::AO__c11_atomic_store || 3377 E->getOp() == AtomicExpr::AO__atomic_store || 3378 E->getOp() == AtomicExpr::AO__atomic_store_n; 3379 bool IsLoad = E->getOp() == AtomicExpr::AO__c11_atomic_load || 3380 E->getOp() == AtomicExpr::AO__atomic_load || 3381 E->getOp() == AtomicExpr::AO__atomic_load_n; 3382 3383 llvm::Type *IPtrTy = 3384 llvm::IntegerType::get(getLLVMContext(), Size * 8)->getPointerTo(); 3385 llvm::Value *OrigDest = Dest; 3386 Ptr = Builder.CreateBitCast(Ptr, IPtrTy); 3387 if (Val1) Val1 = Builder.CreateBitCast(Val1, IPtrTy); 3388 if (Val2) Val2 = Builder.CreateBitCast(Val2, IPtrTy); 3389 if (Dest && !E->isCmpXChg()) Dest = Builder.CreateBitCast(Dest, IPtrTy); 3390 3391 if (isa<llvm::ConstantInt>(Order)) { 3392 int ord = cast<llvm::ConstantInt>(Order)->getZExtValue(); 3393 switch (ord) { 3394 case 0: // memory_order_relaxed 3395 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align, 3396 llvm::Monotonic); 3397 break; 3398 case 1: // memory_order_consume 3399 case 2: // memory_order_acquire 3400 if (IsStore) 3401 break; // Avoid crashing on code with undefined behavior 3402 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align, 3403 llvm::Acquire); 3404 break; 3405 case 3: // memory_order_release 3406 if (IsLoad) 3407 break; // Avoid crashing on code with undefined behavior 3408 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align, 3409 llvm::Release); 3410 break; 3411 case 4: // memory_order_acq_rel 3412 if (IsLoad || IsStore) 3413 break; // Avoid crashing on code with undefined behavior 3414 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align, 3415 llvm::AcquireRelease); 3416 break; 3417 case 5: // memory_order_seq_cst 3418 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align, 3419 llvm::SequentiallyConsistent); 3420 break; 3421 default: // invalid order 3422 // We should not ever get here normally, but it's hard to 3423 // enforce that in general. 3424 break; 3425 } 3426 if (E->getType()->isVoidType()) 3427 return RValue::get(0); 3428 return ConvertTempToRValue(*this, E->getType(), OrigDest); 3429 } 3430 3431 // Long case, when Order isn't obviously constant. 3432 3433 // Create all the relevant BB's 3434 llvm::BasicBlock *MonotonicBB = 0, *AcquireBB = 0, *ReleaseBB = 0, 3435 *AcqRelBB = 0, *SeqCstBB = 0; 3436 MonotonicBB = createBasicBlock("monotonic", CurFn); 3437 if (!IsStore) 3438 AcquireBB = createBasicBlock("acquire", CurFn); 3439 if (!IsLoad) 3440 ReleaseBB = createBasicBlock("release", CurFn); 3441 if (!IsLoad && !IsStore) 3442 AcqRelBB = createBasicBlock("acqrel", CurFn); 3443 SeqCstBB = createBasicBlock("seqcst", CurFn); 3444 llvm::BasicBlock *ContBB = createBasicBlock("atomic.continue", CurFn); 3445 3446 // Create the switch for the split 3447 // MonotonicBB is arbitrarily chosen as the default case; in practice, this 3448 // doesn't matter unless someone is crazy enough to use something that 3449 // doesn't fold to a constant for the ordering. 3450 Order = Builder.CreateIntCast(Order, Builder.getInt32Ty(), false); 3451 llvm::SwitchInst *SI = Builder.CreateSwitch(Order, MonotonicBB); 3452 3453 // Emit all the different atomics 3454 Builder.SetInsertPoint(MonotonicBB); 3455 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align, 3456 llvm::Monotonic); 3457 Builder.CreateBr(ContBB); 3458 if (!IsStore) { 3459 Builder.SetInsertPoint(AcquireBB); 3460 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align, 3461 llvm::Acquire); 3462 Builder.CreateBr(ContBB); 3463 SI->addCase(Builder.getInt32(1), AcquireBB); 3464 SI->addCase(Builder.getInt32(2), AcquireBB); 3465 } 3466 if (!IsLoad) { 3467 Builder.SetInsertPoint(ReleaseBB); 3468 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align, 3469 llvm::Release); 3470 Builder.CreateBr(ContBB); 3471 SI->addCase(Builder.getInt32(3), ReleaseBB); 3472 } 3473 if (!IsLoad && !IsStore) { 3474 Builder.SetInsertPoint(AcqRelBB); 3475 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align, 3476 llvm::AcquireRelease); 3477 Builder.CreateBr(ContBB); 3478 SI->addCase(Builder.getInt32(4), AcqRelBB); 3479 } 3480 Builder.SetInsertPoint(SeqCstBB); 3481 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align, 3482 llvm::SequentiallyConsistent); 3483 Builder.CreateBr(ContBB); 3484 SI->addCase(Builder.getInt32(5), SeqCstBB); 3485 3486 // Cleanup and return 3487 Builder.SetInsertPoint(ContBB); 3488 if (E->getType()->isVoidType()) 3489 return RValue::get(0); 3490 return ConvertTempToRValue(*this, E->getType(), OrigDest); 3491 } 3492 3493 void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) { 3494 assert(Val->getType()->isFPOrFPVectorTy()); 3495 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val)) 3496 return; 3497 3498 llvm::MDBuilder MDHelper(getLLVMContext()); 3499 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy); 3500 3501 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node); 3502 } 3503 3504 namespace { 3505 struct LValueOrRValue { 3506 LValue LV; 3507 RValue RV; 3508 }; 3509 } 3510 3511 static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF, 3512 const PseudoObjectExpr *E, 3513 bool forLValue, 3514 AggValueSlot slot) { 3515 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques; 3516 3517 // Find the result expression, if any. 3518 const Expr *resultExpr = E->getResultExpr(); 3519 LValueOrRValue result; 3520 3521 for (PseudoObjectExpr::const_semantics_iterator 3522 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) { 3523 const Expr *semantic = *i; 3524 3525 // If this semantic expression is an opaque value, bind it 3526 // to the result of its source expression. 3527 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) { 3528 3529 // If this is the result expression, we may need to evaluate 3530 // directly into the slot. 3531 typedef CodeGenFunction::OpaqueValueMappingData OVMA; 3532 OVMA opaqueData; 3533 if (ov == resultExpr && ov->isRValue() && !forLValue && 3534 CodeGenFunction::hasAggregateLLVMType(ov->getType()) && 3535 !ov->getType()->isAnyComplexType()) { 3536 CGF.EmitAggExpr(ov->getSourceExpr(), slot); 3537 3538 LValue LV = CGF.MakeAddrLValue(slot.getAddr(), ov->getType()); 3539 opaqueData = OVMA::bind(CGF, ov, LV); 3540 result.RV = slot.asRValue(); 3541 3542 // Otherwise, emit as normal. 3543 } else { 3544 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr()); 3545 3546 // If this is the result, also evaluate the result now. 3547 if (ov == resultExpr) { 3548 if (forLValue) 3549 result.LV = CGF.EmitLValue(ov); 3550 else 3551 result.RV = CGF.EmitAnyExpr(ov, slot); 3552 } 3553 } 3554 3555 opaques.push_back(opaqueData); 3556 3557 // Otherwise, if the expression is the result, evaluate it 3558 // and remember the result. 3559 } else if (semantic == resultExpr) { 3560 if (forLValue) 3561 result.LV = CGF.EmitLValue(semantic); 3562 else 3563 result.RV = CGF.EmitAnyExpr(semantic, slot); 3564 3565 // Otherwise, evaluate the expression in an ignored context. 3566 } else { 3567 CGF.EmitIgnoredExpr(semantic); 3568 } 3569 } 3570 3571 // Unbind all the opaques now. 3572 for (unsigned i = 0, e = opaques.size(); i != e; ++i) 3573 opaques[i].unbind(CGF); 3574 3575 return result; 3576 } 3577 3578 RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E, 3579 AggValueSlot slot) { 3580 return emitPseudoObjectExpr(*this, E, false, slot).RV; 3581 } 3582 3583 LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) { 3584 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV; 3585 } 3586