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 "CGCXXABI.h" 15 #include "CGCall.h" 16 #include "CGCleanup.h" 17 #include "CGDebugInfo.h" 18 #include "CGObjCRuntime.h" 19 #include "CGOpenMPRuntime.h" 20 #include "CGRecordLayout.h" 21 #include "CodeGenFunction.h" 22 #include "CodeGenModule.h" 23 #include "ConstantEmitter.h" 24 #include "TargetInfo.h" 25 #include "clang/AST/ASTContext.h" 26 #include "clang/AST/Attr.h" 27 #include "clang/AST/DeclObjC.h" 28 #include "clang/AST/NSAPI.h" 29 #include "clang/Frontend/CodeGenOptions.h" 30 #include "llvm/ADT/Hashing.h" 31 #include "llvm/ADT/StringExtras.h" 32 #include "llvm/IR/DataLayout.h" 33 #include "llvm/IR/Intrinsics.h" 34 #include "llvm/IR/LLVMContext.h" 35 #include "llvm/IR/MDBuilder.h" 36 #include "llvm/Support/ConvertUTF.h" 37 #include "llvm/Support/MathExtras.h" 38 #include "llvm/Support/Path.h" 39 #include "llvm/Transforms/Utils/SanitizerStats.h" 40 41 #include <string> 42 43 using namespace clang; 44 using namespace CodeGen; 45 46 //===--------------------------------------------------------------------===// 47 // Miscellaneous Helper Methods 48 //===--------------------------------------------------------------------===// 49 50 llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) { 51 unsigned addressSpace = 52 cast<llvm::PointerType>(value->getType())->getAddressSpace(); 53 54 llvm::PointerType *destType = Int8PtrTy; 55 if (addressSpace) 56 destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace); 57 58 if (value->getType() == destType) return value; 59 return Builder.CreateBitCast(value, destType); 60 } 61 62 /// CreateTempAlloca - This creates a alloca and inserts it into the entry 63 /// block. 64 Address CodeGenFunction::CreateTempAlloca(llvm::Type *Ty, CharUnits Align, 65 const Twine &Name, 66 llvm::Value *ArraySize, 67 bool CastToDefaultAddrSpace) { 68 auto Alloca = CreateTempAlloca(Ty, Name, ArraySize); 69 Alloca->setAlignment(Align.getQuantity()); 70 llvm::Value *V = Alloca; 71 // Alloca always returns a pointer in alloca address space, which may 72 // be different from the type defined by the language. For example, 73 // in C++ the auto variables are in the default address space. Therefore 74 // cast alloca to the default address space when necessary. 75 if (CastToDefaultAddrSpace && getASTAllocaAddressSpace() != LangAS::Default) { 76 auto DestAddrSpace = getContext().getTargetAddressSpace(LangAS::Default); 77 auto CurIP = Builder.saveIP(); 78 Builder.SetInsertPoint(AllocaInsertPt); 79 V = getTargetHooks().performAddrSpaceCast( 80 *this, V, getASTAllocaAddressSpace(), LangAS::Default, 81 Ty->getPointerTo(DestAddrSpace), /*non-null*/ true); 82 Builder.restoreIP(CurIP); 83 } 84 85 return Address(V, Align); 86 } 87 88 /// CreateTempAlloca - This creates an alloca and inserts it into the entry 89 /// block if \p ArraySize is nullptr, otherwise inserts it at the current 90 /// insertion point of the builder. 91 llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty, 92 const Twine &Name, 93 llvm::Value *ArraySize) { 94 if (ArraySize) 95 return Builder.CreateAlloca(Ty, ArraySize, Name); 96 return new llvm::AllocaInst(Ty, CGM.getDataLayout().getAllocaAddrSpace(), 97 ArraySize, Name, AllocaInsertPt); 98 } 99 100 /// CreateDefaultAlignTempAlloca - This creates an alloca with the 101 /// default alignment of the corresponding LLVM type, which is *not* 102 /// guaranteed to be related in any way to the expected alignment of 103 /// an AST type that might have been lowered to Ty. 104 Address CodeGenFunction::CreateDefaultAlignTempAlloca(llvm::Type *Ty, 105 const Twine &Name) { 106 CharUnits Align = 107 CharUnits::fromQuantity(CGM.getDataLayout().getABITypeAlignment(Ty)); 108 return CreateTempAlloca(Ty, Align, Name); 109 } 110 111 void CodeGenFunction::InitTempAlloca(Address Var, llvm::Value *Init) { 112 assert(isa<llvm::AllocaInst>(Var.getPointer())); 113 auto *Store = new llvm::StoreInst(Init, Var.getPointer()); 114 Store->setAlignment(Var.getAlignment().getQuantity()); 115 llvm::BasicBlock *Block = AllocaInsertPt->getParent(); 116 Block->getInstList().insertAfter(AllocaInsertPt->getIterator(), Store); 117 } 118 119 Address CodeGenFunction::CreateIRTemp(QualType Ty, const Twine &Name) { 120 CharUnits Align = getContext().getTypeAlignInChars(Ty); 121 return CreateTempAlloca(ConvertType(Ty), Align, Name); 122 } 123 124 Address CodeGenFunction::CreateMemTemp(QualType Ty, const Twine &Name, 125 bool CastToDefaultAddrSpace) { 126 // FIXME: Should we prefer the preferred type alignment here? 127 return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name, 128 CastToDefaultAddrSpace); 129 } 130 131 Address CodeGenFunction::CreateMemTemp(QualType Ty, CharUnits Align, 132 const Twine &Name, 133 bool CastToDefaultAddrSpace) { 134 return CreateTempAlloca(ConvertTypeForMem(Ty), Align, Name, nullptr, 135 CastToDefaultAddrSpace); 136 } 137 138 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified 139 /// expression and compare the result against zero, returning an Int1Ty value. 140 llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) { 141 PGO.setCurrentStmt(E); 142 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) { 143 llvm::Value *MemPtr = EmitScalarExpr(E); 144 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT); 145 } 146 147 QualType BoolTy = getContext().BoolTy; 148 SourceLocation Loc = E->getExprLoc(); 149 if (!E->getType()->isAnyComplexType()) 150 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc); 151 152 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(), BoolTy, 153 Loc); 154 } 155 156 /// EmitIgnoredExpr - Emit code to compute the specified expression, 157 /// ignoring the result. 158 void CodeGenFunction::EmitIgnoredExpr(const Expr *E) { 159 if (E->isRValue()) 160 return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true); 161 162 // Just emit it as an l-value and drop the result. 163 EmitLValue(E); 164 } 165 166 /// EmitAnyExpr - Emit code to compute the specified expression which 167 /// can have any type. The result is returned as an RValue struct. 168 /// If this is an aggregate expression, AggSlot indicates where the 169 /// result should be returned. 170 RValue CodeGenFunction::EmitAnyExpr(const Expr *E, 171 AggValueSlot aggSlot, 172 bool ignoreResult) { 173 switch (getEvaluationKind(E->getType())) { 174 case TEK_Scalar: 175 return RValue::get(EmitScalarExpr(E, ignoreResult)); 176 case TEK_Complex: 177 return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult)); 178 case TEK_Aggregate: 179 if (!ignoreResult && aggSlot.isIgnored()) 180 aggSlot = CreateAggTemp(E->getType(), "agg-temp"); 181 EmitAggExpr(E, aggSlot); 182 return aggSlot.asRValue(); 183 } 184 llvm_unreachable("bad evaluation kind"); 185 } 186 187 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will 188 /// always be accessible even if no aggregate location is provided. 189 RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) { 190 AggValueSlot AggSlot = AggValueSlot::ignored(); 191 192 if (hasAggregateEvaluationKind(E->getType())) 193 AggSlot = CreateAggTemp(E->getType(), "agg.tmp"); 194 return EmitAnyExpr(E, AggSlot); 195 } 196 197 /// EmitAnyExprToMem - Evaluate an expression into a given memory 198 /// location. 199 void CodeGenFunction::EmitAnyExprToMem(const Expr *E, 200 Address Location, 201 Qualifiers Quals, 202 bool IsInit) { 203 // FIXME: This function should take an LValue as an argument. 204 switch (getEvaluationKind(E->getType())) { 205 case TEK_Complex: 206 EmitComplexExprIntoLValue(E, MakeAddrLValue(Location, E->getType()), 207 /*isInit*/ false); 208 return; 209 210 case TEK_Aggregate: { 211 EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals, 212 AggValueSlot::IsDestructed_t(IsInit), 213 AggValueSlot::DoesNotNeedGCBarriers, 214 AggValueSlot::IsAliased_t(!IsInit))); 215 return; 216 } 217 218 case TEK_Scalar: { 219 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false)); 220 LValue LV = MakeAddrLValue(Location, E->getType()); 221 EmitStoreThroughLValue(RV, LV); 222 return; 223 } 224 } 225 llvm_unreachable("bad evaluation kind"); 226 } 227 228 static void 229 pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M, 230 const Expr *E, Address ReferenceTemporary) { 231 // Objective-C++ ARC: 232 // If we are binding a reference to a temporary that has ownership, we 233 // need to perform retain/release operations on the temporary. 234 // 235 // FIXME: This should be looking at E, not M. 236 if (auto Lifetime = M->getType().getObjCLifetime()) { 237 switch (Lifetime) { 238 case Qualifiers::OCL_None: 239 case Qualifiers::OCL_ExplicitNone: 240 // Carry on to normal cleanup handling. 241 break; 242 243 case Qualifiers::OCL_Autoreleasing: 244 // Nothing to do; cleaned up by an autorelease pool. 245 return; 246 247 case Qualifiers::OCL_Strong: 248 case Qualifiers::OCL_Weak: 249 switch (StorageDuration Duration = M->getStorageDuration()) { 250 case SD_Static: 251 // Note: we intentionally do not register a cleanup to release 252 // the object on program termination. 253 return; 254 255 case SD_Thread: 256 // FIXME: We should probably register a cleanup in this case. 257 return; 258 259 case SD_Automatic: 260 case SD_FullExpression: 261 CodeGenFunction::Destroyer *Destroy; 262 CleanupKind CleanupKind; 263 if (Lifetime == Qualifiers::OCL_Strong) { 264 const ValueDecl *VD = M->getExtendingDecl(); 265 bool Precise = 266 VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>(); 267 CleanupKind = CGF.getARCCleanupKind(); 268 Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise 269 : &CodeGenFunction::destroyARCStrongImprecise; 270 } else { 271 // __weak objects always get EH cleanups; otherwise, exceptions 272 // could cause really nasty crashes instead of mere leaks. 273 CleanupKind = NormalAndEHCleanup; 274 Destroy = &CodeGenFunction::destroyARCWeak; 275 } 276 if (Duration == SD_FullExpression) 277 CGF.pushDestroy(CleanupKind, ReferenceTemporary, 278 M->getType(), *Destroy, 279 CleanupKind & EHCleanup); 280 else 281 CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary, 282 M->getType(), 283 *Destroy, CleanupKind & EHCleanup); 284 return; 285 286 case SD_Dynamic: 287 llvm_unreachable("temporary cannot have dynamic storage duration"); 288 } 289 llvm_unreachable("unknown storage duration"); 290 } 291 } 292 293 CXXDestructorDecl *ReferenceTemporaryDtor = nullptr; 294 if (const RecordType *RT = 295 E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) { 296 // Get the destructor for the reference temporary. 297 auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 298 if (!ClassDecl->hasTrivialDestructor()) 299 ReferenceTemporaryDtor = ClassDecl->getDestructor(); 300 } 301 302 if (!ReferenceTemporaryDtor) 303 return; 304 305 // Call the destructor for the temporary. 306 switch (M->getStorageDuration()) { 307 case SD_Static: 308 case SD_Thread: { 309 llvm::Constant *CleanupFn; 310 llvm::Constant *CleanupArg; 311 if (E->getType()->isArrayType()) { 312 CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper( 313 ReferenceTemporary, E->getType(), 314 CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions, 315 dyn_cast_or_null<VarDecl>(M->getExtendingDecl())); 316 CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy); 317 } else { 318 CleanupFn = CGF.CGM.getAddrOfCXXStructor(ReferenceTemporaryDtor, 319 StructorType::Complete); 320 CleanupArg = cast<llvm::Constant>(ReferenceTemporary.getPointer()); 321 } 322 CGF.CGM.getCXXABI().registerGlobalDtor( 323 CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg); 324 break; 325 } 326 327 case SD_FullExpression: 328 CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(), 329 CodeGenFunction::destroyCXXObject, 330 CGF.getLangOpts().Exceptions); 331 break; 332 333 case SD_Automatic: 334 CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup, 335 ReferenceTemporary, E->getType(), 336 CodeGenFunction::destroyCXXObject, 337 CGF.getLangOpts().Exceptions); 338 break; 339 340 case SD_Dynamic: 341 llvm_unreachable("temporary cannot have dynamic storage duration"); 342 } 343 } 344 345 static Address createReferenceTemporary(CodeGenFunction &CGF, 346 const MaterializeTemporaryExpr *M, 347 const Expr *Inner) { 348 auto &TCG = CGF.getTargetHooks(); 349 switch (M->getStorageDuration()) { 350 case SD_FullExpression: 351 case SD_Automatic: { 352 // If we have a constant temporary array or record try to promote it into a 353 // constant global under the same rules a normal constant would've been 354 // promoted. This is easier on the optimizer and generally emits fewer 355 // instructions. 356 QualType Ty = Inner->getType(); 357 if (CGF.CGM.getCodeGenOpts().MergeAllConstants && 358 (Ty->isArrayType() || Ty->isRecordType()) && 359 CGF.CGM.isTypeConstant(Ty, true)) 360 if (auto Init = ConstantEmitter(CGF).tryEmitAbstract(Inner, Ty)) { 361 if (auto AddrSpace = CGF.getTarget().getConstantAddressSpace()) { 362 auto AS = AddrSpace.getValue(); 363 auto *GV = new llvm::GlobalVariable( 364 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true, 365 llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp", nullptr, 366 llvm::GlobalValue::NotThreadLocal, 367 CGF.getContext().getTargetAddressSpace(AS)); 368 CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty); 369 GV->setAlignment(alignment.getQuantity()); 370 llvm::Constant *C = GV; 371 if (AS != LangAS::Default) 372 C = TCG.performAddrSpaceCast( 373 CGF.CGM, GV, AS, LangAS::Default, 374 GV->getValueType()->getPointerTo( 375 CGF.getContext().getTargetAddressSpace(LangAS::Default))); 376 // FIXME: Should we put the new global into a COMDAT? 377 return Address(C, alignment); 378 } 379 } 380 return CGF.CreateMemTemp(Ty, "ref.tmp"); 381 } 382 case SD_Thread: 383 case SD_Static: 384 return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner); 385 386 case SD_Dynamic: 387 llvm_unreachable("temporary can't have dynamic storage duration"); 388 } 389 llvm_unreachable("unknown storage duration"); 390 } 391 392 LValue CodeGenFunction:: 393 EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) { 394 const Expr *E = M->GetTemporaryExpr(); 395 396 // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so 397 // as that will cause the lifetime adjustment to be lost for ARC 398 auto ownership = M->getType().getObjCLifetime(); 399 if (ownership != Qualifiers::OCL_None && 400 ownership != Qualifiers::OCL_ExplicitNone) { 401 Address Object = createReferenceTemporary(*this, M, E); 402 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) { 403 Object = Address(llvm::ConstantExpr::getBitCast(Var, 404 ConvertTypeForMem(E->getType()) 405 ->getPointerTo(Object.getAddressSpace())), 406 Object.getAlignment()); 407 408 // createReferenceTemporary will promote the temporary to a global with a 409 // constant initializer if it can. It can only do this to a value of 410 // ARC-manageable type if the value is global and therefore "immune" to 411 // ref-counting operations. Therefore we have no need to emit either a 412 // dynamic initialization or a cleanup and we can just return the address 413 // of the temporary. 414 if (Var->hasInitializer()) 415 return MakeAddrLValue(Object, M->getType(), 416 LValueBaseInfo(AlignmentSource::Decl, false)); 417 418 Var->setInitializer(CGM.EmitNullConstant(E->getType())); 419 } 420 LValue RefTempDst = MakeAddrLValue(Object, M->getType(), 421 LValueBaseInfo(AlignmentSource::Decl, 422 false)); 423 424 switch (getEvaluationKind(E->getType())) { 425 default: llvm_unreachable("expected scalar or aggregate expression"); 426 case TEK_Scalar: 427 EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false); 428 break; 429 case TEK_Aggregate: { 430 EmitAggExpr(E, AggValueSlot::forAddr(Object, 431 E->getType().getQualifiers(), 432 AggValueSlot::IsDestructed, 433 AggValueSlot::DoesNotNeedGCBarriers, 434 AggValueSlot::IsNotAliased)); 435 break; 436 } 437 } 438 439 pushTemporaryCleanup(*this, M, E, Object); 440 return RefTempDst; 441 } 442 443 SmallVector<const Expr *, 2> CommaLHSs; 444 SmallVector<SubobjectAdjustment, 2> Adjustments; 445 E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 446 447 for (const auto &Ignored : CommaLHSs) 448 EmitIgnoredExpr(Ignored); 449 450 if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) { 451 if (opaque->getType()->isRecordType()) { 452 assert(Adjustments.empty()); 453 return EmitOpaqueValueLValue(opaque); 454 } 455 } 456 457 // Create and initialize the reference temporary. 458 Address Object = createReferenceTemporary(*this, M, E); 459 if (auto *Var = dyn_cast<llvm::GlobalVariable>( 460 Object.getPointer()->stripPointerCasts())) { 461 Object = Address(llvm::ConstantExpr::getBitCast( 462 cast<llvm::Constant>(Object.getPointer()), 463 ConvertTypeForMem(E->getType())->getPointerTo()), 464 Object.getAlignment()); 465 // If the temporary is a global and has a constant initializer or is a 466 // constant temporary that we promoted to a global, we may have already 467 // initialized it. 468 if (!Var->hasInitializer()) { 469 Var->setInitializer(CGM.EmitNullConstant(E->getType())); 470 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true); 471 } 472 } else { 473 switch (M->getStorageDuration()) { 474 case SD_Automatic: 475 case SD_FullExpression: 476 if (auto *Size = EmitLifetimeStart( 477 CGM.getDataLayout().getTypeAllocSize(Object.getElementType()), 478 Object.getPointer())) { 479 if (M->getStorageDuration() == SD_Automatic) 480 pushCleanupAfterFullExpr<CallLifetimeEnd>(NormalEHLifetimeMarker, 481 Object, Size); 482 else 483 pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, Object, 484 Size); 485 } 486 break; 487 default: 488 break; 489 } 490 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true); 491 } 492 pushTemporaryCleanup(*this, M, E, Object); 493 494 // Perform derived-to-base casts and/or field accesses, to get from the 495 // temporary object we created (and, potentially, for which we extended 496 // the lifetime) to the subobject we're binding the reference to. 497 for (unsigned I = Adjustments.size(); I != 0; --I) { 498 SubobjectAdjustment &Adjustment = Adjustments[I-1]; 499 switch (Adjustment.Kind) { 500 case SubobjectAdjustment::DerivedToBaseAdjustment: 501 Object = 502 GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass, 503 Adjustment.DerivedToBase.BasePath->path_begin(), 504 Adjustment.DerivedToBase.BasePath->path_end(), 505 /*NullCheckValue=*/ false, E->getExprLoc()); 506 break; 507 508 case SubobjectAdjustment::FieldAdjustment: { 509 LValue LV = MakeAddrLValue(Object, E->getType(), 510 LValueBaseInfo(AlignmentSource::Decl, false)); 511 LV = EmitLValueForField(LV, Adjustment.Field); 512 assert(LV.isSimple() && 513 "materialized temporary field is not a simple lvalue"); 514 Object = LV.getAddress(); 515 break; 516 } 517 518 case SubobjectAdjustment::MemberPointerAdjustment: { 519 llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS); 520 Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr, 521 Adjustment.Ptr.MPT); 522 break; 523 } 524 } 525 } 526 527 return MakeAddrLValue(Object, M->getType(), 528 LValueBaseInfo(AlignmentSource::Decl, false)); 529 } 530 531 RValue 532 CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) { 533 // Emit the expression as an lvalue. 534 LValue LV = EmitLValue(E); 535 assert(LV.isSimple()); 536 llvm::Value *Value = LV.getPointer(); 537 538 if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) { 539 // C++11 [dcl.ref]p5 (as amended by core issue 453): 540 // If a glvalue to which a reference is directly bound designates neither 541 // an existing object or function of an appropriate type nor a region of 542 // storage of suitable size and alignment to contain an object of the 543 // reference's type, the behavior is undefined. 544 QualType Ty = E->getType(); 545 EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty); 546 } 547 548 return RValue::get(Value); 549 } 550 551 552 /// getAccessedFieldNo - Given an encoded value and a result number, return the 553 /// input field number being accessed. 554 unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx, 555 const llvm::Constant *Elts) { 556 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx)) 557 ->getZExtValue(); 558 } 559 560 /// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h. 561 static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low, 562 llvm::Value *High) { 563 llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL); 564 llvm::Value *K47 = Builder.getInt64(47); 565 llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul); 566 llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0); 567 llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul); 568 llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0); 569 return Builder.CreateMul(B1, KMul); 570 } 571 572 bool CodeGenFunction::sanitizePerformTypeCheck() const { 573 return SanOpts.has(SanitizerKind::Null) | 574 SanOpts.has(SanitizerKind::Alignment) | 575 SanOpts.has(SanitizerKind::ObjectSize) | 576 SanOpts.has(SanitizerKind::Vptr); 577 } 578 579 void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, 580 llvm::Value *Ptr, QualType Ty, 581 CharUnits Alignment, 582 SanitizerSet SkippedChecks) { 583 if (!sanitizePerformTypeCheck()) 584 return; 585 586 // Don't check pointers outside the default address space. The null check 587 // isn't correct, the object-size check isn't supported by LLVM, and we can't 588 // communicate the addresses to the runtime handler for the vptr check. 589 if (Ptr->getType()->getPointerAddressSpace()) 590 return; 591 592 // Don't check pointers to volatile data. The behavior here is implementation- 593 // defined. 594 if (Ty.isVolatileQualified()) 595 return; 596 597 SanitizerScope SanScope(this); 598 599 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks; 600 llvm::BasicBlock *Done = nullptr; 601 602 // Quickly determine whether we have a pointer to an alloca. It's possible 603 // to skip null checks, and some alignment checks, for these pointers. This 604 // can reduce compile-time significantly. 605 auto PtrToAlloca = 606 dyn_cast<llvm::AllocaInst>(Ptr->stripPointerCastsNoFollowAliases()); 607 608 llvm::Value *IsNonNull = nullptr; 609 bool IsGuaranteedNonNull = 610 SkippedChecks.has(SanitizerKind::Null) || PtrToAlloca; 611 bool AllowNullPointers = TCK == TCK_DowncastPointer || TCK == TCK_Upcast || 612 TCK == TCK_UpcastToVirtualBase; 613 if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) && 614 !IsGuaranteedNonNull) { 615 // The glvalue must not be an empty glvalue. 616 IsNonNull = Builder.CreateIsNotNull(Ptr); 617 618 // The IR builder can constant-fold the null check if the pointer points to 619 // a constant. 620 IsGuaranteedNonNull = 621 IsNonNull == llvm::ConstantInt::getTrue(getLLVMContext()); 622 623 // Skip the null check if the pointer is known to be non-null. 624 if (!IsGuaranteedNonNull) { 625 if (AllowNullPointers) { 626 // When performing pointer casts, it's OK if the value is null. 627 // Skip the remaining checks in that case. 628 Done = createBasicBlock("null"); 629 llvm::BasicBlock *Rest = createBasicBlock("not.null"); 630 Builder.CreateCondBr(IsNonNull, Rest, Done); 631 EmitBlock(Rest); 632 } else { 633 Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null)); 634 } 635 } 636 } 637 638 if (SanOpts.has(SanitizerKind::ObjectSize) && 639 !SkippedChecks.has(SanitizerKind::ObjectSize) && 640 !Ty->isIncompleteType()) { 641 uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity(); 642 643 // The glvalue must refer to a large enough storage region. 644 // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation 645 // to check this. 646 // FIXME: Get object address space 647 llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy }; 648 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys); 649 llvm::Value *Min = Builder.getFalse(); 650 llvm::Value *NullIsUnknown = Builder.getFalse(); 651 llvm::Value *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy); 652 llvm::Value *LargeEnough = Builder.CreateICmpUGE( 653 Builder.CreateCall(F, {CastAddr, Min, NullIsUnknown}), 654 llvm::ConstantInt::get(IntPtrTy, Size)); 655 Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize)); 656 } 657 658 uint64_t AlignVal = 0; 659 llvm::Value *PtrAsInt = nullptr; 660 661 if (SanOpts.has(SanitizerKind::Alignment) && 662 !SkippedChecks.has(SanitizerKind::Alignment)) { 663 AlignVal = Alignment.getQuantity(); 664 if (!Ty->isIncompleteType() && !AlignVal) 665 AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity(); 666 667 // The glvalue must be suitably aligned. 668 if (AlignVal > 1 && 669 (!PtrToAlloca || PtrToAlloca->getAlignment() < AlignVal)) { 670 PtrAsInt = Builder.CreatePtrToInt(Ptr, IntPtrTy); 671 llvm::Value *Align = Builder.CreateAnd( 672 PtrAsInt, llvm::ConstantInt::get(IntPtrTy, AlignVal - 1)); 673 llvm::Value *Aligned = 674 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0)); 675 Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment)); 676 } 677 } 678 679 if (Checks.size() > 0) { 680 // Make sure we're not losing information. Alignment needs to be a power of 681 // 2 682 assert(!AlignVal || (uint64_t)1 << llvm::Log2_64(AlignVal) == AlignVal); 683 llvm::Constant *StaticData[] = { 684 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(Ty), 685 llvm::ConstantInt::get(Int8Ty, AlignVal ? llvm::Log2_64(AlignVal) : 1), 686 llvm::ConstantInt::get(Int8Ty, TCK)}; 687 EmitCheck(Checks, SanitizerHandler::TypeMismatch, StaticData, 688 PtrAsInt ? PtrAsInt : Ptr); 689 } 690 691 // If possible, check that the vptr indicates that there is a subobject of 692 // type Ty at offset zero within this object. 693 // 694 // C++11 [basic.life]p5,6: 695 // [For storage which does not refer to an object within its lifetime] 696 // The program has undefined behavior if: 697 // -- the [pointer or glvalue] is used to access a non-static data member 698 // or call a non-static member function 699 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 700 if (SanOpts.has(SanitizerKind::Vptr) && 701 !SkippedChecks.has(SanitizerKind::Vptr) && 702 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall || 703 TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference || 704 TCK == TCK_UpcastToVirtualBase) && 705 RD && RD->hasDefinition() && RD->isDynamicClass()) { 706 // Ensure that the pointer is non-null before loading it. If there is no 707 // compile-time guarantee, reuse the run-time null check or emit a new one. 708 if (!IsGuaranteedNonNull) { 709 if (!IsNonNull) 710 IsNonNull = Builder.CreateIsNotNull(Ptr); 711 if (!Done) 712 Done = createBasicBlock("vptr.null"); 713 llvm::BasicBlock *VptrNotNull = createBasicBlock("vptr.not.null"); 714 Builder.CreateCondBr(IsNonNull, VptrNotNull, Done); 715 EmitBlock(VptrNotNull); 716 } 717 718 // Compute a hash of the mangled name of the type. 719 // 720 // FIXME: This is not guaranteed to be deterministic! Move to a 721 // fingerprinting mechanism once LLVM provides one. For the time 722 // being the implementation happens to be deterministic. 723 SmallString<64> MangledName; 724 llvm::raw_svector_ostream Out(MangledName); 725 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(), 726 Out); 727 728 // Blacklist based on the mangled type. 729 if (!CGM.getContext().getSanitizerBlacklist().isBlacklistedType( 730 SanitizerKind::Vptr, Out.str())) { 731 llvm::hash_code TypeHash = hash_value(Out.str()); 732 733 // Load the vptr, and compute hash_16_bytes(TypeHash, vptr). 734 llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash); 735 llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0); 736 Address VPtrAddr(Builder.CreateBitCast(Ptr, VPtrTy), getPointerAlign()); 737 llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr); 738 llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty); 739 740 llvm::Value *Hash = emitHash16Bytes(Builder, Low, High); 741 Hash = Builder.CreateTrunc(Hash, IntPtrTy); 742 743 // Look the hash up in our cache. 744 const int CacheSize = 128; 745 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize); 746 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable, 747 "__ubsan_vptr_type_cache"); 748 llvm::Value *Slot = Builder.CreateAnd(Hash, 749 llvm::ConstantInt::get(IntPtrTy, 750 CacheSize-1)); 751 llvm::Value *Indices[] = { Builder.getInt32(0), Slot }; 752 llvm::Value *CacheVal = 753 Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(Cache, Indices), 754 getPointerAlign()); 755 756 // If the hash isn't in the cache, call a runtime handler to perform the 757 // hard work of checking whether the vptr is for an object of the right 758 // type. This will either fill in the cache and return, or produce a 759 // diagnostic. 760 llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash); 761 llvm::Constant *StaticData[] = { 762 EmitCheckSourceLocation(Loc), 763 EmitCheckTypeDescriptor(Ty), 764 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()), 765 llvm::ConstantInt::get(Int8Ty, TCK) 766 }; 767 llvm::Value *DynamicData[] = { Ptr, Hash }; 768 EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr), 769 SanitizerHandler::DynamicTypeCacheMiss, StaticData, 770 DynamicData); 771 } 772 } 773 774 if (Done) { 775 Builder.CreateBr(Done); 776 EmitBlock(Done); 777 } 778 } 779 780 /// Determine whether this expression refers to a flexible array member in a 781 /// struct. We disable array bounds checks for such members. 782 static bool isFlexibleArrayMemberExpr(const Expr *E) { 783 // For compatibility with existing code, we treat arrays of length 0 or 784 // 1 as flexible array members. 785 const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe(); 786 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 787 if (CAT->getSize().ugt(1)) 788 return false; 789 } else if (!isa<IncompleteArrayType>(AT)) 790 return false; 791 792 E = E->IgnoreParens(); 793 794 // A flexible array member must be the last member in the class. 795 if (const auto *ME = dyn_cast<MemberExpr>(E)) { 796 // FIXME: If the base type of the member expr is not FD->getParent(), 797 // this should not be treated as a flexible array member access. 798 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 799 RecordDecl::field_iterator FI( 800 DeclContext::decl_iterator(const_cast<FieldDecl *>(FD))); 801 return ++FI == FD->getParent()->field_end(); 802 } 803 } else if (const auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) { 804 return IRE->getDecl()->getNextIvar() == nullptr; 805 } 806 807 return false; 808 } 809 810 /// If Base is known to point to the start of an array, return the length of 811 /// that array. Return 0 if the length cannot be determined. 812 static llvm::Value *getArrayIndexingBound( 813 CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) { 814 // For the vector indexing extension, the bound is the number of elements. 815 if (const VectorType *VT = Base->getType()->getAs<VectorType>()) { 816 IndexedType = Base->getType(); 817 return CGF.Builder.getInt32(VT->getNumElements()); 818 } 819 820 Base = Base->IgnoreParens(); 821 822 if (const auto *CE = dyn_cast<CastExpr>(Base)) { 823 if (CE->getCastKind() == CK_ArrayToPointerDecay && 824 !isFlexibleArrayMemberExpr(CE->getSubExpr())) { 825 IndexedType = CE->getSubExpr()->getType(); 826 const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe(); 827 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) 828 return CGF.Builder.getInt(CAT->getSize()); 829 else if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) 830 return CGF.getVLASize(VAT).first; 831 } 832 } 833 834 return nullptr; 835 } 836 837 void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base, 838 llvm::Value *Index, QualType IndexType, 839 bool Accessed) { 840 assert(SanOpts.has(SanitizerKind::ArrayBounds) && 841 "should not be called unless adding bounds checks"); 842 SanitizerScope SanScope(this); 843 844 QualType IndexedType; 845 llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType); 846 if (!Bound) 847 return; 848 849 bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType(); 850 llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned); 851 llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false); 852 853 llvm::Constant *StaticData[] = { 854 EmitCheckSourceLocation(E->getExprLoc()), 855 EmitCheckTypeDescriptor(IndexedType), 856 EmitCheckTypeDescriptor(IndexType) 857 }; 858 llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal) 859 : Builder.CreateICmpULE(IndexVal, BoundVal); 860 EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds), 861 SanitizerHandler::OutOfBounds, StaticData, Index); 862 } 863 864 865 CodeGenFunction::ComplexPairTy CodeGenFunction:: 866 EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV, 867 bool isInc, bool isPre) { 868 ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc()); 869 870 llvm::Value *NextVal; 871 if (isa<llvm::IntegerType>(InVal.first->getType())) { 872 uint64_t AmountVal = isInc ? 1 : -1; 873 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true); 874 875 // Add the inc/dec to the real part. 876 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec"); 877 } else { 878 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType(); 879 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1); 880 if (!isInc) 881 FVal.changeSign(); 882 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal); 883 884 // Add the inc/dec to the real part. 885 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec"); 886 } 887 888 ComplexPairTy IncVal(NextVal, InVal.second); 889 890 // Store the updated result through the lvalue. 891 EmitStoreOfComplex(IncVal, LV, /*init*/ false); 892 893 // If this is a postinc, return the value read from memory, otherwise use the 894 // updated value. 895 return isPre ? IncVal : InVal; 896 } 897 898 void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E, 899 CodeGenFunction *CGF) { 900 // Bind VLAs in the cast type. 901 if (CGF && E->getType()->isVariablyModifiedType()) 902 CGF->EmitVariablyModifiedType(E->getType()); 903 904 if (CGDebugInfo *DI = getModuleDebugInfo()) 905 DI->EmitExplicitCastType(E->getType()); 906 } 907 908 //===----------------------------------------------------------------------===// 909 // LValue Expression Emission 910 //===----------------------------------------------------------------------===// 911 912 /// EmitPointerWithAlignment - Given an expression of pointer type, try to 913 /// derive a more accurate bound on the alignment of the pointer. 914 Address CodeGenFunction::EmitPointerWithAlignment(const Expr *E, 915 LValueBaseInfo *BaseInfo) { 916 // We allow this with ObjC object pointers because of fragile ABIs. 917 assert(E->getType()->isPointerType() || 918 E->getType()->isObjCObjectPointerType()); 919 E = E->IgnoreParens(); 920 921 // Casts: 922 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 923 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE)) 924 CGM.EmitExplicitCastExprType(ECE, this); 925 926 switch (CE->getCastKind()) { 927 // Non-converting casts (but not C's implicit conversion from void*). 928 case CK_BitCast: 929 case CK_NoOp: 930 case CK_AddressSpaceConversion: 931 if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) { 932 if (PtrTy->getPointeeType()->isVoidType()) 933 break; 934 935 LValueBaseInfo InnerInfo; 936 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), &InnerInfo); 937 if (BaseInfo) *BaseInfo = InnerInfo; 938 939 // If this is an explicit bitcast, and the source l-value is 940 // opaque, honor the alignment of the casted-to type. 941 if (isa<ExplicitCastExpr>(CE) && 942 InnerInfo.getAlignmentSource() != AlignmentSource::Decl) { 943 LValueBaseInfo ExpInfo; 944 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(), 945 &ExpInfo); 946 if (BaseInfo) 947 BaseInfo->mergeForCast(ExpInfo); 948 Addr = Address(Addr.getPointer(), Align); 949 } 950 951 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast) && 952 CE->getCastKind() == CK_BitCast) { 953 if (auto PT = E->getType()->getAs<PointerType>()) 954 EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr.getPointer(), 955 /*MayBeNull=*/true, 956 CodeGenFunction::CFITCK_UnrelatedCast, 957 CE->getLocStart()); 958 } 959 return CE->getCastKind() != CK_AddressSpaceConversion 960 ? Builder.CreateBitCast(Addr, ConvertType(E->getType())) 961 : Builder.CreateAddrSpaceCast(Addr, 962 ConvertType(E->getType())); 963 } 964 break; 965 966 // Array-to-pointer decay. 967 case CK_ArrayToPointerDecay: 968 return EmitArrayToPointerDecay(CE->getSubExpr(), BaseInfo); 969 970 // Derived-to-base conversions. 971 case CK_UncheckedDerivedToBase: 972 case CK_DerivedToBase: { 973 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), BaseInfo); 974 auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl(); 975 return GetAddressOfBaseClass(Addr, Derived, 976 CE->path_begin(), CE->path_end(), 977 ShouldNullCheckClassCastValue(CE), 978 CE->getExprLoc()); 979 } 980 981 // TODO: Is there any reason to treat base-to-derived conversions 982 // specially? 983 default: 984 break; 985 } 986 } 987 988 // Unary &. 989 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 990 if (UO->getOpcode() == UO_AddrOf) { 991 LValue LV = EmitLValue(UO->getSubExpr()); 992 if (BaseInfo) *BaseInfo = LV.getBaseInfo(); 993 return LV.getAddress(); 994 } 995 } 996 997 // TODO: conditional operators, comma. 998 999 // Otherwise, use the alignment of the type. 1000 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(), BaseInfo); 1001 return Address(EmitScalarExpr(E), Align); 1002 } 1003 1004 RValue CodeGenFunction::GetUndefRValue(QualType Ty) { 1005 if (Ty->isVoidType()) 1006 return RValue::get(nullptr); 1007 1008 switch (getEvaluationKind(Ty)) { 1009 case TEK_Complex: { 1010 llvm::Type *EltTy = 1011 ConvertType(Ty->castAs<ComplexType>()->getElementType()); 1012 llvm::Value *U = llvm::UndefValue::get(EltTy); 1013 return RValue::getComplex(std::make_pair(U, U)); 1014 } 1015 1016 // If this is a use of an undefined aggregate type, the aggregate must have an 1017 // identifiable address. Just because the contents of the value are undefined 1018 // doesn't mean that the address can't be taken and compared. 1019 case TEK_Aggregate: { 1020 Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp"); 1021 return RValue::getAggregate(DestPtr); 1022 } 1023 1024 case TEK_Scalar: 1025 return RValue::get(llvm::UndefValue::get(ConvertType(Ty))); 1026 } 1027 llvm_unreachable("bad evaluation kind"); 1028 } 1029 1030 RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E, 1031 const char *Name) { 1032 ErrorUnsupported(E, Name); 1033 return GetUndefRValue(E->getType()); 1034 } 1035 1036 LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E, 1037 const char *Name) { 1038 ErrorUnsupported(E, Name); 1039 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType())); 1040 return MakeAddrLValue(Address(llvm::UndefValue::get(Ty), CharUnits::One()), 1041 E->getType()); 1042 } 1043 1044 bool CodeGenFunction::IsWrappedCXXThis(const Expr *Obj) { 1045 const Expr *Base = Obj; 1046 while (!isa<CXXThisExpr>(Base)) { 1047 // The result of a dynamic_cast can be null. 1048 if (isa<CXXDynamicCastExpr>(Base)) 1049 return false; 1050 1051 if (const auto *CE = dyn_cast<CastExpr>(Base)) { 1052 Base = CE->getSubExpr(); 1053 } else if (const auto *PE = dyn_cast<ParenExpr>(Base)) { 1054 Base = PE->getSubExpr(); 1055 } else if (const auto *UO = dyn_cast<UnaryOperator>(Base)) { 1056 if (UO->getOpcode() == UO_Extension) 1057 Base = UO->getSubExpr(); 1058 else 1059 return false; 1060 } else { 1061 return false; 1062 } 1063 } 1064 return true; 1065 } 1066 1067 LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) { 1068 LValue LV; 1069 if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E)) 1070 LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true); 1071 else 1072 LV = EmitLValue(E); 1073 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple()) { 1074 SanitizerSet SkippedChecks; 1075 if (const auto *ME = dyn_cast<MemberExpr>(E)) { 1076 bool IsBaseCXXThis = IsWrappedCXXThis(ME->getBase()); 1077 if (IsBaseCXXThis) 1078 SkippedChecks.set(SanitizerKind::Alignment, true); 1079 if (IsBaseCXXThis || isa<DeclRefExpr>(ME->getBase())) 1080 SkippedChecks.set(SanitizerKind::Null, true); 1081 } 1082 EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(), 1083 E->getType(), LV.getAlignment(), SkippedChecks); 1084 } 1085 return LV; 1086 } 1087 1088 /// EmitLValue - Emit code to compute a designator that specifies the location 1089 /// of the expression. 1090 /// 1091 /// This can return one of two things: a simple address or a bitfield reference. 1092 /// In either case, the LLVM Value* in the LValue structure is guaranteed to be 1093 /// an LLVM pointer type. 1094 /// 1095 /// If this returns a bitfield reference, nothing about the pointee type of the 1096 /// LLVM value is known: For example, it may not be a pointer to an integer. 1097 /// 1098 /// If this returns a normal address, and if the lvalue's C type is fixed size, 1099 /// this method guarantees that the returned pointer type will point to an LLVM 1100 /// type of the same size of the lvalue's type. If the lvalue has a variable 1101 /// length type, this is not possible. 1102 /// 1103 LValue CodeGenFunction::EmitLValue(const Expr *E) { 1104 ApplyDebugLocation DL(*this, E); 1105 switch (E->getStmtClass()) { 1106 default: return EmitUnsupportedLValue(E, "l-value expression"); 1107 1108 case Expr::ObjCPropertyRefExprClass: 1109 llvm_unreachable("cannot emit a property reference directly"); 1110 1111 case Expr::ObjCSelectorExprClass: 1112 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E)); 1113 case Expr::ObjCIsaExprClass: 1114 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E)); 1115 case Expr::BinaryOperatorClass: 1116 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E)); 1117 case Expr::CompoundAssignOperatorClass: { 1118 QualType Ty = E->getType(); 1119 if (const AtomicType *AT = Ty->getAs<AtomicType>()) 1120 Ty = AT->getValueType(); 1121 if (!Ty->isAnyComplexType()) 1122 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E)); 1123 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E)); 1124 } 1125 case Expr::CallExprClass: 1126 case Expr::CXXMemberCallExprClass: 1127 case Expr::CXXOperatorCallExprClass: 1128 case Expr::UserDefinedLiteralClass: 1129 return EmitCallExprLValue(cast<CallExpr>(E)); 1130 case Expr::VAArgExprClass: 1131 return EmitVAArgExprLValue(cast<VAArgExpr>(E)); 1132 case Expr::DeclRefExprClass: 1133 return EmitDeclRefLValue(cast<DeclRefExpr>(E)); 1134 case Expr::ParenExprClass: 1135 return EmitLValue(cast<ParenExpr>(E)->getSubExpr()); 1136 case Expr::GenericSelectionExprClass: 1137 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr()); 1138 case Expr::PredefinedExprClass: 1139 return EmitPredefinedLValue(cast<PredefinedExpr>(E)); 1140 case Expr::StringLiteralClass: 1141 return EmitStringLiteralLValue(cast<StringLiteral>(E)); 1142 case Expr::ObjCEncodeExprClass: 1143 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E)); 1144 case Expr::PseudoObjectExprClass: 1145 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E)); 1146 case Expr::InitListExprClass: 1147 return EmitInitListLValue(cast<InitListExpr>(E)); 1148 case Expr::CXXTemporaryObjectExprClass: 1149 case Expr::CXXConstructExprClass: 1150 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E)); 1151 case Expr::CXXBindTemporaryExprClass: 1152 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E)); 1153 case Expr::CXXUuidofExprClass: 1154 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E)); 1155 case Expr::LambdaExprClass: 1156 return EmitLambdaLValue(cast<LambdaExpr>(E)); 1157 1158 case Expr::ExprWithCleanupsClass: { 1159 const auto *cleanups = cast<ExprWithCleanups>(E); 1160 enterFullExpression(cleanups); 1161 RunCleanupsScope Scope(*this); 1162 LValue LV = EmitLValue(cleanups->getSubExpr()); 1163 if (LV.isSimple()) { 1164 // Defend against branches out of gnu statement expressions surrounded by 1165 // cleanups. 1166 llvm::Value *V = LV.getPointer(); 1167 Scope.ForceCleanup({&V}); 1168 return LValue::MakeAddr(Address(V, LV.getAlignment()), LV.getType(), 1169 getContext(), LV.getBaseInfo(), 1170 LV.getTBAAAccessType()); 1171 } 1172 // FIXME: Is it possible to create an ExprWithCleanups that produces a 1173 // bitfield lvalue or some other non-simple lvalue? 1174 return LV; 1175 } 1176 1177 case Expr::CXXDefaultArgExprClass: 1178 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr()); 1179 case Expr::CXXDefaultInitExprClass: { 1180 CXXDefaultInitExprScope Scope(*this); 1181 return EmitLValue(cast<CXXDefaultInitExpr>(E)->getExpr()); 1182 } 1183 case Expr::CXXTypeidExprClass: 1184 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E)); 1185 1186 case Expr::ObjCMessageExprClass: 1187 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E)); 1188 case Expr::ObjCIvarRefExprClass: 1189 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E)); 1190 case Expr::StmtExprClass: 1191 return EmitStmtExprLValue(cast<StmtExpr>(E)); 1192 case Expr::UnaryOperatorClass: 1193 return EmitUnaryOpLValue(cast<UnaryOperator>(E)); 1194 case Expr::ArraySubscriptExprClass: 1195 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E)); 1196 case Expr::OMPArraySectionExprClass: 1197 return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E)); 1198 case Expr::ExtVectorElementExprClass: 1199 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E)); 1200 case Expr::MemberExprClass: 1201 return EmitMemberExpr(cast<MemberExpr>(E)); 1202 case Expr::CompoundLiteralExprClass: 1203 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E)); 1204 case Expr::ConditionalOperatorClass: 1205 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E)); 1206 case Expr::BinaryConditionalOperatorClass: 1207 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E)); 1208 case Expr::ChooseExprClass: 1209 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr()); 1210 case Expr::OpaqueValueExprClass: 1211 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E)); 1212 case Expr::SubstNonTypeTemplateParmExprClass: 1213 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement()); 1214 case Expr::ImplicitCastExprClass: 1215 case Expr::CStyleCastExprClass: 1216 case Expr::CXXFunctionalCastExprClass: 1217 case Expr::CXXStaticCastExprClass: 1218 case Expr::CXXDynamicCastExprClass: 1219 case Expr::CXXReinterpretCastExprClass: 1220 case Expr::CXXConstCastExprClass: 1221 case Expr::ObjCBridgedCastExprClass: 1222 return EmitCastLValue(cast<CastExpr>(E)); 1223 1224 case Expr::MaterializeTemporaryExprClass: 1225 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E)); 1226 1227 case Expr::CoawaitExprClass: 1228 return EmitCoawaitLValue(cast<CoawaitExpr>(E)); 1229 case Expr::CoyieldExprClass: 1230 return EmitCoyieldLValue(cast<CoyieldExpr>(E)); 1231 } 1232 } 1233 1234 /// Given an object of the given canonical type, can we safely copy a 1235 /// value out of it based on its initializer? 1236 static bool isConstantEmittableObjectType(QualType type) { 1237 assert(type.isCanonical()); 1238 assert(!type->isReferenceType()); 1239 1240 // Must be const-qualified but non-volatile. 1241 Qualifiers qs = type.getLocalQualifiers(); 1242 if (!qs.hasConst() || qs.hasVolatile()) return false; 1243 1244 // Otherwise, all object types satisfy this except C++ classes with 1245 // mutable subobjects or non-trivial copy/destroy behavior. 1246 if (const auto *RT = dyn_cast<RecordType>(type)) 1247 if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) 1248 if (RD->hasMutableFields() || !RD->isTrivial()) 1249 return false; 1250 1251 return true; 1252 } 1253 1254 /// Can we constant-emit a load of a reference to a variable of the 1255 /// given type? This is different from predicates like 1256 /// Decl::isUsableInConstantExpressions because we do want it to apply 1257 /// in situations that don't necessarily satisfy the language's rules 1258 /// for this (e.g. C++'s ODR-use rules). For example, we want to able 1259 /// to do this with const float variables even if those variables 1260 /// aren't marked 'constexpr'. 1261 enum ConstantEmissionKind { 1262 CEK_None, 1263 CEK_AsReferenceOnly, 1264 CEK_AsValueOrReference, 1265 CEK_AsValueOnly 1266 }; 1267 static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) { 1268 type = type.getCanonicalType(); 1269 if (const auto *ref = dyn_cast<ReferenceType>(type)) { 1270 if (isConstantEmittableObjectType(ref->getPointeeType())) 1271 return CEK_AsValueOrReference; 1272 return CEK_AsReferenceOnly; 1273 } 1274 if (isConstantEmittableObjectType(type)) 1275 return CEK_AsValueOnly; 1276 return CEK_None; 1277 } 1278 1279 /// Try to emit a reference to the given value without producing it as 1280 /// an l-value. This is actually more than an optimization: we can't 1281 /// produce an l-value for variables that we never actually captured 1282 /// in a block or lambda, which means const int variables or constexpr 1283 /// literals or similar. 1284 CodeGenFunction::ConstantEmission 1285 CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) { 1286 ValueDecl *value = refExpr->getDecl(); 1287 1288 // The value needs to be an enum constant or a constant variable. 1289 ConstantEmissionKind CEK; 1290 if (isa<ParmVarDecl>(value)) { 1291 CEK = CEK_None; 1292 } else if (auto *var = dyn_cast<VarDecl>(value)) { 1293 CEK = checkVarTypeForConstantEmission(var->getType()); 1294 } else if (isa<EnumConstantDecl>(value)) { 1295 CEK = CEK_AsValueOnly; 1296 } else { 1297 CEK = CEK_None; 1298 } 1299 if (CEK == CEK_None) return ConstantEmission(); 1300 1301 Expr::EvalResult result; 1302 bool resultIsReference; 1303 QualType resultType; 1304 1305 // It's best to evaluate all the way as an r-value if that's permitted. 1306 if (CEK != CEK_AsReferenceOnly && 1307 refExpr->EvaluateAsRValue(result, getContext())) { 1308 resultIsReference = false; 1309 resultType = refExpr->getType(); 1310 1311 // Otherwise, try to evaluate as an l-value. 1312 } else if (CEK != CEK_AsValueOnly && 1313 refExpr->EvaluateAsLValue(result, getContext())) { 1314 resultIsReference = true; 1315 resultType = value->getType(); 1316 1317 // Failure. 1318 } else { 1319 return ConstantEmission(); 1320 } 1321 1322 // In any case, if the initializer has side-effects, abandon ship. 1323 if (result.HasSideEffects) 1324 return ConstantEmission(); 1325 1326 // Emit as a constant. 1327 auto C = ConstantEmitter(*this).emitAbstract(refExpr->getLocation(), 1328 result.Val, resultType); 1329 1330 // Make sure we emit a debug reference to the global variable. 1331 // This should probably fire even for 1332 if (isa<VarDecl>(value)) { 1333 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value))) 1334 EmitDeclRefExprDbgValue(refExpr, result.Val); 1335 } else { 1336 assert(isa<EnumConstantDecl>(value)); 1337 EmitDeclRefExprDbgValue(refExpr, result.Val); 1338 } 1339 1340 // If we emitted a reference constant, we need to dereference that. 1341 if (resultIsReference) 1342 return ConstantEmission::forReference(C); 1343 1344 return ConstantEmission::forValue(C); 1345 } 1346 1347 static DeclRefExpr *tryToConvertMemberExprToDeclRefExpr(CodeGenFunction &CGF, 1348 const MemberExpr *ME) { 1349 if (auto *VD = dyn_cast<VarDecl>(ME->getMemberDecl())) { 1350 // Try to emit static variable member expressions as DREs. 1351 return DeclRefExpr::Create( 1352 CGF.getContext(), NestedNameSpecifierLoc(), SourceLocation(), VD, 1353 /*RefersToEnclosingVariableOrCapture=*/false, ME->getExprLoc(), 1354 ME->getType(), ME->getValueKind()); 1355 } 1356 return nullptr; 1357 } 1358 1359 CodeGenFunction::ConstantEmission 1360 CodeGenFunction::tryEmitAsConstant(const MemberExpr *ME) { 1361 if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, ME)) 1362 return tryEmitAsConstant(DRE); 1363 return ConstantEmission(); 1364 } 1365 1366 llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue, 1367 SourceLocation Loc) { 1368 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(), 1369 lvalue.getType(), Loc, lvalue.getBaseInfo(), 1370 lvalue.getTBAAAccessType(), 1371 lvalue.getTBAABaseType(), lvalue.getTBAAOffset(), 1372 lvalue.isNontemporal()); 1373 } 1374 1375 static bool hasBooleanRepresentation(QualType Ty) { 1376 if (Ty->isBooleanType()) 1377 return true; 1378 1379 if (const EnumType *ET = Ty->getAs<EnumType>()) 1380 return ET->getDecl()->getIntegerType()->isBooleanType(); 1381 1382 if (const AtomicType *AT = Ty->getAs<AtomicType>()) 1383 return hasBooleanRepresentation(AT->getValueType()); 1384 1385 return false; 1386 } 1387 1388 static bool getRangeForType(CodeGenFunction &CGF, QualType Ty, 1389 llvm::APInt &Min, llvm::APInt &End, 1390 bool StrictEnums, bool IsBool) { 1391 const EnumType *ET = Ty->getAs<EnumType>(); 1392 bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums && 1393 ET && !ET->getDecl()->isFixed(); 1394 if (!IsBool && !IsRegularCPlusPlusEnum) 1395 return false; 1396 1397 if (IsBool) { 1398 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0); 1399 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2); 1400 } else { 1401 const EnumDecl *ED = ET->getDecl(); 1402 llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType()); 1403 unsigned Bitwidth = LTy->getScalarSizeInBits(); 1404 unsigned NumNegativeBits = ED->getNumNegativeBits(); 1405 unsigned NumPositiveBits = ED->getNumPositiveBits(); 1406 1407 if (NumNegativeBits) { 1408 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1); 1409 assert(NumBits <= Bitwidth); 1410 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1); 1411 Min = -End; 1412 } else { 1413 assert(NumPositiveBits <= Bitwidth); 1414 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits; 1415 Min = llvm::APInt(Bitwidth, 0); 1416 } 1417 } 1418 return true; 1419 } 1420 1421 llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) { 1422 llvm::APInt Min, End; 1423 if (!getRangeForType(*this, Ty, Min, End, CGM.getCodeGenOpts().StrictEnums, 1424 hasBooleanRepresentation(Ty))) 1425 return nullptr; 1426 1427 llvm::MDBuilder MDHelper(getLLVMContext()); 1428 return MDHelper.createRange(Min, End); 1429 } 1430 1431 bool CodeGenFunction::EmitScalarRangeCheck(llvm::Value *Value, QualType Ty, 1432 SourceLocation Loc) { 1433 bool HasBoolCheck = SanOpts.has(SanitizerKind::Bool); 1434 bool HasEnumCheck = SanOpts.has(SanitizerKind::Enum); 1435 if (!HasBoolCheck && !HasEnumCheck) 1436 return false; 1437 1438 bool IsBool = hasBooleanRepresentation(Ty) || 1439 NSAPI(CGM.getContext()).isObjCBOOLType(Ty); 1440 bool NeedsBoolCheck = HasBoolCheck && IsBool; 1441 bool NeedsEnumCheck = HasEnumCheck && Ty->getAs<EnumType>(); 1442 if (!NeedsBoolCheck && !NeedsEnumCheck) 1443 return false; 1444 1445 // Single-bit booleans don't need to be checked. Special-case this to avoid 1446 // a bit width mismatch when handling bitfield values. This is handled by 1447 // EmitFromMemory for the non-bitfield case. 1448 if (IsBool && 1449 cast<llvm::IntegerType>(Value->getType())->getBitWidth() == 1) 1450 return false; 1451 1452 llvm::APInt Min, End; 1453 if (!getRangeForType(*this, Ty, Min, End, /*StrictEnums=*/true, IsBool)) 1454 return true; 1455 1456 SanitizerScope SanScope(this); 1457 llvm::Value *Check; 1458 --End; 1459 if (!Min) { 1460 Check = Builder.CreateICmpULE( 1461 Value, llvm::ConstantInt::get(getLLVMContext(), End)); 1462 } else { 1463 llvm::Value *Upper = Builder.CreateICmpSLE( 1464 Value, llvm::ConstantInt::get(getLLVMContext(), End)); 1465 llvm::Value *Lower = Builder.CreateICmpSGE( 1466 Value, llvm::ConstantInt::get(getLLVMContext(), Min)); 1467 Check = Builder.CreateAnd(Upper, Lower); 1468 } 1469 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc), 1470 EmitCheckTypeDescriptor(Ty)}; 1471 SanitizerMask Kind = 1472 NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool; 1473 EmitCheck(std::make_pair(Check, Kind), SanitizerHandler::LoadInvalidValue, 1474 StaticArgs, EmitCheckValue(Value)); 1475 return true; 1476 } 1477 1478 llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile, 1479 QualType Ty, 1480 SourceLocation Loc, 1481 LValueBaseInfo BaseInfo, 1482 llvm::MDNode *TBAAAccessType, 1483 QualType TBAABaseType, 1484 uint64_t TBAAOffset, 1485 bool isNontemporal) { 1486 if (!CGM.getCodeGenOpts().PreserveVec3Type) { 1487 // For better performance, handle vector loads differently. 1488 if (Ty->isVectorType()) { 1489 const llvm::Type *EltTy = Addr.getElementType(); 1490 1491 const auto *VTy = cast<llvm::VectorType>(EltTy); 1492 1493 // Handle vectors of size 3 like size 4 for better performance. 1494 if (VTy->getNumElements() == 3) { 1495 1496 // Bitcast to vec4 type. 1497 llvm::VectorType *vec4Ty = 1498 llvm::VectorType::get(VTy->getElementType(), 4); 1499 Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4"); 1500 // Now load value. 1501 llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4"); 1502 1503 // Shuffle vector to get vec3. 1504 V = Builder.CreateShuffleVector(V, llvm::UndefValue::get(vec4Ty), 1505 {0, 1, 2}, "extractVec"); 1506 return EmitFromMemory(V, Ty); 1507 } 1508 } 1509 } 1510 1511 // Atomic operations have to be done on integral types. 1512 LValue AtomicLValue = 1513 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAAccessType); 1514 if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) { 1515 return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal(); 1516 } 1517 1518 llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile); 1519 if (isNontemporal) { 1520 llvm::MDNode *Node = llvm::MDNode::get( 1521 Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1))); 1522 Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node); 1523 } 1524 if (TBAAAccessType) { 1525 bool MayAlias = BaseInfo.getMayAlias(); 1526 llvm::MDNode *TBAA = MayAlias 1527 ? CGM.getTBAAMayAliasTypeInfo() 1528 : CGM.getTBAAStructTagInfo(TBAABaseType, TBAAAccessType, TBAAOffset); 1529 if (TBAA) 1530 CGM.DecorateInstructionWithTBAA(Load, TBAA, MayAlias); 1531 } 1532 1533 if (EmitScalarRangeCheck(Load, Ty, Loc)) { 1534 // In order to prevent the optimizer from throwing away the check, don't 1535 // attach range metadata to the load. 1536 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0) 1537 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty)) 1538 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo); 1539 1540 return EmitFromMemory(Load, Ty); 1541 } 1542 1543 llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) { 1544 // Bool has a different representation in memory than in registers. 1545 if (hasBooleanRepresentation(Ty)) { 1546 // This should really always be an i1, but sometimes it's already 1547 // an i8, and it's awkward to track those cases down. 1548 if (Value->getType()->isIntegerTy(1)) 1549 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool"); 1550 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) && 1551 "wrong value rep of bool"); 1552 } 1553 1554 return Value; 1555 } 1556 1557 llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) { 1558 // Bool has a different representation in memory than in registers. 1559 if (hasBooleanRepresentation(Ty)) { 1560 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) && 1561 "wrong value rep of bool"); 1562 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool"); 1563 } 1564 1565 return Value; 1566 } 1567 1568 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr, 1569 bool Volatile, QualType Ty, 1570 LValueBaseInfo BaseInfo, 1571 llvm::MDNode *TBAAAccessType, 1572 bool isInit, QualType TBAABaseType, 1573 uint64_t TBAAOffset, 1574 bool isNontemporal) { 1575 1576 if (!CGM.getCodeGenOpts().PreserveVec3Type) { 1577 // Handle vectors differently to get better performance. 1578 if (Ty->isVectorType()) { 1579 llvm::Type *SrcTy = Value->getType(); 1580 auto *VecTy = dyn_cast<llvm::VectorType>(SrcTy); 1581 // Handle vec3 special. 1582 if (VecTy && VecTy->getNumElements() == 3) { 1583 // Our source is a vec3, do a shuffle vector to make it a vec4. 1584 llvm::Constant *Mask[] = {Builder.getInt32(0), Builder.getInt32(1), 1585 Builder.getInt32(2), 1586 llvm::UndefValue::get(Builder.getInt32Ty())}; 1587 llvm::Value *MaskV = llvm::ConstantVector::get(Mask); 1588 Value = Builder.CreateShuffleVector(Value, llvm::UndefValue::get(VecTy), 1589 MaskV, "extractVec"); 1590 SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4); 1591 } 1592 if (Addr.getElementType() != SrcTy) { 1593 Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp"); 1594 } 1595 } 1596 } 1597 1598 Value = EmitToMemory(Value, Ty); 1599 1600 LValue AtomicLValue = 1601 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAAccessType); 1602 if (Ty->isAtomicType() || 1603 (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) { 1604 EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit); 1605 return; 1606 } 1607 1608 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile); 1609 if (isNontemporal) { 1610 llvm::MDNode *Node = 1611 llvm::MDNode::get(Store->getContext(), 1612 llvm::ConstantAsMetadata::get(Builder.getInt32(1))); 1613 Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node); 1614 } 1615 if (TBAAAccessType) { 1616 bool MayAlias = BaseInfo.getMayAlias(); 1617 llvm::MDNode *TBAA = MayAlias 1618 ? CGM.getTBAAMayAliasTypeInfo() 1619 : CGM.getTBAAStructTagInfo(TBAABaseType, TBAAAccessType, TBAAOffset); 1620 if (TBAA) 1621 CGM.DecorateInstructionWithTBAA(Store, TBAA, MayAlias); 1622 } 1623 } 1624 1625 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue, 1626 bool isInit) { 1627 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(), 1628 lvalue.getType(), lvalue.getBaseInfo(), 1629 lvalue.getTBAAAccessType(), isInit, 1630 lvalue.getTBAABaseType(), lvalue.getTBAAOffset(), 1631 lvalue.isNontemporal()); 1632 } 1633 1634 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this 1635 /// method emits the address of the lvalue, then loads the result as an rvalue, 1636 /// returning the rvalue. 1637 RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) { 1638 if (LV.isObjCWeak()) { 1639 // load of a __weak object. 1640 Address AddrWeakObj = LV.getAddress(); 1641 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this, 1642 AddrWeakObj)); 1643 } 1644 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) { 1645 // In MRC mode, we do a load+autorelease. 1646 if (!getLangOpts().ObjCAutoRefCount) { 1647 return RValue::get(EmitARCLoadWeak(LV.getAddress())); 1648 } 1649 1650 // In ARC mode, we load retained and then consume the value. 1651 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress()); 1652 Object = EmitObjCConsumeObject(LV.getType(), Object); 1653 return RValue::get(Object); 1654 } 1655 1656 if (LV.isSimple()) { 1657 assert(!LV.getType()->isFunctionType()); 1658 1659 // Everything needs a load. 1660 return RValue::get(EmitLoadOfScalar(LV, Loc)); 1661 } 1662 1663 if (LV.isVectorElt()) { 1664 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(), 1665 LV.isVolatileQualified()); 1666 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(), 1667 "vecext")); 1668 } 1669 1670 // If this is a reference to a subset of the elements of a vector, either 1671 // shuffle the input or extract/insert them as appropriate. 1672 if (LV.isExtVectorElt()) 1673 return EmitLoadOfExtVectorElementLValue(LV); 1674 1675 // Global Register variables always invoke intrinsics 1676 if (LV.isGlobalReg()) 1677 return EmitLoadOfGlobalRegLValue(LV); 1678 1679 assert(LV.isBitField() && "Unknown LValue type!"); 1680 return EmitLoadOfBitfieldLValue(LV, Loc); 1681 } 1682 1683 RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV, 1684 SourceLocation Loc) { 1685 const CGBitFieldInfo &Info = LV.getBitFieldInfo(); 1686 1687 // Get the output type. 1688 llvm::Type *ResLTy = ConvertType(LV.getType()); 1689 1690 Address Ptr = LV.getBitFieldAddress(); 1691 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load"); 1692 1693 if (Info.IsSigned) { 1694 assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize); 1695 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size; 1696 if (HighBits) 1697 Val = Builder.CreateShl(Val, HighBits, "bf.shl"); 1698 if (Info.Offset + HighBits) 1699 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr"); 1700 } else { 1701 if (Info.Offset) 1702 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr"); 1703 if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize) 1704 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize, 1705 Info.Size), 1706 "bf.clear"); 1707 } 1708 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast"); 1709 EmitScalarRangeCheck(Val, LV.getType(), Loc); 1710 return RValue::get(Val); 1711 } 1712 1713 // If this is a reference to a subset of the elements of a vector, create an 1714 // appropriate shufflevector. 1715 RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) { 1716 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(), 1717 LV.isVolatileQualified()); 1718 1719 const llvm::Constant *Elts = LV.getExtVectorElts(); 1720 1721 // If the result of the expression is a non-vector type, we must be extracting 1722 // a single element. Just codegen as an extractelement. 1723 const VectorType *ExprVT = LV.getType()->getAs<VectorType>(); 1724 if (!ExprVT) { 1725 unsigned InIdx = getAccessedFieldNo(0, Elts); 1726 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx); 1727 return RValue::get(Builder.CreateExtractElement(Vec, Elt)); 1728 } 1729 1730 // Always use shuffle vector to try to retain the original program structure 1731 unsigned NumResultElts = ExprVT->getNumElements(); 1732 1733 SmallVector<llvm::Constant*, 4> Mask; 1734 for (unsigned i = 0; i != NumResultElts; ++i) 1735 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts))); 1736 1737 llvm::Value *MaskV = llvm::ConstantVector::get(Mask); 1738 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()), 1739 MaskV); 1740 return RValue::get(Vec); 1741 } 1742 1743 /// @brief Generates lvalue for partial ext_vector access. 1744 Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) { 1745 Address VectorAddress = LV.getExtVectorAddress(); 1746 const VectorType *ExprVT = LV.getType()->getAs<VectorType>(); 1747 QualType EQT = ExprVT->getElementType(); 1748 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT); 1749 1750 Address CastToPointerElement = 1751 Builder.CreateElementBitCast(VectorAddress, VectorElementTy, 1752 "conv.ptr.element"); 1753 1754 const llvm::Constant *Elts = LV.getExtVectorElts(); 1755 unsigned ix = getAccessedFieldNo(0, Elts); 1756 1757 Address VectorBasePtrPlusIx = 1758 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix, 1759 getContext().getTypeSizeInChars(EQT), 1760 "vector.elt"); 1761 1762 return VectorBasePtrPlusIx; 1763 } 1764 1765 /// @brief Load of global gamed gegisters are always calls to intrinsics. 1766 RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) { 1767 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) && 1768 "Bad type for register variable"); 1769 llvm::MDNode *RegName = cast<llvm::MDNode>( 1770 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata()); 1771 1772 // We accept integer and pointer types only 1773 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType()); 1774 llvm::Type *Ty = OrigTy; 1775 if (OrigTy->isPointerTy()) 1776 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy); 1777 llvm::Type *Types[] = { Ty }; 1778 1779 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types); 1780 llvm::Value *Call = Builder.CreateCall( 1781 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName)); 1782 if (OrigTy->isPointerTy()) 1783 Call = Builder.CreateIntToPtr(Call, OrigTy); 1784 return RValue::get(Call); 1785 } 1786 1787 1788 /// EmitStoreThroughLValue - Store the specified rvalue into the specified 1789 /// lvalue, where both are guaranteed to the have the same type, and that type 1790 /// is 'Ty'. 1791 void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst, 1792 bool isInit) { 1793 if (!Dst.isSimple()) { 1794 if (Dst.isVectorElt()) { 1795 // Read/modify/write the vector, inserting the new element. 1796 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(), 1797 Dst.isVolatileQualified()); 1798 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(), 1799 Dst.getVectorIdx(), "vecins"); 1800 Builder.CreateStore(Vec, Dst.getVectorAddress(), 1801 Dst.isVolatileQualified()); 1802 return; 1803 } 1804 1805 // If this is an update of extended vector elements, insert them as 1806 // appropriate. 1807 if (Dst.isExtVectorElt()) 1808 return EmitStoreThroughExtVectorComponentLValue(Src, Dst); 1809 1810 if (Dst.isGlobalReg()) 1811 return EmitStoreThroughGlobalRegLValue(Src, Dst); 1812 1813 assert(Dst.isBitField() && "Unknown LValue type"); 1814 return EmitStoreThroughBitfieldLValue(Src, Dst); 1815 } 1816 1817 // There's special magic for assigning into an ARC-qualified l-value. 1818 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) { 1819 switch (Lifetime) { 1820 case Qualifiers::OCL_None: 1821 llvm_unreachable("present but none"); 1822 1823 case Qualifiers::OCL_ExplicitNone: 1824 // nothing special 1825 break; 1826 1827 case Qualifiers::OCL_Strong: 1828 if (isInit) { 1829 Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal())); 1830 break; 1831 } 1832 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true); 1833 return; 1834 1835 case Qualifiers::OCL_Weak: 1836 if (isInit) 1837 // Initialize and then skip the primitive store. 1838 EmitARCInitWeak(Dst.getAddress(), Src.getScalarVal()); 1839 else 1840 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true); 1841 return; 1842 1843 case Qualifiers::OCL_Autoreleasing: 1844 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(), 1845 Src.getScalarVal())); 1846 // fall into the normal path 1847 break; 1848 } 1849 } 1850 1851 if (Dst.isObjCWeak() && !Dst.isNonGC()) { 1852 // load of a __weak object. 1853 Address LvalueDst = Dst.getAddress(); 1854 llvm::Value *src = Src.getScalarVal(); 1855 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst); 1856 return; 1857 } 1858 1859 if (Dst.isObjCStrong() && !Dst.isNonGC()) { 1860 // load of a __strong object. 1861 Address LvalueDst = Dst.getAddress(); 1862 llvm::Value *src = Src.getScalarVal(); 1863 if (Dst.isObjCIvar()) { 1864 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL"); 1865 llvm::Type *ResultType = IntPtrTy; 1866 Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp()); 1867 llvm::Value *RHS = dst.getPointer(); 1868 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast"); 1869 llvm::Value *LHS = 1870 Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType, 1871 "sub.ptr.lhs.cast"); 1872 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset"); 1873 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst, 1874 BytesBetween); 1875 } else if (Dst.isGlobalObjCRef()) { 1876 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst, 1877 Dst.isThreadLocalRef()); 1878 } 1879 else 1880 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst); 1881 return; 1882 } 1883 1884 assert(Src.isScalar() && "Can't emit an agg store with this method"); 1885 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit); 1886 } 1887 1888 void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, 1889 llvm::Value **Result) { 1890 const CGBitFieldInfo &Info = Dst.getBitFieldInfo(); 1891 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType()); 1892 Address Ptr = Dst.getBitFieldAddress(); 1893 1894 // Get the source value, truncated to the width of the bit-field. 1895 llvm::Value *SrcVal = Src.getScalarVal(); 1896 1897 // Cast the source to the storage type and shift it into place. 1898 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(), 1899 /*IsSigned=*/false); 1900 llvm::Value *MaskedVal = SrcVal; 1901 1902 // See if there are other bits in the bitfield's storage we'll need to load 1903 // and mask together with source before storing. 1904 if (Info.StorageSize != Info.Size) { 1905 assert(Info.StorageSize > Info.Size && "Invalid bitfield size."); 1906 llvm::Value *Val = 1907 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load"); 1908 1909 // Mask the source value as needed. 1910 if (!hasBooleanRepresentation(Dst.getType())) 1911 SrcVal = Builder.CreateAnd(SrcVal, 1912 llvm::APInt::getLowBitsSet(Info.StorageSize, 1913 Info.Size), 1914 "bf.value"); 1915 MaskedVal = SrcVal; 1916 if (Info.Offset) 1917 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl"); 1918 1919 // Mask out the original value. 1920 Val = Builder.CreateAnd(Val, 1921 ~llvm::APInt::getBitsSet(Info.StorageSize, 1922 Info.Offset, 1923 Info.Offset + Info.Size), 1924 "bf.clear"); 1925 1926 // Or together the unchanged values and the source value. 1927 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set"); 1928 } else { 1929 assert(Info.Offset == 0); 1930 } 1931 1932 // Write the new value back out. 1933 Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified()); 1934 1935 // Return the new value of the bit-field, if requested. 1936 if (Result) { 1937 llvm::Value *ResultVal = MaskedVal; 1938 1939 // Sign extend the value if needed. 1940 if (Info.IsSigned) { 1941 assert(Info.Size <= Info.StorageSize); 1942 unsigned HighBits = Info.StorageSize - Info.Size; 1943 if (HighBits) { 1944 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl"); 1945 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr"); 1946 } 1947 } 1948 1949 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned, 1950 "bf.result.cast"); 1951 *Result = EmitFromMemory(ResultVal, Dst.getType()); 1952 } 1953 } 1954 1955 void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src, 1956 LValue Dst) { 1957 // This access turns into a read/modify/write of the vector. Load the input 1958 // value now. 1959 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(), 1960 Dst.isVolatileQualified()); 1961 const llvm::Constant *Elts = Dst.getExtVectorElts(); 1962 1963 llvm::Value *SrcVal = Src.getScalarVal(); 1964 1965 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) { 1966 unsigned NumSrcElts = VTy->getNumElements(); 1967 unsigned NumDstElts = Vec->getType()->getVectorNumElements(); 1968 if (NumDstElts == NumSrcElts) { 1969 // Use shuffle vector is the src and destination are the same number of 1970 // elements and restore the vector mask since it is on the side it will be 1971 // stored. 1972 SmallVector<llvm::Constant*, 4> Mask(NumDstElts); 1973 for (unsigned i = 0; i != NumSrcElts; ++i) 1974 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i); 1975 1976 llvm::Value *MaskV = llvm::ConstantVector::get(Mask); 1977 Vec = Builder.CreateShuffleVector(SrcVal, 1978 llvm::UndefValue::get(Vec->getType()), 1979 MaskV); 1980 } else if (NumDstElts > NumSrcElts) { 1981 // Extended the source vector to the same length and then shuffle it 1982 // into the destination. 1983 // FIXME: since we're shuffling with undef, can we just use the indices 1984 // into that? This could be simpler. 1985 SmallVector<llvm::Constant*, 4> ExtMask; 1986 for (unsigned i = 0; i != NumSrcElts; ++i) 1987 ExtMask.push_back(Builder.getInt32(i)); 1988 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty)); 1989 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask); 1990 llvm::Value *ExtSrcVal = 1991 Builder.CreateShuffleVector(SrcVal, 1992 llvm::UndefValue::get(SrcVal->getType()), 1993 ExtMaskV); 1994 // build identity 1995 SmallVector<llvm::Constant*, 4> Mask; 1996 for (unsigned i = 0; i != NumDstElts; ++i) 1997 Mask.push_back(Builder.getInt32(i)); 1998 1999 // When the vector size is odd and .odd or .hi is used, the last element 2000 // of the Elts constant array will be one past the size of the vector. 2001 // Ignore the last element here, if it is greater than the mask size. 2002 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size()) 2003 NumSrcElts--; 2004 2005 // modify when what gets shuffled in 2006 for (unsigned i = 0; i != NumSrcElts; ++i) 2007 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts); 2008 llvm::Value *MaskV = llvm::ConstantVector::get(Mask); 2009 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV); 2010 } else { 2011 // We should never shorten the vector 2012 llvm_unreachable("unexpected shorten vector length"); 2013 } 2014 } else { 2015 // If the Src is a scalar (not a vector) it must be updating one element. 2016 unsigned InIdx = getAccessedFieldNo(0, Elts); 2017 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx); 2018 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt); 2019 } 2020 2021 Builder.CreateStore(Vec, Dst.getExtVectorAddress(), 2022 Dst.isVolatileQualified()); 2023 } 2024 2025 /// @brief Store of global named registers are always calls to intrinsics. 2026 void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) { 2027 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) && 2028 "Bad type for register variable"); 2029 llvm::MDNode *RegName = cast<llvm::MDNode>( 2030 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata()); 2031 assert(RegName && "Register LValue is not metadata"); 2032 2033 // We accept integer and pointer types only 2034 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType()); 2035 llvm::Type *Ty = OrigTy; 2036 if (OrigTy->isPointerTy()) 2037 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy); 2038 llvm::Type *Types[] = { Ty }; 2039 2040 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types); 2041 llvm::Value *Value = Src.getScalarVal(); 2042 if (OrigTy->isPointerTy()) 2043 Value = Builder.CreatePtrToInt(Value, Ty); 2044 Builder.CreateCall( 2045 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value}); 2046 } 2047 2048 // setObjCGCLValueClass - sets class of the lvalue for the purpose of 2049 // generating write-barries API. It is currently a global, ivar, 2050 // or neither. 2051 static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E, 2052 LValue &LV, 2053 bool IsMemberAccess=false) { 2054 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC) 2055 return; 2056 2057 if (isa<ObjCIvarRefExpr>(E)) { 2058 QualType ExpTy = E->getType(); 2059 if (IsMemberAccess && ExpTy->isPointerType()) { 2060 // If ivar is a structure pointer, assigning to field of 2061 // this struct follows gcc's behavior and makes it a non-ivar 2062 // writer-barrier conservatively. 2063 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType(); 2064 if (ExpTy->isRecordType()) { 2065 LV.setObjCIvar(false); 2066 return; 2067 } 2068 } 2069 LV.setObjCIvar(true); 2070 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E)); 2071 LV.setBaseIvarExp(Exp->getBase()); 2072 LV.setObjCArray(E->getType()->isArrayType()); 2073 return; 2074 } 2075 2076 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) { 2077 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) { 2078 if (VD->hasGlobalStorage()) { 2079 LV.setGlobalObjCRef(true); 2080 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None); 2081 } 2082 } 2083 LV.setObjCArray(E->getType()->isArrayType()); 2084 return; 2085 } 2086 2087 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) { 2088 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess); 2089 return; 2090 } 2091 2092 if (const auto *Exp = dyn_cast<ParenExpr>(E)) { 2093 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess); 2094 if (LV.isObjCIvar()) { 2095 // If cast is to a structure pointer, follow gcc's behavior and make it 2096 // a non-ivar write-barrier. 2097 QualType ExpTy = E->getType(); 2098 if (ExpTy->isPointerType()) 2099 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType(); 2100 if (ExpTy->isRecordType()) 2101 LV.setObjCIvar(false); 2102 } 2103 return; 2104 } 2105 2106 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) { 2107 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV); 2108 return; 2109 } 2110 2111 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) { 2112 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess); 2113 return; 2114 } 2115 2116 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) { 2117 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess); 2118 return; 2119 } 2120 2121 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) { 2122 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess); 2123 return; 2124 } 2125 2126 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) { 2127 setObjCGCLValueClass(Ctx, Exp->getBase(), LV); 2128 if (LV.isObjCIvar() && !LV.isObjCArray()) 2129 // Using array syntax to assigning to what an ivar points to is not 2130 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0; 2131 LV.setObjCIvar(false); 2132 else if (LV.isGlobalObjCRef() && !LV.isObjCArray()) 2133 // Using array syntax to assigning to what global points to is not 2134 // same as assigning to the global itself. {id *G;} G[i] = 0; 2135 LV.setGlobalObjCRef(false); 2136 return; 2137 } 2138 2139 if (const auto *Exp = dyn_cast<MemberExpr>(E)) { 2140 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true); 2141 // We don't know if member is an 'ivar', but this flag is looked at 2142 // only in the context of LV.isObjCIvar(). 2143 LV.setObjCArray(E->getType()->isArrayType()); 2144 return; 2145 } 2146 } 2147 2148 static llvm::Value * 2149 EmitBitCastOfLValueToProperType(CodeGenFunction &CGF, 2150 llvm::Value *V, llvm::Type *IRType, 2151 StringRef Name = StringRef()) { 2152 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace(); 2153 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name); 2154 } 2155 2156 static LValue EmitThreadPrivateVarDeclLValue( 2157 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr, 2158 llvm::Type *RealVarTy, SourceLocation Loc) { 2159 Addr = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc); 2160 Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy); 2161 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false); 2162 return CGF.MakeAddrLValue(Addr, T, BaseInfo); 2163 } 2164 2165 Address CodeGenFunction::EmitLoadOfReference(Address Addr, 2166 const ReferenceType *RefTy, 2167 LValueBaseInfo *BaseInfo) { 2168 llvm::Value *Ptr = Builder.CreateLoad(Addr); 2169 return Address(Ptr, getNaturalTypeAlignment(RefTy->getPointeeType(), 2170 BaseInfo, /*forPointee*/ true)); 2171 } 2172 2173 LValue CodeGenFunction::EmitLoadOfReferenceLValue(Address RefAddr, 2174 const ReferenceType *RefTy) { 2175 LValueBaseInfo BaseInfo; 2176 Address Addr = EmitLoadOfReference(RefAddr, RefTy, &BaseInfo); 2177 return MakeAddrLValue(Addr, RefTy->getPointeeType(), BaseInfo); 2178 } 2179 2180 Address CodeGenFunction::EmitLoadOfPointer(Address Ptr, 2181 const PointerType *PtrTy, 2182 LValueBaseInfo *BaseInfo) { 2183 llvm::Value *Addr = Builder.CreateLoad(Ptr); 2184 return Address(Addr, getNaturalTypeAlignment(PtrTy->getPointeeType(), 2185 BaseInfo, 2186 /*forPointeeType=*/true)); 2187 } 2188 2189 LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr, 2190 const PointerType *PtrTy) { 2191 LValueBaseInfo BaseInfo; 2192 Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &BaseInfo); 2193 return MakeAddrLValue(Addr, PtrTy->getPointeeType(), BaseInfo); 2194 } 2195 2196 static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF, 2197 const Expr *E, const VarDecl *VD) { 2198 QualType T = E->getType(); 2199 2200 // If it's thread_local, emit a call to its wrapper function instead. 2201 if (VD->getTLSKind() == VarDecl::TLS_Dynamic && 2202 CGF.CGM.getCXXABI().usesThreadWrapperFunction()) 2203 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T); 2204 2205 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD); 2206 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType()); 2207 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy); 2208 CharUnits Alignment = CGF.getContext().getDeclAlign(VD); 2209 Address Addr(V, Alignment); 2210 LValue LV; 2211 // Emit reference to the private copy of the variable if it is an OpenMP 2212 // threadprivate variable. 2213 if (CGF.getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>()) 2214 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy, 2215 E->getExprLoc()); 2216 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) { 2217 LV = CGF.EmitLoadOfReferenceLValue(Addr, RefTy); 2218 } else { 2219 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false); 2220 LV = CGF.MakeAddrLValue(Addr, T, BaseInfo); 2221 } 2222 setObjCGCLValueClass(CGF.getContext(), E, LV); 2223 return LV; 2224 } 2225 2226 static llvm::Constant *EmitFunctionDeclPointer(CodeGenModule &CGM, 2227 const FunctionDecl *FD) { 2228 if (FD->hasAttr<WeakRefAttr>()) { 2229 ConstantAddress aliasee = CGM.GetWeakRefReference(FD); 2230 return aliasee.getPointer(); 2231 } 2232 2233 llvm::Constant *V = CGM.GetAddrOfFunction(FD); 2234 if (!FD->hasPrototype()) { 2235 if (const FunctionProtoType *Proto = 2236 FD->getType()->getAs<FunctionProtoType>()) { 2237 // Ugly case: for a K&R-style definition, the type of the definition 2238 // isn't the same as the type of a use. Correct for this with a 2239 // bitcast. 2240 QualType NoProtoType = 2241 CGM.getContext().getFunctionNoProtoType(Proto->getReturnType()); 2242 NoProtoType = CGM.getContext().getPointerType(NoProtoType); 2243 V = llvm::ConstantExpr::getBitCast(V, 2244 CGM.getTypes().ConvertType(NoProtoType)); 2245 } 2246 } 2247 return V; 2248 } 2249 2250 static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF, 2251 const Expr *E, const FunctionDecl *FD) { 2252 llvm::Value *V = EmitFunctionDeclPointer(CGF.CGM, FD); 2253 CharUnits Alignment = CGF.getContext().getDeclAlign(FD); 2254 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false); 2255 return CGF.MakeAddrLValue(V, E->getType(), Alignment, BaseInfo); 2256 } 2257 2258 static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD, 2259 llvm::Value *ThisValue) { 2260 QualType TagType = CGF.getContext().getTagDeclType(FD->getParent()); 2261 LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType); 2262 return CGF.EmitLValueForField(LV, FD); 2263 } 2264 2265 /// Named Registers are named metadata pointing to the register name 2266 /// which will be read from/written to as an argument to the intrinsic 2267 /// @llvm.read/write_register. 2268 /// So far, only the name is being passed down, but other options such as 2269 /// register type, allocation type or even optimization options could be 2270 /// passed down via the metadata node. 2271 static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) { 2272 SmallString<64> Name("llvm.named.register."); 2273 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>(); 2274 assert(Asm->getLabel().size() < 64-Name.size() && 2275 "Register name too big"); 2276 Name.append(Asm->getLabel()); 2277 llvm::NamedMDNode *M = 2278 CGM.getModule().getOrInsertNamedMetadata(Name); 2279 if (M->getNumOperands() == 0) { 2280 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(), 2281 Asm->getLabel()); 2282 llvm::Metadata *Ops[] = {Str}; 2283 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 2284 } 2285 2286 CharUnits Alignment = CGM.getContext().getDeclAlign(VD); 2287 2288 llvm::Value *Ptr = 2289 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0)); 2290 return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType()); 2291 } 2292 2293 LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) { 2294 const NamedDecl *ND = E->getDecl(); 2295 QualType T = E->getType(); 2296 2297 if (const auto *VD = dyn_cast<VarDecl>(ND)) { 2298 // Global Named registers access via intrinsics only 2299 if (VD->getStorageClass() == SC_Register && 2300 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl()) 2301 return EmitGlobalNamedRegister(VD, CGM); 2302 2303 // A DeclRefExpr for a reference initialized by a constant expression can 2304 // appear without being odr-used. Directly emit the constant initializer. 2305 const Expr *Init = VD->getAnyInitializer(VD); 2306 if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() && 2307 VD->isUsableInConstantExpressions(getContext()) && 2308 VD->checkInitIsICE() && 2309 // Do not emit if it is private OpenMP variable. 2310 !(E->refersToEnclosingVariableOrCapture() && CapturedStmtInfo && 2311 LocalDeclMap.count(VD))) { 2312 llvm::Constant *Val = 2313 ConstantEmitter(*this).emitAbstract(E->getLocation(), 2314 *VD->evaluateValue(), 2315 VD->getType()); 2316 assert(Val && "failed to emit reference constant expression"); 2317 // FIXME: Eventually we will want to emit vector element references. 2318 2319 // Should we be using the alignment of the constant pointer we emitted? 2320 CharUnits Alignment = getNaturalTypeAlignment(E->getType(), nullptr, 2321 /*pointee*/ true); 2322 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false); 2323 return MakeAddrLValue(Address(Val, Alignment), T, BaseInfo); 2324 } 2325 2326 // Check for captured variables. 2327 if (E->refersToEnclosingVariableOrCapture()) { 2328 VD = VD->getCanonicalDecl(); 2329 if (auto *FD = LambdaCaptureFields.lookup(VD)) 2330 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue); 2331 else if (CapturedStmtInfo) { 2332 auto I = LocalDeclMap.find(VD); 2333 if (I != LocalDeclMap.end()) { 2334 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) 2335 return EmitLoadOfReferenceLValue(I->second, RefTy); 2336 return MakeAddrLValue(I->second, T); 2337 } 2338 LValue CapLVal = 2339 EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD), 2340 CapturedStmtInfo->getContextValue()); 2341 bool MayAlias = CapLVal.getBaseInfo().getMayAlias(); 2342 return MakeAddrLValue( 2343 Address(CapLVal.getPointer(), getContext().getDeclAlign(VD)), 2344 CapLVal.getType(), LValueBaseInfo(AlignmentSource::Decl, MayAlias)); 2345 } 2346 2347 assert(isa<BlockDecl>(CurCodeDecl)); 2348 Address addr = GetAddrOfBlockDecl(VD, VD->hasAttr<BlocksAttr>()); 2349 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false); 2350 return MakeAddrLValue(addr, T, BaseInfo); 2351 } 2352 } 2353 2354 // FIXME: We should be able to assert this for FunctionDecls as well! 2355 // FIXME: We should be able to assert this for all DeclRefExprs, not just 2356 // those with a valid source location. 2357 assert((ND->isUsed(false) || !isa<VarDecl>(ND) || 2358 !E->getLocation().isValid()) && 2359 "Should not use decl without marking it used!"); 2360 2361 if (ND->hasAttr<WeakRefAttr>()) { 2362 const auto *VD = cast<ValueDecl>(ND); 2363 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD); 2364 return MakeAddrLValue(Aliasee, T, 2365 LValueBaseInfo(AlignmentSource::Decl, false)); 2366 } 2367 2368 if (const auto *VD = dyn_cast<VarDecl>(ND)) { 2369 // Check if this is a global variable. 2370 if (VD->hasLinkage() || VD->isStaticDataMember()) 2371 return EmitGlobalVarDeclLValue(*this, E, VD); 2372 2373 Address addr = Address::invalid(); 2374 2375 // The variable should generally be present in the local decl map. 2376 auto iter = LocalDeclMap.find(VD); 2377 if (iter != LocalDeclMap.end()) { 2378 addr = iter->second; 2379 2380 // Otherwise, it might be static local we haven't emitted yet for 2381 // some reason; most likely, because it's in an outer function. 2382 } else if (VD->isStaticLocal()) { 2383 addr = Address(CGM.getOrCreateStaticVarDecl( 2384 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false)), 2385 getContext().getDeclAlign(VD)); 2386 2387 // No other cases for now. 2388 } else { 2389 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?"); 2390 } 2391 2392 2393 // Check for OpenMP threadprivate variables. 2394 if (getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>()) { 2395 return EmitThreadPrivateVarDeclLValue( 2396 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()), 2397 E->getExprLoc()); 2398 } 2399 2400 // Drill into block byref variables. 2401 bool isBlockByref = VD->hasAttr<BlocksAttr>(); 2402 if (isBlockByref) { 2403 addr = emitBlockByrefAddress(addr, VD); 2404 } 2405 2406 // Drill into reference types. 2407 LValue LV; 2408 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) { 2409 LV = EmitLoadOfReferenceLValue(addr, RefTy); 2410 } else { 2411 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false); 2412 LV = MakeAddrLValue(addr, T, BaseInfo); 2413 } 2414 2415 bool isLocalStorage = VD->hasLocalStorage(); 2416 2417 bool NonGCable = isLocalStorage && 2418 !VD->getType()->isReferenceType() && 2419 !isBlockByref; 2420 if (NonGCable) { 2421 LV.getQuals().removeObjCGCAttr(); 2422 LV.setNonGC(true); 2423 } 2424 2425 bool isImpreciseLifetime = 2426 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>()); 2427 if (isImpreciseLifetime) 2428 LV.setARCPreciseLifetime(ARCImpreciseLifetime); 2429 setObjCGCLValueClass(getContext(), E, LV); 2430 return LV; 2431 } 2432 2433 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) 2434 return EmitFunctionDeclLValue(*this, E, FD); 2435 2436 // FIXME: While we're emitting a binding from an enclosing scope, all other 2437 // DeclRefExprs we see should be implicitly treated as if they also refer to 2438 // an enclosing scope. 2439 if (const auto *BD = dyn_cast<BindingDecl>(ND)) 2440 return EmitLValue(BD->getBinding()); 2441 2442 llvm_unreachable("Unhandled DeclRefExpr"); 2443 } 2444 2445 LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) { 2446 // __extension__ doesn't affect lvalue-ness. 2447 if (E->getOpcode() == UO_Extension) 2448 return EmitLValue(E->getSubExpr()); 2449 2450 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType()); 2451 switch (E->getOpcode()) { 2452 default: llvm_unreachable("Unknown unary operator lvalue!"); 2453 case UO_Deref: { 2454 QualType T = E->getSubExpr()->getType()->getPointeeType(); 2455 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type"); 2456 2457 LValueBaseInfo BaseInfo; 2458 Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &BaseInfo); 2459 LValue LV = MakeAddrLValue(Addr, T, BaseInfo); 2460 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace()); 2461 2462 // We should not generate __weak write barrier on indirect reference 2463 // of a pointer to object; as in void foo (__weak id *param); *param = 0; 2464 // But, we continue to generate __strong write barrier on indirect write 2465 // into a pointer to object. 2466 if (getLangOpts().ObjC1 && 2467 getLangOpts().getGC() != LangOptions::NonGC && 2468 LV.isObjCWeak()) 2469 LV.setNonGC(!E->isOBJCGCCandidate(getContext())); 2470 return LV; 2471 } 2472 case UO_Real: 2473 case UO_Imag: { 2474 LValue LV = EmitLValue(E->getSubExpr()); 2475 assert(LV.isSimple() && "real/imag on non-ordinary l-value"); 2476 2477 // __real is valid on scalars. This is a faster way of testing that. 2478 // __imag can only produce an rvalue on scalars. 2479 if (E->getOpcode() == UO_Real && 2480 !LV.getAddress().getElementType()->isStructTy()) { 2481 assert(E->getSubExpr()->getType()->isArithmeticType()); 2482 return LV; 2483 } 2484 2485 QualType T = ExprTy->castAs<ComplexType>()->getElementType(); 2486 2487 Address Component = 2488 (E->getOpcode() == UO_Real 2489 ? emitAddrOfRealComponent(LV.getAddress(), LV.getType()) 2490 : emitAddrOfImagComponent(LV.getAddress(), LV.getType())); 2491 LValue ElemLV = MakeAddrLValue(Component, T, LV.getBaseInfo()); 2492 ElemLV.getQuals().addQualifiers(LV.getQuals()); 2493 return ElemLV; 2494 } 2495 case UO_PreInc: 2496 case UO_PreDec: { 2497 LValue LV = EmitLValue(E->getSubExpr()); 2498 bool isInc = E->getOpcode() == UO_PreInc; 2499 2500 if (E->getType()->isAnyComplexType()) 2501 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/); 2502 else 2503 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/); 2504 return LV; 2505 } 2506 } 2507 } 2508 2509 LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) { 2510 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E), 2511 E->getType(), 2512 LValueBaseInfo(AlignmentSource::Decl, false)); 2513 } 2514 2515 LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) { 2516 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E), 2517 E->getType(), 2518 LValueBaseInfo(AlignmentSource::Decl, false)); 2519 } 2520 2521 LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) { 2522 auto SL = E->getFunctionName(); 2523 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr"); 2524 StringRef FnName = CurFn->getName(); 2525 if (FnName.startswith("\01")) 2526 FnName = FnName.substr(1); 2527 StringRef NameItems[] = { 2528 PredefinedExpr::getIdentTypeName(E->getIdentType()), FnName}; 2529 std::string GVName = llvm::join(NameItems, NameItems + 2, "."); 2530 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false); 2531 if (auto *BD = dyn_cast<BlockDecl>(CurCodeDecl)) { 2532 std::string Name = SL->getString(); 2533 if (!Name.empty()) { 2534 unsigned Discriminator = 2535 CGM.getCXXABI().getMangleContext().getBlockId(BD, true); 2536 if (Discriminator) 2537 Name += "_" + Twine(Discriminator + 1).str(); 2538 auto C = CGM.GetAddrOfConstantCString(Name, GVName.c_str()); 2539 return MakeAddrLValue(C, E->getType(), BaseInfo); 2540 } else { 2541 auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str()); 2542 return MakeAddrLValue(C, E->getType(), BaseInfo); 2543 } 2544 } 2545 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName); 2546 return MakeAddrLValue(C, E->getType(), BaseInfo); 2547 } 2548 2549 /// Emit a type description suitable for use by a runtime sanitizer library. The 2550 /// format of a type descriptor is 2551 /// 2552 /// \code 2553 /// { i16 TypeKind, i16 TypeInfo } 2554 /// \endcode 2555 /// 2556 /// followed by an array of i8 containing the type name. TypeKind is 0 for an 2557 /// integer, 1 for a floating point value, and -1 for anything else. 2558 llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) { 2559 // Only emit each type's descriptor once. 2560 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T)) 2561 return C; 2562 2563 uint16_t TypeKind = -1; 2564 uint16_t TypeInfo = 0; 2565 2566 if (T->isIntegerType()) { 2567 TypeKind = 0; 2568 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) | 2569 (T->isSignedIntegerType() ? 1 : 0); 2570 } else if (T->isFloatingType()) { 2571 TypeKind = 1; 2572 TypeInfo = getContext().getTypeSize(T); 2573 } 2574 2575 // Format the type name as if for a diagnostic, including quotes and 2576 // optionally an 'aka'. 2577 SmallString<32> Buffer; 2578 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype, 2579 (intptr_t)T.getAsOpaquePtr(), 2580 StringRef(), StringRef(), None, Buffer, 2581 None); 2582 2583 llvm::Constant *Components[] = { 2584 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo), 2585 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer) 2586 }; 2587 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components); 2588 2589 auto *GV = new llvm::GlobalVariable( 2590 CGM.getModule(), Descriptor->getType(), 2591 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor); 2592 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2593 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV); 2594 2595 // Remember the descriptor for this type. 2596 CGM.setTypeDescriptorInMap(T, GV); 2597 2598 return GV; 2599 } 2600 2601 llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) { 2602 llvm::Type *TargetTy = IntPtrTy; 2603 2604 if (V->getType() == TargetTy) 2605 return V; 2606 2607 // Floating-point types which fit into intptr_t are bitcast to integers 2608 // and then passed directly (after zero-extension, if necessary). 2609 if (V->getType()->isFloatingPointTy()) { 2610 unsigned Bits = V->getType()->getPrimitiveSizeInBits(); 2611 if (Bits <= TargetTy->getIntegerBitWidth()) 2612 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(), 2613 Bits)); 2614 } 2615 2616 // Integers which fit in intptr_t are zero-extended and passed directly. 2617 if (V->getType()->isIntegerTy() && 2618 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth()) 2619 return Builder.CreateZExt(V, TargetTy); 2620 2621 // Pointers are passed directly, everything else is passed by address. 2622 if (!V->getType()->isPointerTy()) { 2623 Address Ptr = CreateDefaultAlignTempAlloca(V->getType()); 2624 Builder.CreateStore(V, Ptr); 2625 V = Ptr.getPointer(); 2626 } 2627 return Builder.CreatePtrToInt(V, TargetTy); 2628 } 2629 2630 /// \brief Emit a representation of a SourceLocation for passing to a handler 2631 /// in a sanitizer runtime library. The format for this data is: 2632 /// \code 2633 /// struct SourceLocation { 2634 /// const char *Filename; 2635 /// int32_t Line, Column; 2636 /// }; 2637 /// \endcode 2638 /// For an invalid SourceLocation, the Filename pointer is null. 2639 llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) { 2640 llvm::Constant *Filename; 2641 int Line, Column; 2642 2643 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc); 2644 if (PLoc.isValid()) { 2645 StringRef FilenameString = PLoc.getFilename(); 2646 2647 int PathComponentsToStrip = 2648 CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip; 2649 if (PathComponentsToStrip < 0) { 2650 assert(PathComponentsToStrip != INT_MIN); 2651 int PathComponentsToKeep = -PathComponentsToStrip; 2652 auto I = llvm::sys::path::rbegin(FilenameString); 2653 auto E = llvm::sys::path::rend(FilenameString); 2654 while (I != E && --PathComponentsToKeep) 2655 ++I; 2656 2657 FilenameString = FilenameString.substr(I - E); 2658 } else if (PathComponentsToStrip > 0) { 2659 auto I = llvm::sys::path::begin(FilenameString); 2660 auto E = llvm::sys::path::end(FilenameString); 2661 while (I != E && PathComponentsToStrip--) 2662 ++I; 2663 2664 if (I != E) 2665 FilenameString = 2666 FilenameString.substr(I - llvm::sys::path::begin(FilenameString)); 2667 else 2668 FilenameString = llvm::sys::path::filename(FilenameString); 2669 } 2670 2671 auto FilenameGV = CGM.GetAddrOfConstantCString(FilenameString, ".src"); 2672 CGM.getSanitizerMetadata()->disableSanitizerForGlobal( 2673 cast<llvm::GlobalVariable>(FilenameGV.getPointer())); 2674 Filename = FilenameGV.getPointer(); 2675 Line = PLoc.getLine(); 2676 Column = PLoc.getColumn(); 2677 } else { 2678 Filename = llvm::Constant::getNullValue(Int8PtrTy); 2679 Line = Column = 0; 2680 } 2681 2682 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line), 2683 Builder.getInt32(Column)}; 2684 2685 return llvm::ConstantStruct::getAnon(Data); 2686 } 2687 2688 namespace { 2689 /// \brief Specify under what conditions this check can be recovered 2690 enum class CheckRecoverableKind { 2691 /// Always terminate program execution if this check fails. 2692 Unrecoverable, 2693 /// Check supports recovering, runtime has both fatal (noreturn) and 2694 /// non-fatal handlers for this check. 2695 Recoverable, 2696 /// Runtime conditionally aborts, always need to support recovery. 2697 AlwaysRecoverable 2698 }; 2699 } 2700 2701 static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) { 2702 assert(llvm::countPopulation(Kind) == 1); 2703 switch (Kind) { 2704 case SanitizerKind::Vptr: 2705 return CheckRecoverableKind::AlwaysRecoverable; 2706 case SanitizerKind::Return: 2707 case SanitizerKind::Unreachable: 2708 return CheckRecoverableKind::Unrecoverable; 2709 default: 2710 return CheckRecoverableKind::Recoverable; 2711 } 2712 } 2713 2714 namespace { 2715 struct SanitizerHandlerInfo { 2716 char const *const Name; 2717 unsigned Version; 2718 }; 2719 } 2720 2721 const SanitizerHandlerInfo SanitizerHandlers[] = { 2722 #define SANITIZER_CHECK(Enum, Name, Version) {#Name, Version}, 2723 LIST_SANITIZER_CHECKS 2724 #undef SANITIZER_CHECK 2725 }; 2726 2727 static void emitCheckHandlerCall(CodeGenFunction &CGF, 2728 llvm::FunctionType *FnType, 2729 ArrayRef<llvm::Value *> FnArgs, 2730 SanitizerHandler CheckHandler, 2731 CheckRecoverableKind RecoverKind, bool IsFatal, 2732 llvm::BasicBlock *ContBB) { 2733 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable); 2734 bool NeedsAbortSuffix = 2735 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable; 2736 bool MinimalRuntime = CGF.CGM.getCodeGenOpts().SanitizeMinimalRuntime; 2737 const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler]; 2738 const StringRef CheckName = CheckInfo.Name; 2739 std::string FnName = "__ubsan_handle_" + CheckName.str(); 2740 if (CheckInfo.Version && !MinimalRuntime) 2741 FnName += "_v" + llvm::utostr(CheckInfo.Version); 2742 if (MinimalRuntime) 2743 FnName += "_minimal"; 2744 if (NeedsAbortSuffix) 2745 FnName += "_abort"; 2746 bool MayReturn = 2747 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable; 2748 2749 llvm::AttrBuilder B; 2750 if (!MayReturn) { 2751 B.addAttribute(llvm::Attribute::NoReturn) 2752 .addAttribute(llvm::Attribute::NoUnwind); 2753 } 2754 B.addAttribute(llvm::Attribute::UWTable); 2755 2756 llvm::Value *Fn = CGF.CGM.CreateRuntimeFunction( 2757 FnType, FnName, 2758 llvm::AttributeList::get(CGF.getLLVMContext(), 2759 llvm::AttributeList::FunctionIndex, B), 2760 /*Local=*/true); 2761 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs); 2762 if (!MayReturn) { 2763 HandlerCall->setDoesNotReturn(); 2764 CGF.Builder.CreateUnreachable(); 2765 } else { 2766 CGF.Builder.CreateBr(ContBB); 2767 } 2768 } 2769 2770 void CodeGenFunction::EmitCheck( 2771 ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked, 2772 SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs, 2773 ArrayRef<llvm::Value *> DynamicArgs) { 2774 assert(IsSanitizerScope); 2775 assert(Checked.size() > 0); 2776 assert(CheckHandler >= 0 && 2777 CheckHandler < sizeof(SanitizerHandlers) / sizeof(*SanitizerHandlers)); 2778 const StringRef CheckName = SanitizerHandlers[CheckHandler].Name; 2779 2780 llvm::Value *FatalCond = nullptr; 2781 llvm::Value *RecoverableCond = nullptr; 2782 llvm::Value *TrapCond = nullptr; 2783 for (int i = 0, n = Checked.size(); i < n; ++i) { 2784 llvm::Value *Check = Checked[i].first; 2785 // -fsanitize-trap= overrides -fsanitize-recover=. 2786 llvm::Value *&Cond = 2787 CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second) 2788 ? TrapCond 2789 : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second) 2790 ? RecoverableCond 2791 : FatalCond; 2792 Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check; 2793 } 2794 2795 if (TrapCond) 2796 EmitTrapCheck(TrapCond); 2797 if (!FatalCond && !RecoverableCond) 2798 return; 2799 2800 llvm::Value *JointCond; 2801 if (FatalCond && RecoverableCond) 2802 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond); 2803 else 2804 JointCond = FatalCond ? FatalCond : RecoverableCond; 2805 assert(JointCond); 2806 2807 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second); 2808 assert(SanOpts.has(Checked[0].second)); 2809 #ifndef NDEBUG 2810 for (int i = 1, n = Checked.size(); i < n; ++i) { 2811 assert(RecoverKind == getRecoverableKind(Checked[i].second) && 2812 "All recoverable kinds in a single check must be same!"); 2813 assert(SanOpts.has(Checked[i].second)); 2814 } 2815 #endif 2816 2817 llvm::BasicBlock *Cont = createBasicBlock("cont"); 2818 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName); 2819 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers); 2820 // Give hint that we very much don't expect to execute the handler 2821 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp 2822 llvm::MDBuilder MDHelper(getLLVMContext()); 2823 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1); 2824 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node); 2825 EmitBlock(Handlers); 2826 2827 // Handler functions take an i8* pointing to the (handler-specific) static 2828 // information block, followed by a sequence of intptr_t arguments 2829 // representing operand values. 2830 SmallVector<llvm::Value *, 4> Args; 2831 SmallVector<llvm::Type *, 4> ArgTypes; 2832 if (!CGM.getCodeGenOpts().SanitizeMinimalRuntime) { 2833 Args.reserve(DynamicArgs.size() + 1); 2834 ArgTypes.reserve(DynamicArgs.size() + 1); 2835 2836 // Emit handler arguments and create handler function type. 2837 if (!StaticArgs.empty()) { 2838 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs); 2839 auto *InfoPtr = 2840 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false, 2841 llvm::GlobalVariable::PrivateLinkage, Info); 2842 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2843 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr); 2844 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy)); 2845 ArgTypes.push_back(Int8PtrTy); 2846 } 2847 2848 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) { 2849 Args.push_back(EmitCheckValue(DynamicArgs[i])); 2850 ArgTypes.push_back(IntPtrTy); 2851 } 2852 } 2853 2854 llvm::FunctionType *FnType = 2855 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false); 2856 2857 if (!FatalCond || !RecoverableCond) { 2858 // Simple case: we need to generate a single handler call, either 2859 // fatal, or non-fatal. 2860 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, 2861 (FatalCond != nullptr), Cont); 2862 } else { 2863 // Emit two handler calls: first one for set of unrecoverable checks, 2864 // another one for recoverable. 2865 llvm::BasicBlock *NonFatalHandlerBB = 2866 createBasicBlock("non_fatal." + CheckName); 2867 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName); 2868 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB); 2869 EmitBlock(FatalHandlerBB); 2870 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true, 2871 NonFatalHandlerBB); 2872 EmitBlock(NonFatalHandlerBB); 2873 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false, 2874 Cont); 2875 } 2876 2877 EmitBlock(Cont); 2878 } 2879 2880 void CodeGenFunction::EmitCfiSlowPathCheck( 2881 SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId, 2882 llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) { 2883 llvm::BasicBlock *Cont = createBasicBlock("cfi.cont"); 2884 2885 llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath"); 2886 llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB); 2887 2888 llvm::MDBuilder MDHelper(getLLVMContext()); 2889 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1); 2890 BI->setMetadata(llvm::LLVMContext::MD_prof, Node); 2891 2892 EmitBlock(CheckBB); 2893 2894 bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind); 2895 2896 llvm::CallInst *CheckCall; 2897 if (WithDiag) { 2898 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs); 2899 auto *InfoPtr = 2900 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false, 2901 llvm::GlobalVariable::PrivateLinkage, Info); 2902 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2903 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr); 2904 2905 llvm::Constant *SlowPathDiagFn = CGM.getModule().getOrInsertFunction( 2906 "__cfi_slowpath_diag", 2907 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, 2908 false)); 2909 CheckCall = Builder.CreateCall( 2910 SlowPathDiagFn, 2911 {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)}); 2912 } else { 2913 llvm::Constant *SlowPathFn = CGM.getModule().getOrInsertFunction( 2914 "__cfi_slowpath", 2915 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false)); 2916 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr}); 2917 } 2918 2919 CheckCall->setDoesNotThrow(); 2920 2921 EmitBlock(Cont); 2922 } 2923 2924 // Emit a stub for __cfi_check function so that the linker knows about this 2925 // symbol in LTO mode. 2926 void CodeGenFunction::EmitCfiCheckStub() { 2927 llvm::Module *M = &CGM.getModule(); 2928 auto &Ctx = M->getContext(); 2929 llvm::Function *F = llvm::Function::Create( 2930 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, false), 2931 llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M); 2932 llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F); 2933 // FIXME: consider emitting an intrinsic call like 2934 // call void @llvm.cfi_check(i64 %0, i8* %1, i8* %2) 2935 // which can be lowered in CrossDSOCFI pass to the actual contents of 2936 // __cfi_check. This would allow inlining of __cfi_check calls. 2937 llvm::CallInst::Create( 2938 llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::trap), "", BB); 2939 llvm::ReturnInst::Create(Ctx, nullptr, BB); 2940 } 2941 2942 // This function is basically a switch over the CFI failure kind, which is 2943 // extracted from CFICheckFailData (1st function argument). Each case is either 2944 // llvm.trap or a call to one of the two runtime handlers, based on 2945 // -fsanitize-trap and -fsanitize-recover settings. Default case (invalid 2946 // failure kind) traps, but this should really never happen. CFICheckFailData 2947 // can be nullptr if the calling module has -fsanitize-trap behavior for this 2948 // check kind; in this case __cfi_check_fail traps as well. 2949 void CodeGenFunction::EmitCfiCheckFail() { 2950 SanitizerScope SanScope(this); 2951 FunctionArgList Args; 2952 ImplicitParamDecl ArgData(getContext(), getContext().VoidPtrTy, 2953 ImplicitParamDecl::Other); 2954 ImplicitParamDecl ArgAddr(getContext(), getContext().VoidPtrTy, 2955 ImplicitParamDecl::Other); 2956 Args.push_back(&ArgData); 2957 Args.push_back(&ArgAddr); 2958 2959 const CGFunctionInfo &FI = 2960 CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args); 2961 2962 llvm::Function *F = llvm::Function::Create( 2963 llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false), 2964 llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule()); 2965 F->setVisibility(llvm::GlobalValue::HiddenVisibility); 2966 2967 StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args, 2968 SourceLocation()); 2969 2970 llvm::Value *Data = 2971 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false, 2972 CGM.getContext().VoidPtrTy, ArgData.getLocation()); 2973 llvm::Value *Addr = 2974 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false, 2975 CGM.getContext().VoidPtrTy, ArgAddr.getLocation()); 2976 2977 // Data == nullptr means the calling module has trap behaviour for this check. 2978 llvm::Value *DataIsNotNullPtr = 2979 Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy)); 2980 EmitTrapCheck(DataIsNotNullPtr); 2981 2982 llvm::StructType *SourceLocationTy = 2983 llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty); 2984 llvm::StructType *CfiCheckFailDataTy = 2985 llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy); 2986 2987 llvm::Value *V = Builder.CreateConstGEP2_32( 2988 CfiCheckFailDataTy, 2989 Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0, 2990 0); 2991 Address CheckKindAddr(V, getIntAlign()); 2992 llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr); 2993 2994 llvm::Value *AllVtables = llvm::MetadataAsValue::get( 2995 CGM.getLLVMContext(), 2996 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables")); 2997 llvm::Value *ValidVtable = Builder.CreateZExt( 2998 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test), 2999 {Addr, AllVtables}), 3000 IntPtrTy); 3001 3002 const std::pair<int, SanitizerMask> CheckKinds[] = { 3003 {CFITCK_VCall, SanitizerKind::CFIVCall}, 3004 {CFITCK_NVCall, SanitizerKind::CFINVCall}, 3005 {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast}, 3006 {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast}, 3007 {CFITCK_ICall, SanitizerKind::CFIICall}}; 3008 3009 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks; 3010 for (auto CheckKindMaskPair : CheckKinds) { 3011 int Kind = CheckKindMaskPair.first; 3012 SanitizerMask Mask = CheckKindMaskPair.second; 3013 llvm::Value *Cond = 3014 Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind)); 3015 if (CGM.getLangOpts().Sanitize.has(Mask)) 3016 EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {}, 3017 {Data, Addr, ValidVtable}); 3018 else 3019 EmitTrapCheck(Cond); 3020 } 3021 3022 FinishFunction(); 3023 // The only reference to this function will be created during LTO link. 3024 // Make sure it survives until then. 3025 CGM.addUsedGlobal(F); 3026 } 3027 3028 void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) { 3029 llvm::BasicBlock *Cont = createBasicBlock("cont"); 3030 3031 // If we're optimizing, collapse all calls to trap down to just one per 3032 // function to save on code size. 3033 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) { 3034 TrapBB = createBasicBlock("trap"); 3035 Builder.CreateCondBr(Checked, Cont, TrapBB); 3036 EmitBlock(TrapBB); 3037 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap); 3038 TrapCall->setDoesNotReturn(); 3039 TrapCall->setDoesNotThrow(); 3040 Builder.CreateUnreachable(); 3041 } else { 3042 Builder.CreateCondBr(Checked, Cont, TrapBB); 3043 } 3044 3045 EmitBlock(Cont); 3046 } 3047 3048 llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) { 3049 llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID)); 3050 3051 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) { 3052 auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name", 3053 CGM.getCodeGenOpts().TrapFuncName); 3054 TrapCall->addAttribute(llvm::AttributeList::FunctionIndex, A); 3055 } 3056 3057 return TrapCall; 3058 } 3059 3060 Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E, 3061 LValueBaseInfo *BaseInfo) { 3062 assert(E->getType()->isArrayType() && 3063 "Array to pointer decay must have array source type!"); 3064 3065 // Expressions of array type can't be bitfields or vector elements. 3066 LValue LV = EmitLValue(E); 3067 Address Addr = LV.getAddress(); 3068 if (BaseInfo) *BaseInfo = LV.getBaseInfo(); 3069 3070 // If the array type was an incomplete type, we need to make sure 3071 // the decay ends up being the right type. 3072 llvm::Type *NewTy = ConvertType(E->getType()); 3073 Addr = Builder.CreateElementBitCast(Addr, NewTy); 3074 3075 // Note that VLA pointers are always decayed, so we don't need to do 3076 // anything here. 3077 if (!E->getType()->isVariableArrayType()) { 3078 assert(isa<llvm::ArrayType>(Addr.getElementType()) && 3079 "Expected pointer to array"); 3080 Addr = Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(), "arraydecay"); 3081 } 3082 3083 QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType(); 3084 return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType)); 3085 } 3086 3087 /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an 3088 /// array to pointer, return the array subexpression. 3089 static const Expr *isSimpleArrayDecayOperand(const Expr *E) { 3090 // If this isn't just an array->pointer decay, bail out. 3091 const auto *CE = dyn_cast<CastExpr>(E); 3092 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay) 3093 return nullptr; 3094 3095 // If this is a decay from variable width array, bail out. 3096 const Expr *SubExpr = CE->getSubExpr(); 3097 if (SubExpr->getType()->isVariableArrayType()) 3098 return nullptr; 3099 3100 return SubExpr; 3101 } 3102 3103 static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF, 3104 llvm::Value *ptr, 3105 ArrayRef<llvm::Value*> indices, 3106 bool inbounds, 3107 bool signedIndices, 3108 SourceLocation loc, 3109 const llvm::Twine &name = "arrayidx") { 3110 if (inbounds) { 3111 return CGF.EmitCheckedInBoundsGEP(ptr, indices, signedIndices, 3112 CodeGenFunction::NotSubtraction, loc, 3113 name); 3114 } else { 3115 return CGF.Builder.CreateGEP(ptr, indices, name); 3116 } 3117 } 3118 3119 static CharUnits getArrayElementAlign(CharUnits arrayAlign, 3120 llvm::Value *idx, 3121 CharUnits eltSize) { 3122 // If we have a constant index, we can use the exact offset of the 3123 // element we're accessing. 3124 if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) { 3125 CharUnits offset = constantIdx->getZExtValue() * eltSize; 3126 return arrayAlign.alignmentAtOffset(offset); 3127 3128 // Otherwise, use the worst-case alignment for any element. 3129 } else { 3130 return arrayAlign.alignmentOfArrayElement(eltSize); 3131 } 3132 } 3133 3134 static QualType getFixedSizeElementType(const ASTContext &ctx, 3135 const VariableArrayType *vla) { 3136 QualType eltType; 3137 do { 3138 eltType = vla->getElementType(); 3139 } while ((vla = ctx.getAsVariableArrayType(eltType))); 3140 return eltType; 3141 } 3142 3143 static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr, 3144 ArrayRef<llvm::Value *> indices, 3145 QualType eltType, bool inbounds, 3146 bool signedIndices, SourceLocation loc, 3147 const llvm::Twine &name = "arrayidx") { 3148 // All the indices except that last must be zero. 3149 #ifndef NDEBUG 3150 for (auto idx : indices.drop_back()) 3151 assert(isa<llvm::ConstantInt>(idx) && 3152 cast<llvm::ConstantInt>(idx)->isZero()); 3153 #endif 3154 3155 // Determine the element size of the statically-sized base. This is 3156 // the thing that the indices are expressed in terms of. 3157 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) { 3158 eltType = getFixedSizeElementType(CGF.getContext(), vla); 3159 } 3160 3161 // We can use that to compute the best alignment of the element. 3162 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType); 3163 CharUnits eltAlign = 3164 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize); 3165 3166 llvm::Value *eltPtr = emitArraySubscriptGEP( 3167 CGF, addr.getPointer(), indices, inbounds, signedIndices, loc, name); 3168 return Address(eltPtr, eltAlign); 3169 } 3170 3171 LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E, 3172 bool Accessed) { 3173 // The index must always be an integer, which is not an aggregate. Emit it 3174 // in lexical order (this complexity is, sadly, required by C++17). 3175 llvm::Value *IdxPre = 3176 (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr; 3177 bool SignedIndices = false; 3178 auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * { 3179 auto *Idx = IdxPre; 3180 if (E->getLHS() != E->getIdx()) { 3181 assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS"); 3182 Idx = EmitScalarExpr(E->getIdx()); 3183 } 3184 3185 QualType IdxTy = E->getIdx()->getType(); 3186 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType(); 3187 SignedIndices |= IdxSigned; 3188 3189 if (SanOpts.has(SanitizerKind::ArrayBounds)) 3190 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed); 3191 3192 // Extend or truncate the index type to 32 or 64-bits. 3193 if (Promote && Idx->getType() != IntPtrTy) 3194 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom"); 3195 3196 return Idx; 3197 }; 3198 IdxPre = nullptr; 3199 3200 // If the base is a vector type, then we are forming a vector element lvalue 3201 // with this subscript. 3202 if (E->getBase()->getType()->isVectorType() && 3203 !isa<ExtVectorElementExpr>(E->getBase())) { 3204 // Emit the vector as an lvalue to get its address. 3205 LValue LHS = EmitLValue(E->getBase()); 3206 auto *Idx = EmitIdxAfterBase(/*Promote*/false); 3207 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!"); 3208 return LValue::MakeVectorElt(LHS.getAddress(), Idx, 3209 E->getBase()->getType(), 3210 LHS.getBaseInfo()); 3211 } 3212 3213 // All the other cases basically behave like simple offsetting. 3214 3215 // Handle the extvector case we ignored above. 3216 if (isa<ExtVectorElementExpr>(E->getBase())) { 3217 LValue LV = EmitLValue(E->getBase()); 3218 auto *Idx = EmitIdxAfterBase(/*Promote*/true); 3219 Address Addr = EmitExtVectorElementLValue(LV); 3220 3221 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType(); 3222 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true, 3223 SignedIndices, E->getExprLoc()); 3224 return MakeAddrLValue(Addr, EltType, LV.getBaseInfo()); 3225 } 3226 3227 LValueBaseInfo BaseInfo; 3228 Address Addr = Address::invalid(); 3229 if (const VariableArrayType *vla = 3230 getContext().getAsVariableArrayType(E->getType())) { 3231 // The base must be a pointer, which is not an aggregate. Emit 3232 // it. It needs to be emitted first in case it's what captures 3233 // the VLA bounds. 3234 Addr = EmitPointerWithAlignment(E->getBase(), &BaseInfo); 3235 auto *Idx = EmitIdxAfterBase(/*Promote*/true); 3236 3237 // The element count here is the total number of non-VLA elements. 3238 llvm::Value *numElements = getVLASize(vla).first; 3239 3240 // Effectively, the multiply by the VLA size is part of the GEP. 3241 // GEP indexes are signed, and scaling an index isn't permitted to 3242 // signed-overflow, so we use the same semantics for our explicit 3243 // multiply. We suppress this if overflow is not undefined behavior. 3244 if (getLangOpts().isSignedOverflowDefined()) { 3245 Idx = Builder.CreateMul(Idx, numElements); 3246 } else { 3247 Idx = Builder.CreateNSWMul(Idx, numElements); 3248 } 3249 3250 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(), 3251 !getLangOpts().isSignedOverflowDefined(), 3252 SignedIndices, E->getExprLoc()); 3253 3254 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){ 3255 // Indexing over an interface, as in "NSString *P; P[4];" 3256 3257 // Emit the base pointer. 3258 Addr = EmitPointerWithAlignment(E->getBase(), &BaseInfo); 3259 auto *Idx = EmitIdxAfterBase(/*Promote*/true); 3260 3261 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT); 3262 llvm::Value *InterfaceSizeVal = 3263 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity()); 3264 3265 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal); 3266 3267 // We don't necessarily build correct LLVM struct types for ObjC 3268 // interfaces, so we can't rely on GEP to do this scaling 3269 // correctly, so we need to cast to i8*. FIXME: is this actually 3270 // true? A lot of other things in the fragile ABI would break... 3271 llvm::Type *OrigBaseTy = Addr.getType(); 3272 Addr = Builder.CreateElementBitCast(Addr, Int8Ty); 3273 3274 // Do the GEP. 3275 CharUnits EltAlign = 3276 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize); 3277 llvm::Value *EltPtr = 3278 emitArraySubscriptGEP(*this, Addr.getPointer(), ScaledIdx, false, 3279 SignedIndices, E->getExprLoc()); 3280 Addr = Address(EltPtr, EltAlign); 3281 3282 // Cast back. 3283 Addr = Builder.CreateBitCast(Addr, OrigBaseTy); 3284 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) { 3285 // If this is A[i] where A is an array, the frontend will have decayed the 3286 // base to be a ArrayToPointerDecay implicit cast. While correct, it is 3287 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a 3288 // "gep x, i" here. Emit one "gep A, 0, i". 3289 assert(Array->getType()->isArrayType() && 3290 "Array to pointer decay must have array source type!"); 3291 LValue ArrayLV; 3292 // For simple multidimensional array indexing, set the 'accessed' flag for 3293 // better bounds-checking of the base expression. 3294 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array)) 3295 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true); 3296 else 3297 ArrayLV = EmitLValue(Array); 3298 auto *Idx = EmitIdxAfterBase(/*Promote*/true); 3299 3300 // Propagate the alignment from the array itself to the result. 3301 Addr = emitArraySubscriptGEP( 3302 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx}, 3303 E->getType(), !getLangOpts().isSignedOverflowDefined(), SignedIndices, 3304 E->getExprLoc()); 3305 BaseInfo = ArrayLV.getBaseInfo(); 3306 } else { 3307 // The base must be a pointer; emit it with an estimate of its alignment. 3308 Addr = EmitPointerWithAlignment(E->getBase(), &BaseInfo); 3309 auto *Idx = EmitIdxAfterBase(/*Promote*/true); 3310 Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(), 3311 !getLangOpts().isSignedOverflowDefined(), 3312 SignedIndices, E->getExprLoc()); 3313 } 3314 3315 LValue LV = MakeAddrLValue(Addr, E->getType(), BaseInfo); 3316 3317 // TODO: Preserve/extend path TBAA metadata? 3318 3319 if (getLangOpts().ObjC1 && 3320 getLangOpts().getGC() != LangOptions::NonGC) { 3321 LV.setNonGC(!E->isOBJCGCCandidate(getContext())); 3322 setObjCGCLValueClass(getContext(), E, LV); 3323 } 3324 return LV; 3325 } 3326 3327 static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base, 3328 LValueBaseInfo &BaseInfo, 3329 QualType BaseTy, QualType ElTy, 3330 bool IsLowerBound) { 3331 LValue BaseLVal; 3332 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) { 3333 BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound); 3334 if (BaseTy->isArrayType()) { 3335 Address Addr = BaseLVal.getAddress(); 3336 BaseInfo = BaseLVal.getBaseInfo(); 3337 3338 // If the array type was an incomplete type, we need to make sure 3339 // the decay ends up being the right type. 3340 llvm::Type *NewTy = CGF.ConvertType(BaseTy); 3341 Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy); 3342 3343 // Note that VLA pointers are always decayed, so we don't need to do 3344 // anything here. 3345 if (!BaseTy->isVariableArrayType()) { 3346 assert(isa<llvm::ArrayType>(Addr.getElementType()) && 3347 "Expected pointer to array"); 3348 Addr = CGF.Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(), 3349 "arraydecay"); 3350 } 3351 3352 return CGF.Builder.CreateElementBitCast(Addr, 3353 CGF.ConvertTypeForMem(ElTy)); 3354 } 3355 LValueBaseInfo TypeInfo; 3356 CharUnits Align = CGF.getNaturalTypeAlignment(ElTy, &TypeInfo); 3357 BaseInfo.mergeForCast(TypeInfo); 3358 return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress()), Align); 3359 } 3360 return CGF.EmitPointerWithAlignment(Base, &BaseInfo); 3361 } 3362 3363 LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E, 3364 bool IsLowerBound) { 3365 QualType BaseTy; 3366 if (auto *ASE = 3367 dyn_cast<OMPArraySectionExpr>(E->getBase()->IgnoreParenImpCasts())) 3368 BaseTy = OMPArraySectionExpr::getBaseOriginalType(ASE); 3369 else 3370 BaseTy = E->getBase()->getType(); 3371 QualType ResultExprTy; 3372 if (auto *AT = getContext().getAsArrayType(BaseTy)) 3373 ResultExprTy = AT->getElementType(); 3374 else 3375 ResultExprTy = BaseTy->getPointeeType(); 3376 llvm::Value *Idx = nullptr; 3377 if (IsLowerBound || E->getColonLoc().isInvalid()) { 3378 // Requesting lower bound or upper bound, but without provided length and 3379 // without ':' symbol for the default length -> length = 1. 3380 // Idx = LowerBound ?: 0; 3381 if (auto *LowerBound = E->getLowerBound()) { 3382 Idx = Builder.CreateIntCast( 3383 EmitScalarExpr(LowerBound), IntPtrTy, 3384 LowerBound->getType()->hasSignedIntegerRepresentation()); 3385 } else 3386 Idx = llvm::ConstantInt::getNullValue(IntPtrTy); 3387 } else { 3388 // Try to emit length or lower bound as constant. If this is possible, 1 3389 // is subtracted from constant length or lower bound. Otherwise, emit LLVM 3390 // IR (LB + Len) - 1. 3391 auto &C = CGM.getContext(); 3392 auto *Length = E->getLength(); 3393 llvm::APSInt ConstLength; 3394 if (Length) { 3395 // Idx = LowerBound + Length - 1; 3396 if (Length->isIntegerConstantExpr(ConstLength, C)) { 3397 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits); 3398 Length = nullptr; 3399 } 3400 auto *LowerBound = E->getLowerBound(); 3401 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false); 3402 if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) { 3403 ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits); 3404 LowerBound = nullptr; 3405 } 3406 if (!Length) 3407 --ConstLength; 3408 else if (!LowerBound) 3409 --ConstLowerBound; 3410 3411 if (Length || LowerBound) { 3412 auto *LowerBoundVal = 3413 LowerBound 3414 ? Builder.CreateIntCast( 3415 EmitScalarExpr(LowerBound), IntPtrTy, 3416 LowerBound->getType()->hasSignedIntegerRepresentation()) 3417 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound); 3418 auto *LengthVal = 3419 Length 3420 ? Builder.CreateIntCast( 3421 EmitScalarExpr(Length), IntPtrTy, 3422 Length->getType()->hasSignedIntegerRepresentation()) 3423 : llvm::ConstantInt::get(IntPtrTy, ConstLength); 3424 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len", 3425 /*HasNUW=*/false, 3426 !getLangOpts().isSignedOverflowDefined()); 3427 if (Length && LowerBound) { 3428 Idx = Builder.CreateSub( 3429 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1", 3430 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined()); 3431 } 3432 } else 3433 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound); 3434 } else { 3435 // Idx = ArraySize - 1; 3436 QualType ArrayTy = BaseTy->isPointerType() 3437 ? E->getBase()->IgnoreParenImpCasts()->getType() 3438 : BaseTy; 3439 if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) { 3440 Length = VAT->getSizeExpr(); 3441 if (Length->isIntegerConstantExpr(ConstLength, C)) 3442 Length = nullptr; 3443 } else { 3444 auto *CAT = C.getAsConstantArrayType(ArrayTy); 3445 ConstLength = CAT->getSize(); 3446 } 3447 if (Length) { 3448 auto *LengthVal = Builder.CreateIntCast( 3449 EmitScalarExpr(Length), IntPtrTy, 3450 Length->getType()->hasSignedIntegerRepresentation()); 3451 Idx = Builder.CreateSub( 3452 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1", 3453 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined()); 3454 } else { 3455 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits); 3456 --ConstLength; 3457 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength); 3458 } 3459 } 3460 } 3461 assert(Idx); 3462 3463 Address EltPtr = Address::invalid(); 3464 LValueBaseInfo BaseInfo; 3465 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) { 3466 // The base must be a pointer, which is not an aggregate. Emit 3467 // it. It needs to be emitted first in case it's what captures 3468 // the VLA bounds. 3469 Address Base = 3470 emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, BaseTy, 3471 VLA->getElementType(), IsLowerBound); 3472 // The element count here is the total number of non-VLA elements. 3473 llvm::Value *NumElements = getVLASize(VLA).first; 3474 3475 // Effectively, the multiply by the VLA size is part of the GEP. 3476 // GEP indexes are signed, and scaling an index isn't permitted to 3477 // signed-overflow, so we use the same semantics for our explicit 3478 // multiply. We suppress this if overflow is not undefined behavior. 3479 if (getLangOpts().isSignedOverflowDefined()) 3480 Idx = Builder.CreateMul(Idx, NumElements); 3481 else 3482 Idx = Builder.CreateNSWMul(Idx, NumElements); 3483 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(), 3484 !getLangOpts().isSignedOverflowDefined(), 3485 /*SignedIndices=*/false, E->getExprLoc()); 3486 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) { 3487 // If this is A[i] where A is an array, the frontend will have decayed the 3488 // base to be a ArrayToPointerDecay implicit cast. While correct, it is 3489 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a 3490 // "gep x, i" here. Emit one "gep A, 0, i". 3491 assert(Array->getType()->isArrayType() && 3492 "Array to pointer decay must have array source type!"); 3493 LValue ArrayLV; 3494 // For simple multidimensional array indexing, set the 'accessed' flag for 3495 // better bounds-checking of the base expression. 3496 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array)) 3497 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true); 3498 else 3499 ArrayLV = EmitLValue(Array); 3500 3501 // Propagate the alignment from the array itself to the result. 3502 EltPtr = emitArraySubscriptGEP( 3503 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx}, 3504 ResultExprTy, !getLangOpts().isSignedOverflowDefined(), 3505 /*SignedIndices=*/false, E->getExprLoc()); 3506 BaseInfo = ArrayLV.getBaseInfo(); 3507 } else { 3508 Address Base = emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, 3509 BaseTy, ResultExprTy, IsLowerBound); 3510 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy, 3511 !getLangOpts().isSignedOverflowDefined(), 3512 /*SignedIndices=*/false, E->getExprLoc()); 3513 } 3514 3515 return MakeAddrLValue(EltPtr, ResultExprTy, BaseInfo); 3516 } 3517 3518 LValue CodeGenFunction:: 3519 EmitExtVectorElementExpr(const ExtVectorElementExpr *E) { 3520 // Emit the base vector as an l-value. 3521 LValue Base; 3522 3523 // ExtVectorElementExpr's base can either be a vector or pointer to vector. 3524 if (E->isArrow()) { 3525 // If it is a pointer to a vector, emit the address and form an lvalue with 3526 // it. 3527 LValueBaseInfo BaseInfo; 3528 Address Ptr = EmitPointerWithAlignment(E->getBase(), &BaseInfo); 3529 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>(); 3530 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), BaseInfo); 3531 Base.getQuals().removeObjCGCAttr(); 3532 } else if (E->getBase()->isGLValue()) { 3533 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x), 3534 // emit the base as an lvalue. 3535 assert(E->getBase()->getType()->isVectorType()); 3536 Base = EmitLValue(E->getBase()); 3537 } else { 3538 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such. 3539 assert(E->getBase()->getType()->isVectorType() && 3540 "Result must be a vector"); 3541 llvm::Value *Vec = EmitScalarExpr(E->getBase()); 3542 3543 // Store the vector to memory (because LValue wants an address). 3544 Address VecMem = CreateMemTemp(E->getBase()->getType()); 3545 Builder.CreateStore(Vec, VecMem); 3546 Base = MakeAddrLValue(VecMem, E->getBase()->getType(), 3547 LValueBaseInfo(AlignmentSource::Decl, false)); 3548 } 3549 3550 QualType type = 3551 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers()); 3552 3553 // Encode the element access list into a vector of unsigned indices. 3554 SmallVector<uint32_t, 4> Indices; 3555 E->getEncodedElementAccess(Indices); 3556 3557 if (Base.isSimple()) { 3558 llvm::Constant *CV = 3559 llvm::ConstantDataVector::get(getLLVMContext(), Indices); 3560 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type, 3561 Base.getBaseInfo()); 3562 } 3563 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!"); 3564 3565 llvm::Constant *BaseElts = Base.getExtVectorElts(); 3566 SmallVector<llvm::Constant *, 4> CElts; 3567 3568 for (unsigned i = 0, e = Indices.size(); i != e; ++i) 3569 CElts.push_back(BaseElts->getAggregateElement(Indices[i])); 3570 llvm::Constant *CV = llvm::ConstantVector::get(CElts); 3571 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type, 3572 Base.getBaseInfo()); 3573 } 3574 3575 LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) { 3576 if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, E)) { 3577 EmitIgnoredExpr(E->getBase()); 3578 return EmitDeclRefLValue(DRE); 3579 } 3580 3581 Expr *BaseExpr = E->getBase(); 3582 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar. 3583 LValue BaseLV; 3584 if (E->isArrow()) { 3585 LValueBaseInfo BaseInfo; 3586 Address Addr = EmitPointerWithAlignment(BaseExpr, &BaseInfo); 3587 QualType PtrTy = BaseExpr->getType()->getPointeeType(); 3588 SanitizerSet SkippedChecks; 3589 bool IsBaseCXXThis = IsWrappedCXXThis(BaseExpr); 3590 if (IsBaseCXXThis) 3591 SkippedChecks.set(SanitizerKind::Alignment, true); 3592 if (IsBaseCXXThis || isa<DeclRefExpr>(BaseExpr)) 3593 SkippedChecks.set(SanitizerKind::Null, true); 3594 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy, 3595 /*Alignment=*/CharUnits::Zero(), SkippedChecks); 3596 BaseLV = MakeAddrLValue(Addr, PtrTy, BaseInfo); 3597 } else 3598 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess); 3599 3600 NamedDecl *ND = E->getMemberDecl(); 3601 if (auto *Field = dyn_cast<FieldDecl>(ND)) { 3602 LValue LV = EmitLValueForField(BaseLV, Field); 3603 setObjCGCLValueClass(getContext(), E, LV); 3604 return LV; 3605 } 3606 3607 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) 3608 return EmitFunctionDeclLValue(*this, E, FD); 3609 3610 llvm_unreachable("Unhandled member declaration!"); 3611 } 3612 3613 /// Given that we are currently emitting a lambda, emit an l-value for 3614 /// one of its members. 3615 LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) { 3616 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda()); 3617 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent()); 3618 QualType LambdaTagType = 3619 getContext().getTagDeclType(Field->getParent()); 3620 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType); 3621 return EmitLValueForField(LambdaLV, Field); 3622 } 3623 3624 /// Drill down to the storage of a field without walking into 3625 /// reference types. 3626 /// 3627 /// The resulting address doesn't necessarily have the right type. 3628 static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base, 3629 const FieldDecl *field) { 3630 const RecordDecl *rec = field->getParent(); 3631 3632 unsigned idx = 3633 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field); 3634 3635 CharUnits offset; 3636 // Adjust the alignment down to the given offset. 3637 // As a special case, if the LLVM field index is 0, we know that this 3638 // is zero. 3639 assert((idx != 0 || CGF.getContext().getASTRecordLayout(rec) 3640 .getFieldOffset(field->getFieldIndex()) == 0) && 3641 "LLVM field at index zero had non-zero offset?"); 3642 if (idx != 0) { 3643 auto &recLayout = CGF.getContext().getASTRecordLayout(rec); 3644 auto offsetInBits = recLayout.getFieldOffset(field->getFieldIndex()); 3645 offset = CGF.getContext().toCharUnitsFromBits(offsetInBits); 3646 } 3647 3648 return CGF.Builder.CreateStructGEP(base, idx, offset, field->getName()); 3649 } 3650 3651 static bool hasAnyVptr(const QualType Type, const ASTContext &Context) { 3652 const auto *RD = Type.getTypePtr()->getAsCXXRecordDecl(); 3653 if (!RD) 3654 return false; 3655 3656 if (RD->isDynamicClass()) 3657 return true; 3658 3659 for (const auto &Base : RD->bases()) 3660 if (hasAnyVptr(Base.getType(), Context)) 3661 return true; 3662 3663 for (const FieldDecl *Field : RD->fields()) 3664 if (hasAnyVptr(Field->getType(), Context)) 3665 return true; 3666 3667 return false; 3668 } 3669 3670 LValue CodeGenFunction::EmitLValueForField(LValue base, 3671 const FieldDecl *field) { 3672 LValueBaseInfo BaseInfo = base.getBaseInfo(); 3673 AlignmentSource fieldAlignSource = 3674 getFieldAlignmentSource(BaseInfo.getAlignmentSource()); 3675 LValueBaseInfo FieldBaseInfo(fieldAlignSource, BaseInfo.getMayAlias()); 3676 3677 QualType type = field->getType(); 3678 const RecordDecl *rec = field->getParent(); 3679 if (rec->isUnion() || rec->hasAttr<MayAliasAttr>() || type->isVectorType()) 3680 FieldBaseInfo.setMayAlias(true); 3681 bool mayAlias = FieldBaseInfo.getMayAlias(); 3682 3683 if (field->isBitField()) { 3684 const CGRecordLayout &RL = 3685 CGM.getTypes().getCGRecordLayout(field->getParent()); 3686 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field); 3687 Address Addr = base.getAddress(); 3688 unsigned Idx = RL.getLLVMFieldNo(field); 3689 if (Idx != 0) 3690 // For structs, we GEP to the field that the record layout suggests. 3691 Addr = Builder.CreateStructGEP(Addr, Idx, Info.StorageOffset, 3692 field->getName()); 3693 // Get the access type. 3694 llvm::Type *FieldIntTy = 3695 llvm::Type::getIntNTy(getLLVMContext(), Info.StorageSize); 3696 if (Addr.getElementType() != FieldIntTy) 3697 Addr = Builder.CreateElementBitCast(Addr, FieldIntTy); 3698 3699 QualType fieldType = 3700 field->getType().withCVRQualifiers(base.getVRQualifiers()); 3701 return LValue::MakeBitfield(Addr, Info, fieldType, FieldBaseInfo); 3702 } 3703 3704 Address addr = base.getAddress(); 3705 unsigned cvr = base.getVRQualifiers(); 3706 bool TBAAPath = CGM.getCodeGenOpts().StructPathTBAA; 3707 if (rec->isUnion()) { 3708 // For unions, there is no pointer adjustment. 3709 assert(!type->isReferenceType() && "union has reference member"); 3710 // TODO: handle path-aware TBAA for union. 3711 TBAAPath = false; 3712 3713 const auto FieldType = field->getType(); 3714 if (CGM.getCodeGenOpts().StrictVTablePointers && 3715 hasAnyVptr(FieldType, getContext())) 3716 // Because unions can easily skip invariant.barriers, we need to add 3717 // a barrier every time CXXRecord field with vptr is referenced. 3718 addr = Address(Builder.CreateInvariantGroupBarrier(addr.getPointer()), 3719 addr.getAlignment()); 3720 } else { 3721 // For structs, we GEP to the field that the record layout suggests. 3722 addr = emitAddrOfFieldStorage(*this, addr, field); 3723 3724 // If this is a reference field, load the reference right now. 3725 if (const ReferenceType *refType = type->getAs<ReferenceType>()) { 3726 llvm::LoadInst *load = Builder.CreateLoad(addr, "ref"); 3727 if (cvr & Qualifiers::Volatile) load->setVolatile(true); 3728 3729 // Loading the reference will disable path-aware TBAA. 3730 TBAAPath = false; 3731 if (CGM.shouldUseTBAA()) { 3732 llvm::MDNode *tbaa = mayAlias ? CGM.getTBAAMayAliasTypeInfo() : 3733 CGM.getTBAATypeInfo(type); 3734 if (tbaa) 3735 CGM.DecorateInstructionWithTBAA(load, tbaa); 3736 } 3737 3738 mayAlias = false; 3739 type = refType->getPointeeType(); 3740 3741 CharUnits alignment = 3742 getNaturalTypeAlignment(type, &FieldBaseInfo, /*pointee*/ true); 3743 FieldBaseInfo.setMayAlias(false); 3744 addr = Address(load, alignment); 3745 3746 // Qualifiers on the struct don't apply to the referencee, and 3747 // we'll pick up CVR from the actual type later, so reset these 3748 // additional qualifiers now. 3749 cvr = 0; 3750 } 3751 } 3752 3753 // Make sure that the address is pointing to the right type. This is critical 3754 // for both unions and structs. A union needs a bitcast, a struct element 3755 // will need a bitcast if the LLVM type laid out doesn't match the desired 3756 // type. 3757 addr = Builder.CreateElementBitCast(addr, 3758 CGM.getTypes().ConvertTypeForMem(type), 3759 field->getName()); 3760 3761 if (field->hasAttr<AnnotateAttr>()) 3762 addr = EmitFieldAnnotations(field, addr); 3763 3764 LValue LV = MakeAddrLValue(addr, type, FieldBaseInfo); 3765 LV.getQuals().addCVRQualifiers(cvr); 3766 if (TBAAPath) { 3767 const ASTRecordLayout &Layout = 3768 getContext().getASTRecordLayout(field->getParent()); 3769 // Set the base type to be the base type of the base LValue and 3770 // update offset to be relative to the base type. 3771 LV.setTBAABaseType(mayAlias ? getContext().CharTy : base.getTBAABaseType()); 3772 LV.setTBAAOffset(mayAlias ? 0 : base.getTBAAOffset() + 3773 Layout.getFieldOffset(field->getFieldIndex()) / 3774 getContext().getCharWidth()); 3775 } 3776 3777 // __weak attribute on a field is ignored. 3778 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak) 3779 LV.getQuals().removeObjCGCAttr(); 3780 3781 // Fields of may_alias structs act like 'char' for TBAA purposes. 3782 // FIXME: this should get propagated down through anonymous structs 3783 // and unions. 3784 if (mayAlias && LV.getTBAAAccessType()) 3785 LV.setTBAAAccessType(CGM.getTBAAMayAliasTypeInfo()); 3786 3787 return LV; 3788 } 3789 3790 LValue 3791 CodeGenFunction::EmitLValueForFieldInitialization(LValue Base, 3792 const FieldDecl *Field) { 3793 QualType FieldType = Field->getType(); 3794 3795 if (!FieldType->isReferenceType()) 3796 return EmitLValueForField(Base, Field); 3797 3798 Address V = emitAddrOfFieldStorage(*this, Base.getAddress(), Field); 3799 3800 // Make sure that the address is pointing to the right type. 3801 llvm::Type *llvmType = ConvertTypeForMem(FieldType); 3802 V = Builder.CreateElementBitCast(V, llvmType, Field->getName()); 3803 3804 // TODO: access-path TBAA? 3805 LValueBaseInfo BaseInfo = Base.getBaseInfo(); 3806 LValueBaseInfo FieldBaseInfo( 3807 getFieldAlignmentSource(BaseInfo.getAlignmentSource()), 3808 BaseInfo.getMayAlias()); 3809 return MakeAddrLValue(V, FieldType, FieldBaseInfo); 3810 } 3811 3812 LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){ 3813 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false); 3814 if (E->isFileScope()) { 3815 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E); 3816 return MakeAddrLValue(GlobalPtr, E->getType(), BaseInfo); 3817 } 3818 if (E->getType()->isVariablyModifiedType()) 3819 // make sure to emit the VLA size. 3820 EmitVariablyModifiedType(E->getType()); 3821 3822 Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral"); 3823 const Expr *InitExpr = E->getInitializer(); 3824 LValue Result = MakeAddrLValue(DeclPtr, E->getType(), BaseInfo); 3825 3826 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(), 3827 /*Init*/ true); 3828 3829 return Result; 3830 } 3831 3832 LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) { 3833 if (!E->isGLValue()) 3834 // Initializing an aggregate temporary in C++11: T{...}. 3835 return EmitAggExprToLValue(E); 3836 3837 // An lvalue initializer list must be initializing a reference. 3838 assert(E->isTransparent() && "non-transparent glvalue init list"); 3839 return EmitLValue(E->getInit(0)); 3840 } 3841 3842 /// Emit the operand of a glvalue conditional operator. This is either a glvalue 3843 /// or a (possibly-parenthesized) throw-expression. If this is a throw, no 3844 /// LValue is returned and the current block has been terminated. 3845 static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF, 3846 const Expr *Operand) { 3847 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) { 3848 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false); 3849 return None; 3850 } 3851 3852 return CGF.EmitLValue(Operand); 3853 } 3854 3855 LValue CodeGenFunction:: 3856 EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) { 3857 if (!expr->isGLValue()) { 3858 // ?: here should be an aggregate. 3859 assert(hasAggregateEvaluationKind(expr->getType()) && 3860 "Unexpected conditional operator!"); 3861 return EmitAggExprToLValue(expr); 3862 } 3863 3864 OpaqueValueMapping binding(*this, expr); 3865 3866 const Expr *condExpr = expr->getCond(); 3867 bool CondExprBool; 3868 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) { 3869 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr(); 3870 if (!CondExprBool) std::swap(live, dead); 3871 3872 if (!ContainsLabel(dead)) { 3873 // If the true case is live, we need to track its region. 3874 if (CondExprBool) 3875 incrementProfileCounter(expr); 3876 return EmitLValue(live); 3877 } 3878 } 3879 3880 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true"); 3881 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false"); 3882 llvm::BasicBlock *contBlock = createBasicBlock("cond.end"); 3883 3884 ConditionalEvaluation eval(*this); 3885 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr)); 3886 3887 // Any temporaries created here are conditional. 3888 EmitBlock(lhsBlock); 3889 incrementProfileCounter(expr); 3890 eval.begin(*this); 3891 Optional<LValue> lhs = 3892 EmitLValueOrThrowExpression(*this, expr->getTrueExpr()); 3893 eval.end(*this); 3894 3895 if (lhs && !lhs->isSimple()) 3896 return EmitUnsupportedLValue(expr, "conditional operator"); 3897 3898 lhsBlock = Builder.GetInsertBlock(); 3899 if (lhs) 3900 Builder.CreateBr(contBlock); 3901 3902 // Any temporaries created here are conditional. 3903 EmitBlock(rhsBlock); 3904 eval.begin(*this); 3905 Optional<LValue> rhs = 3906 EmitLValueOrThrowExpression(*this, expr->getFalseExpr()); 3907 eval.end(*this); 3908 if (rhs && !rhs->isSimple()) 3909 return EmitUnsupportedLValue(expr, "conditional operator"); 3910 rhsBlock = Builder.GetInsertBlock(); 3911 3912 EmitBlock(contBlock); 3913 3914 if (lhs && rhs) { 3915 llvm::PHINode *phi = Builder.CreatePHI(lhs->getPointer()->getType(), 3916 2, "cond-lvalue"); 3917 phi->addIncoming(lhs->getPointer(), lhsBlock); 3918 phi->addIncoming(rhs->getPointer(), rhsBlock); 3919 Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment())); 3920 AlignmentSource alignSource = 3921 std::max(lhs->getBaseInfo().getAlignmentSource(), 3922 rhs->getBaseInfo().getAlignmentSource()); 3923 bool MayAlias = lhs->getBaseInfo().getMayAlias() || 3924 rhs->getBaseInfo().getMayAlias(); 3925 return MakeAddrLValue(result, expr->getType(), 3926 LValueBaseInfo(alignSource, MayAlias)); 3927 } else { 3928 assert((lhs || rhs) && 3929 "both operands of glvalue conditional are throw-expressions?"); 3930 return lhs ? *lhs : *rhs; 3931 } 3932 } 3933 3934 /// EmitCastLValue - Casts are never lvalues unless that cast is to a reference 3935 /// type. If the cast is to a reference, we can have the usual lvalue result, 3936 /// otherwise if a cast is needed by the code generator in an lvalue context, 3937 /// then it must mean that we need the address of an aggregate in order to 3938 /// access one of its members. This can happen for all the reasons that casts 3939 /// are permitted with aggregate result, including noop aggregate casts, and 3940 /// cast from scalar to union. 3941 LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) { 3942 switch (E->getCastKind()) { 3943 case CK_ToVoid: 3944 case CK_BitCast: 3945 case CK_ArrayToPointerDecay: 3946 case CK_FunctionToPointerDecay: 3947 case CK_NullToMemberPointer: 3948 case CK_NullToPointer: 3949 case CK_IntegralToPointer: 3950 case CK_PointerToIntegral: 3951 case CK_PointerToBoolean: 3952 case CK_VectorSplat: 3953 case CK_IntegralCast: 3954 case CK_BooleanToSignedIntegral: 3955 case CK_IntegralToBoolean: 3956 case CK_IntegralToFloating: 3957 case CK_FloatingToIntegral: 3958 case CK_FloatingToBoolean: 3959 case CK_FloatingCast: 3960 case CK_FloatingRealToComplex: 3961 case CK_FloatingComplexToReal: 3962 case CK_FloatingComplexToBoolean: 3963 case CK_FloatingComplexCast: 3964 case CK_FloatingComplexToIntegralComplex: 3965 case CK_IntegralRealToComplex: 3966 case CK_IntegralComplexToReal: 3967 case CK_IntegralComplexToBoolean: 3968 case CK_IntegralComplexCast: 3969 case CK_IntegralComplexToFloatingComplex: 3970 case CK_DerivedToBaseMemberPointer: 3971 case CK_BaseToDerivedMemberPointer: 3972 case CK_MemberPointerToBoolean: 3973 case CK_ReinterpretMemberPointer: 3974 case CK_AnyPointerToBlockPointerCast: 3975 case CK_ARCProduceObject: 3976 case CK_ARCConsumeObject: 3977 case CK_ARCReclaimReturnedObject: 3978 case CK_ARCExtendBlockObject: 3979 case CK_CopyAndAutoreleaseBlockObject: 3980 case CK_AddressSpaceConversion: 3981 case CK_IntToOCLSampler: 3982 return EmitUnsupportedLValue(E, "unexpected cast lvalue"); 3983 3984 case CK_Dependent: 3985 llvm_unreachable("dependent cast kind in IR gen!"); 3986 3987 case CK_BuiltinFnToFnPtr: 3988 llvm_unreachable("builtin functions are handled elsewhere"); 3989 3990 // These are never l-values; just use the aggregate emission code. 3991 case CK_NonAtomicToAtomic: 3992 case CK_AtomicToNonAtomic: 3993 return EmitAggExprToLValue(E); 3994 3995 case CK_Dynamic: { 3996 LValue LV = EmitLValue(E->getSubExpr()); 3997 Address V = LV.getAddress(); 3998 const auto *DCE = cast<CXXDynamicCastExpr>(E); 3999 return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType()); 4000 } 4001 4002 case CK_ConstructorConversion: 4003 case CK_UserDefinedConversion: 4004 case CK_CPointerToObjCPointerCast: 4005 case CK_BlockPointerToObjCPointerCast: 4006 case CK_NoOp: 4007 case CK_LValueToRValue: 4008 return EmitLValue(E->getSubExpr()); 4009 4010 case CK_UncheckedDerivedToBase: 4011 case CK_DerivedToBase: { 4012 const RecordType *DerivedClassTy = 4013 E->getSubExpr()->getType()->getAs<RecordType>(); 4014 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl()); 4015 4016 LValue LV = EmitLValue(E->getSubExpr()); 4017 Address This = LV.getAddress(); 4018 4019 // Perform the derived-to-base conversion 4020 Address Base = GetAddressOfBaseClass( 4021 This, DerivedClassDecl, E->path_begin(), E->path_end(), 4022 /*NullCheckValue=*/false, E->getExprLoc()); 4023 4024 return MakeAddrLValue(Base, E->getType(), LV.getBaseInfo()); 4025 } 4026 case CK_ToUnion: 4027 return EmitAggExprToLValue(E); 4028 case CK_BaseToDerived: { 4029 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>(); 4030 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl()); 4031 4032 LValue LV = EmitLValue(E->getSubExpr()); 4033 4034 // Perform the base-to-derived conversion 4035 Address Derived = 4036 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl, 4037 E->path_begin(), E->path_end(), 4038 /*NullCheckValue=*/false); 4039 4040 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is 4041 // performed and the object is not of the derived type. 4042 if (sanitizePerformTypeCheck()) 4043 EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(), 4044 Derived.getPointer(), E->getType()); 4045 4046 if (SanOpts.has(SanitizerKind::CFIDerivedCast)) 4047 EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(), 4048 /*MayBeNull=*/false, 4049 CFITCK_DerivedCast, E->getLocStart()); 4050 4051 return MakeAddrLValue(Derived, E->getType(), LV.getBaseInfo()); 4052 } 4053 case CK_LValueBitCast: { 4054 // This must be a reinterpret_cast (or c-style equivalent). 4055 const auto *CE = cast<ExplicitCastExpr>(E); 4056 4057 CGM.EmitExplicitCastExprType(CE, this); 4058 LValue LV = EmitLValue(E->getSubExpr()); 4059 Address V = Builder.CreateBitCast(LV.getAddress(), 4060 ConvertType(CE->getTypeAsWritten())); 4061 4062 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast)) 4063 EmitVTablePtrCheckForCast(E->getType(), V.getPointer(), 4064 /*MayBeNull=*/false, 4065 CFITCK_UnrelatedCast, E->getLocStart()); 4066 4067 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo()); 4068 } 4069 case CK_ObjCObjectLValueCast: { 4070 LValue LV = EmitLValue(E->getSubExpr()); 4071 Address V = Builder.CreateElementBitCast(LV.getAddress(), 4072 ConvertType(E->getType())); 4073 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo()); 4074 } 4075 case CK_ZeroToOCLQueue: 4076 llvm_unreachable("NULL to OpenCL queue lvalue cast is not valid"); 4077 case CK_ZeroToOCLEvent: 4078 llvm_unreachable("NULL to OpenCL event lvalue cast is not valid"); 4079 } 4080 4081 llvm_unreachable("Unhandled lvalue cast kind?"); 4082 } 4083 4084 LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) { 4085 assert(OpaqueValueMappingData::shouldBindAsLValue(e)); 4086 return getOpaqueLValueMapping(e); 4087 } 4088 4089 RValue CodeGenFunction::EmitRValueForField(LValue LV, 4090 const FieldDecl *FD, 4091 SourceLocation Loc) { 4092 QualType FT = FD->getType(); 4093 LValue FieldLV = EmitLValueForField(LV, FD); 4094 switch (getEvaluationKind(FT)) { 4095 case TEK_Complex: 4096 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc)); 4097 case TEK_Aggregate: 4098 return FieldLV.asAggregateRValue(); 4099 case TEK_Scalar: 4100 // This routine is used to load fields one-by-one to perform a copy, so 4101 // don't load reference fields. 4102 if (FD->getType()->isReferenceType()) 4103 return RValue::get(FieldLV.getPointer()); 4104 return EmitLoadOfLValue(FieldLV, Loc); 4105 } 4106 llvm_unreachable("bad evaluation kind"); 4107 } 4108 4109 //===--------------------------------------------------------------------===// 4110 // Expression Emission 4111 //===--------------------------------------------------------------------===// 4112 4113 RValue CodeGenFunction::EmitCallExpr(const CallExpr *E, 4114 ReturnValueSlot ReturnValue) { 4115 // Builtins never have block type. 4116 if (E->getCallee()->getType()->isBlockPointerType()) 4117 return EmitBlockCallExpr(E, ReturnValue); 4118 4119 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E)) 4120 return EmitCXXMemberCallExpr(CE, ReturnValue); 4121 4122 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E)) 4123 return EmitCUDAKernelCallExpr(CE, ReturnValue); 4124 4125 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E)) 4126 if (const CXXMethodDecl *MD = 4127 dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl())) 4128 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue); 4129 4130 CGCallee callee = EmitCallee(E->getCallee()); 4131 4132 if (callee.isBuiltin()) { 4133 return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(), 4134 E, ReturnValue); 4135 } 4136 4137 if (callee.isPseudoDestructor()) { 4138 return EmitCXXPseudoDestructorExpr(callee.getPseudoDestructorExpr()); 4139 } 4140 4141 return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue); 4142 } 4143 4144 /// Emit a CallExpr without considering whether it might be a subclass. 4145 RValue CodeGenFunction::EmitSimpleCallExpr(const CallExpr *E, 4146 ReturnValueSlot ReturnValue) { 4147 CGCallee Callee = EmitCallee(E->getCallee()); 4148 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue); 4149 } 4150 4151 static CGCallee EmitDirectCallee(CodeGenFunction &CGF, const FunctionDecl *FD) { 4152 if (auto builtinID = FD->getBuiltinID()) { 4153 return CGCallee::forBuiltin(builtinID, FD); 4154 } 4155 4156 llvm::Constant *calleePtr = EmitFunctionDeclPointer(CGF.CGM, FD); 4157 return CGCallee::forDirect(calleePtr, FD); 4158 } 4159 4160 CGCallee CodeGenFunction::EmitCallee(const Expr *E) { 4161 E = E->IgnoreParens(); 4162 4163 // Look through function-to-pointer decay. 4164 if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) { 4165 if (ICE->getCastKind() == CK_FunctionToPointerDecay || 4166 ICE->getCastKind() == CK_BuiltinFnToFnPtr) { 4167 return EmitCallee(ICE->getSubExpr()); 4168 } 4169 4170 // Resolve direct calls. 4171 } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) { 4172 if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) { 4173 return EmitDirectCallee(*this, FD); 4174 } 4175 } else if (auto ME = dyn_cast<MemberExpr>(E)) { 4176 if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) { 4177 EmitIgnoredExpr(ME->getBase()); 4178 return EmitDirectCallee(*this, FD); 4179 } 4180 4181 // Look through template substitutions. 4182 } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) { 4183 return EmitCallee(NTTP->getReplacement()); 4184 4185 // Treat pseudo-destructor calls differently. 4186 } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) { 4187 return CGCallee::forPseudoDestructor(PDE); 4188 } 4189 4190 // Otherwise, we have an indirect reference. 4191 llvm::Value *calleePtr; 4192 QualType functionType; 4193 if (auto ptrType = E->getType()->getAs<PointerType>()) { 4194 calleePtr = EmitScalarExpr(E); 4195 functionType = ptrType->getPointeeType(); 4196 } else { 4197 functionType = E->getType(); 4198 calleePtr = EmitLValue(E).getPointer(); 4199 } 4200 assert(functionType->isFunctionType()); 4201 CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(), 4202 E->getReferencedDeclOfCallee()); 4203 CGCallee callee(calleeInfo, calleePtr); 4204 return callee; 4205 } 4206 4207 LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) { 4208 // Comma expressions just emit their LHS then their RHS as an l-value. 4209 if (E->getOpcode() == BO_Comma) { 4210 EmitIgnoredExpr(E->getLHS()); 4211 EnsureInsertPoint(); 4212 return EmitLValue(E->getRHS()); 4213 } 4214 4215 if (E->getOpcode() == BO_PtrMemD || 4216 E->getOpcode() == BO_PtrMemI) 4217 return EmitPointerToDataMemberBinaryExpr(E); 4218 4219 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value"); 4220 4221 // Note that in all of these cases, __block variables need the RHS 4222 // evaluated first just in case the variable gets moved by the RHS. 4223 4224 switch (getEvaluationKind(E->getType())) { 4225 case TEK_Scalar: { 4226 switch (E->getLHS()->getType().getObjCLifetime()) { 4227 case Qualifiers::OCL_Strong: 4228 return EmitARCStoreStrong(E, /*ignored*/ false).first; 4229 4230 case Qualifiers::OCL_Autoreleasing: 4231 return EmitARCStoreAutoreleasing(E).first; 4232 4233 // No reason to do any of these differently. 4234 case Qualifiers::OCL_None: 4235 case Qualifiers::OCL_ExplicitNone: 4236 case Qualifiers::OCL_Weak: 4237 break; 4238 } 4239 4240 RValue RV = EmitAnyExpr(E->getRHS()); 4241 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store); 4242 if (RV.isScalar()) 4243 EmitNullabilityCheck(LV, RV.getScalarVal(), E->getExprLoc()); 4244 EmitStoreThroughLValue(RV, LV); 4245 return LV; 4246 } 4247 4248 case TEK_Complex: 4249 return EmitComplexAssignmentLValue(E); 4250 4251 case TEK_Aggregate: 4252 return EmitAggExprToLValue(E); 4253 } 4254 llvm_unreachable("bad evaluation kind"); 4255 } 4256 4257 LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) { 4258 RValue RV = EmitCallExpr(E); 4259 4260 if (!RV.isScalar()) 4261 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(), 4262 LValueBaseInfo(AlignmentSource::Decl, false)); 4263 4264 assert(E->getCallReturnType(getContext())->isReferenceType() && 4265 "Can't have a scalar return unless the return type is a " 4266 "reference type!"); 4267 4268 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType()); 4269 } 4270 4271 LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) { 4272 // FIXME: This shouldn't require another copy. 4273 return EmitAggExprToLValue(E); 4274 } 4275 4276 LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) { 4277 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor() 4278 && "binding l-value to type which needs a temporary"); 4279 AggValueSlot Slot = CreateAggTemp(E->getType()); 4280 EmitCXXConstructExpr(E, Slot); 4281 return MakeAddrLValue(Slot.getAddress(), E->getType(), 4282 LValueBaseInfo(AlignmentSource::Decl, false)); 4283 } 4284 4285 LValue 4286 CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) { 4287 return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType()); 4288 } 4289 4290 Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) { 4291 return Builder.CreateElementBitCast(CGM.GetAddrOfUuidDescriptor(E), 4292 ConvertType(E->getType())); 4293 } 4294 4295 LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) { 4296 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(), 4297 LValueBaseInfo(AlignmentSource::Decl, false)); 4298 } 4299 4300 LValue 4301 CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) { 4302 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue"); 4303 Slot.setExternallyDestructed(); 4304 EmitAggExpr(E->getSubExpr(), Slot); 4305 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress()); 4306 return MakeAddrLValue(Slot.getAddress(), E->getType(), 4307 LValueBaseInfo(AlignmentSource::Decl, false)); 4308 } 4309 4310 LValue 4311 CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) { 4312 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue"); 4313 EmitLambdaExpr(E, Slot); 4314 return MakeAddrLValue(Slot.getAddress(), E->getType(), 4315 LValueBaseInfo(AlignmentSource::Decl, false)); 4316 } 4317 4318 LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) { 4319 RValue RV = EmitObjCMessageExpr(E); 4320 4321 if (!RV.isScalar()) 4322 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(), 4323 LValueBaseInfo(AlignmentSource::Decl, false)); 4324 4325 assert(E->getMethodDecl()->getReturnType()->isReferenceType() && 4326 "Can't have a scalar return unless the return type is a " 4327 "reference type!"); 4328 4329 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType()); 4330 } 4331 4332 LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) { 4333 Address V = 4334 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector()); 4335 return MakeAddrLValue(V, E->getType(), 4336 LValueBaseInfo(AlignmentSource::Decl, false)); 4337 } 4338 4339 llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface, 4340 const ObjCIvarDecl *Ivar) { 4341 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar); 4342 } 4343 4344 LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy, 4345 llvm::Value *BaseValue, 4346 const ObjCIvarDecl *Ivar, 4347 unsigned CVRQualifiers) { 4348 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue, 4349 Ivar, CVRQualifiers); 4350 } 4351 4352 LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) { 4353 // FIXME: A lot of the code below could be shared with EmitMemberExpr. 4354 llvm::Value *BaseValue = nullptr; 4355 const Expr *BaseExpr = E->getBase(); 4356 Qualifiers BaseQuals; 4357 QualType ObjectTy; 4358 if (E->isArrow()) { 4359 BaseValue = EmitScalarExpr(BaseExpr); 4360 ObjectTy = BaseExpr->getType()->getPointeeType(); 4361 BaseQuals = ObjectTy.getQualifiers(); 4362 } else { 4363 LValue BaseLV = EmitLValue(BaseExpr); 4364 BaseValue = BaseLV.getPointer(); 4365 ObjectTy = BaseExpr->getType(); 4366 BaseQuals = ObjectTy.getQualifiers(); 4367 } 4368 4369 LValue LV = 4370 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(), 4371 BaseQuals.getCVRQualifiers()); 4372 setObjCGCLValueClass(getContext(), E, LV); 4373 return LV; 4374 } 4375 4376 LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) { 4377 // Can only get l-value for message expression returning aggregate type 4378 RValue RV = EmitAnyExprToTemp(E); 4379 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(), 4380 LValueBaseInfo(AlignmentSource::Decl, false)); 4381 } 4382 4383 RValue CodeGenFunction::EmitCall(QualType CalleeType, const CGCallee &OrigCallee, 4384 const CallExpr *E, ReturnValueSlot ReturnValue, 4385 llvm::Value *Chain) { 4386 // Get the actual function type. The callee type will always be a pointer to 4387 // function type or a block pointer type. 4388 assert(CalleeType->isFunctionPointerType() && 4389 "Call must have function pointer type!"); 4390 4391 const Decl *TargetDecl = OrigCallee.getAbstractInfo().getCalleeDecl(); 4392 4393 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 4394 // We can only guarantee that a function is called from the correct 4395 // context/function based on the appropriate target attributes, 4396 // so only check in the case where we have both always_inline and target 4397 // since otherwise we could be making a conditional call after a check for 4398 // the proper cpu features (and it won't cause code generation issues due to 4399 // function based code generation). 4400 if (TargetDecl->hasAttr<AlwaysInlineAttr>() && 4401 TargetDecl->hasAttr<TargetAttr>()) 4402 checkTargetFeatures(E, FD); 4403 4404 CalleeType = getContext().getCanonicalType(CalleeType); 4405 4406 const auto *FnType = 4407 cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType()); 4408 4409 CGCallee Callee = OrigCallee; 4410 4411 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) && 4412 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) { 4413 if (llvm::Constant *PrefixSig = 4414 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) { 4415 SanitizerScope SanScope(this); 4416 llvm::Constant *FTRTTIConst = 4417 CGM.GetAddrOfRTTIDescriptor(QualType(FnType, 0), /*ForEH=*/true); 4418 llvm::Type *PrefixStructTyElems[] = {PrefixSig->getType(), Int32Ty}; 4419 llvm::StructType *PrefixStructTy = llvm::StructType::get( 4420 CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true); 4421 4422 llvm::Value *CalleePtr = Callee.getFunctionPointer(); 4423 4424 llvm::Value *CalleePrefixStruct = Builder.CreateBitCast( 4425 CalleePtr, llvm::PointerType::getUnqual(PrefixStructTy)); 4426 llvm::Value *CalleeSigPtr = 4427 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0); 4428 llvm::Value *CalleeSig = 4429 Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign()); 4430 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig); 4431 4432 llvm::BasicBlock *Cont = createBasicBlock("cont"); 4433 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck"); 4434 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont); 4435 4436 EmitBlock(TypeCheck); 4437 llvm::Value *CalleeRTTIPtr = 4438 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1); 4439 llvm::Value *CalleeRTTIEncoded = 4440 Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign()); 4441 llvm::Value *CalleeRTTI = 4442 DecodeAddrUsedInPrologue(CalleePtr, CalleeRTTIEncoded); 4443 llvm::Value *CalleeRTTIMatch = 4444 Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst); 4445 llvm::Constant *StaticData[] = { 4446 EmitCheckSourceLocation(E->getLocStart()), 4447 EmitCheckTypeDescriptor(CalleeType) 4448 }; 4449 EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function), 4450 SanitizerHandler::FunctionTypeMismatch, StaticData, CalleePtr); 4451 4452 Builder.CreateBr(Cont); 4453 EmitBlock(Cont); 4454 } 4455 } 4456 4457 // If we are checking indirect calls and this call is indirect, check that the 4458 // function pointer is a member of the bit set for the function type. 4459 if (SanOpts.has(SanitizerKind::CFIICall) && 4460 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) { 4461 SanitizerScope SanScope(this); 4462 EmitSanitizerStatReport(llvm::SanStat_CFI_ICall); 4463 4464 llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0)); 4465 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD); 4466 4467 llvm::Value *CalleePtr = Callee.getFunctionPointer(); 4468 llvm::Value *CastedCallee = Builder.CreateBitCast(CalleePtr, Int8PtrTy); 4469 llvm::Value *TypeTest = Builder.CreateCall( 4470 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedCallee, TypeId}); 4471 4472 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD); 4473 llvm::Constant *StaticData[] = { 4474 llvm::ConstantInt::get(Int8Ty, CFITCK_ICall), 4475 EmitCheckSourceLocation(E->getLocStart()), 4476 EmitCheckTypeDescriptor(QualType(FnType, 0)), 4477 }; 4478 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) { 4479 EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId, 4480 CastedCallee, StaticData); 4481 } else { 4482 EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall), 4483 SanitizerHandler::CFICheckFail, StaticData, 4484 {CastedCallee, llvm::UndefValue::get(IntPtrTy)}); 4485 } 4486 } 4487 4488 CallArgList Args; 4489 if (Chain) 4490 Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)), 4491 CGM.getContext().VoidPtrTy); 4492 4493 // C++17 requires that we evaluate arguments to a call using assignment syntax 4494 // right-to-left, and that we evaluate arguments to certain other operators 4495 // left-to-right. Note that we allow this to override the order dictated by 4496 // the calling convention on the MS ABI, which means that parameter 4497 // destruction order is not necessarily reverse construction order. 4498 // FIXME: Revisit this based on C++ committee response to unimplementability. 4499 EvaluationOrder Order = EvaluationOrder::Default; 4500 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) { 4501 if (OCE->isAssignmentOp()) 4502 Order = EvaluationOrder::ForceRightToLeft; 4503 else { 4504 switch (OCE->getOperator()) { 4505 case OO_LessLess: 4506 case OO_GreaterGreater: 4507 case OO_AmpAmp: 4508 case OO_PipePipe: 4509 case OO_Comma: 4510 case OO_ArrowStar: 4511 Order = EvaluationOrder::ForceLeftToRight; 4512 break; 4513 default: 4514 break; 4515 } 4516 } 4517 } 4518 4519 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(), 4520 E->getDirectCallee(), /*ParamsToSkip*/ 0, Order); 4521 4522 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall( 4523 Args, FnType, /*isChainCall=*/Chain); 4524 4525 // C99 6.5.2.2p6: 4526 // If the expression that denotes the called function has a type 4527 // that does not include a prototype, [the default argument 4528 // promotions are performed]. If the number of arguments does not 4529 // equal the number of parameters, the behavior is undefined. If 4530 // the function is defined with a type that includes a prototype, 4531 // and either the prototype ends with an ellipsis (, ...) or the 4532 // types of the arguments after promotion are not compatible with 4533 // the types of the parameters, the behavior is undefined. If the 4534 // function is defined with a type that does not include a 4535 // prototype, and the types of the arguments after promotion are 4536 // not compatible with those of the parameters after promotion, 4537 // the behavior is undefined [except in some trivial cases]. 4538 // That is, in the general case, we should assume that a call 4539 // through an unprototyped function type works like a *non-variadic* 4540 // call. The way we make this work is to cast to the exact type 4541 // of the promoted arguments. 4542 // 4543 // Chain calls use this same code path to add the invisible chain parameter 4544 // to the function type. 4545 if (isa<FunctionNoProtoType>(FnType) || Chain) { 4546 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo); 4547 CalleeTy = CalleeTy->getPointerTo(); 4548 4549 llvm::Value *CalleePtr = Callee.getFunctionPointer(); 4550 CalleePtr = Builder.CreateBitCast(CalleePtr, CalleeTy, "callee.knr.cast"); 4551 Callee.setFunctionPointer(CalleePtr); 4552 } 4553 4554 return EmitCall(FnInfo, Callee, ReturnValue, Args); 4555 } 4556 4557 LValue CodeGenFunction:: 4558 EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) { 4559 Address BaseAddr = Address::invalid(); 4560 if (E->getOpcode() == BO_PtrMemI) { 4561 BaseAddr = EmitPointerWithAlignment(E->getLHS()); 4562 } else { 4563 BaseAddr = EmitLValue(E->getLHS()).getAddress(); 4564 } 4565 4566 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS()); 4567 4568 const MemberPointerType *MPT 4569 = E->getRHS()->getType()->getAs<MemberPointerType>(); 4570 4571 LValueBaseInfo BaseInfo; 4572 Address MemberAddr = 4573 EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT, &BaseInfo); 4574 4575 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), BaseInfo); 4576 } 4577 4578 /// Given the address of a temporary variable, produce an r-value of 4579 /// its type. 4580 RValue CodeGenFunction::convertTempToRValue(Address addr, 4581 QualType type, 4582 SourceLocation loc) { 4583 LValue lvalue = MakeAddrLValue(addr, type, 4584 LValueBaseInfo(AlignmentSource::Decl, false)); 4585 switch (getEvaluationKind(type)) { 4586 case TEK_Complex: 4587 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc)); 4588 case TEK_Aggregate: 4589 return lvalue.asAggregateRValue(); 4590 case TEK_Scalar: 4591 return RValue::get(EmitLoadOfScalar(lvalue, loc)); 4592 } 4593 llvm_unreachable("bad evaluation kind"); 4594 } 4595 4596 void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) { 4597 assert(Val->getType()->isFPOrFPVectorTy()); 4598 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val)) 4599 return; 4600 4601 llvm::MDBuilder MDHelper(getLLVMContext()); 4602 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy); 4603 4604 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node); 4605 } 4606 4607 namespace { 4608 struct LValueOrRValue { 4609 LValue LV; 4610 RValue RV; 4611 }; 4612 } 4613 4614 static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF, 4615 const PseudoObjectExpr *E, 4616 bool forLValue, 4617 AggValueSlot slot) { 4618 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques; 4619 4620 // Find the result expression, if any. 4621 const Expr *resultExpr = E->getResultExpr(); 4622 LValueOrRValue result; 4623 4624 for (PseudoObjectExpr::const_semantics_iterator 4625 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) { 4626 const Expr *semantic = *i; 4627 4628 // If this semantic expression is an opaque value, bind it 4629 // to the result of its source expression. 4630 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) { 4631 4632 // If this is the result expression, we may need to evaluate 4633 // directly into the slot. 4634 typedef CodeGenFunction::OpaqueValueMappingData OVMA; 4635 OVMA opaqueData; 4636 if (ov == resultExpr && ov->isRValue() && !forLValue && 4637 CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) { 4638 CGF.EmitAggExpr(ov->getSourceExpr(), slot); 4639 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false); 4640 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(), 4641 BaseInfo); 4642 opaqueData = OVMA::bind(CGF, ov, LV); 4643 result.RV = slot.asRValue(); 4644 4645 // Otherwise, emit as normal. 4646 } else { 4647 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr()); 4648 4649 // If this is the result, also evaluate the result now. 4650 if (ov == resultExpr) { 4651 if (forLValue) 4652 result.LV = CGF.EmitLValue(ov); 4653 else 4654 result.RV = CGF.EmitAnyExpr(ov, slot); 4655 } 4656 } 4657 4658 opaques.push_back(opaqueData); 4659 4660 // Otherwise, if the expression is the result, evaluate it 4661 // and remember the result. 4662 } else if (semantic == resultExpr) { 4663 if (forLValue) 4664 result.LV = CGF.EmitLValue(semantic); 4665 else 4666 result.RV = CGF.EmitAnyExpr(semantic, slot); 4667 4668 // Otherwise, evaluate the expression in an ignored context. 4669 } else { 4670 CGF.EmitIgnoredExpr(semantic); 4671 } 4672 } 4673 4674 // Unbind all the opaques now. 4675 for (unsigned i = 0, e = opaques.size(); i != e; ++i) 4676 opaques[i].unbind(CGF); 4677 4678 return result; 4679 } 4680 4681 RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E, 4682 AggValueSlot slot) { 4683 return emitPseudoObjectExpr(*this, E, false, slot).RV; 4684 } 4685 4686 LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) { 4687 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV; 4688 } 4689