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