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