clang 22.0.0git
CGExpr.cpp
Go to the documentation of this file.
1/===--- CGExpr.cpp - Emit LLVM Code from Expressions ---------------------===/
2/
3/ Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4/ See https://llvm.org/LICENSE.txt for license information.
5/ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6/
7/===----------------------------------------------------------------------===/
8/
9/ This contains code to emit Expr nodes as LLVM code.
10/
11/===----------------------------------------------------------------------===/
12
13#include "ABIInfoImpl.h"
14#include "CGCUDARuntime.h"
15#include "CGCXXABI.h"
16#include "CGCall.h"
17#include "CGCleanup.h"
18#include "CGDebugInfo.h"
19#include "CGHLSLRuntime.h"
20#include "CGObjCRuntime.h"
21#include "CGOpenMPRuntime.h"
22#include "CGRecordLayout.h"
23#include "CodeGenFunction.h"
24#include "CodeGenModule.h"
25#include "CodeGenPGO.h"
26#include "ConstantEmitter.h"
27#include "TargetInfo.h"
29#include "clang/AST/ASTLambda.h"
30#include "clang/AST/Attr.h"
31#include "clang/AST/DeclObjC.h"
33#include "clang/AST/NSAPI.h"
38#include "clang/Basic/Module.h"
40#include "llvm/ADT/STLExtras.h"
41#include "llvm/ADT/ScopeExit.h"
42#include "llvm/ADT/StringExtras.h"
43#include "llvm/IR/DataLayout.h"
44#include "llvm/IR/Intrinsics.h"
45#include "llvm/IR/LLVMContext.h"
46#include "llvm/IR/MDBuilder.h"
47#include "llvm/IR/MatrixBuilder.h"
48#include "llvm/Support/ConvertUTF.h"
49#include "llvm/Support/Endian.h"
50#include "llvm/Support/MathExtras.h"
51#include "llvm/Support/Path.h"
52#include "llvm/Support/xxhash.h"
53#include "llvm/Transforms/Utils/SanitizerStats.h"
54
55#include <numeric>
56#include <optional>
57#include <string>
58
59using namespace clang;
60using namespace CodeGen;
61
62namespace clang {
63/ TODO: consider deprecating ClSanitizeGuardChecks; functionality is subsumed
64/ by -fsanitize-skip-hot-cutoff
65llvm::cl::opt<bool> ClSanitizeGuardChecks(
66 "ubsan-guard-checks", llvm::cl::Optional,
67 llvm::cl::desc("Guard UBSAN checks with `llvm.allow.ubsan.check()`."));
68
69} / namespace clang
70
71/===--------------------------------------------------------------------===/
72/ Defines for metadata
73/===--------------------------------------------------------------------===/
74
75/ Those values are crucial to be the SAME as in ubsan runtime library.
77 / An integer type.
78 TK_Integer = 0x0000,
79 / A floating-point type.
80 TK_Float = 0x0001,
81 / An _BitInt(N) type.
82 TK_BitInt = 0x0002,
83 / Any other type. The value representation is unspecified.
84 TK_Unknown = 0xffff
85};
86
87/===--------------------------------------------------------------------===/
88/ Miscellaneous Helper Methods
89/===--------------------------------------------------------------------===/
90
91static llvm::StringRef GetUBSanTrapForHandler(SanitizerHandler ID) {
92 switch (ID) {
93#define SANITIZER_CHECK(Enum, Name, Version, Msg) \
94 case SanitizerHandler::Enum: \
95 return Msg;
97#undef SANITIZER_CHECK
98 }
99 llvm_unreachable("unhandled switch case");
100}
101
102/ CreateTempAlloca - This creates a alloca and inserts it into the entry
103/ block.
106 const Twine &Name,
107 llvm::Value *ArraySize) {
108 auto Alloca = CreateTempAlloca(Ty, Name, ArraySize);
109 Alloca->setAlignment(Align.getAsAlign());
110 return RawAddress(Alloca, Ty, Align, KnownNonNull);
111}
112
113RawAddress CodeGenFunction::MaybeCastStackAddressSpace(RawAddress Alloca,
114 LangAS DestLangAS,
115 llvm::Value *ArraySize) {
116
117 llvm::Value *V = Alloca.getPointer();
118 / Alloca always returns a pointer in alloca address space, which may
119 / be different from the type defined by the language. For example,
120 / in C++ the auto variables are in the default address space. Therefore
121 / cast alloca to the default address space when necessary.
122
123 unsigned DestAddrSpace = getContext().getTargetAddressSpace(DestLangAS);
124 if (DestAddrSpace != Alloca.getAddressSpace()) {
125 llvm::IRBuilderBase::InsertPointGuard IPG(Builder);
126 / When ArraySize is nullptr, alloca is inserted at AllocaInsertPt,
127 / otherwise alloca is inserted at the current insertion point of the
128 / builder.
129 if (!ArraySize)
130 Builder.SetInsertPoint(getPostAllocaInsertPoint());
132 *this, V, getASTAllocaAddressSpace(), Builder.getPtrTy(DestAddrSpace),
133 /*IsNonNull=*/true);
134 }
135
136 return RawAddress(V, Alloca.getElementType(), Alloca.getAlignment(),
138}
139
141 CharUnits Align, const Twine &Name,
142 llvm::Value *ArraySize,
143 RawAddress *AllocaAddr) {
144 RawAddress Alloca = CreateTempAllocaWithoutCast(Ty, Align, Name, ArraySize);
145 if (AllocaAddr)
146 *AllocaAddr = Alloca;
147 return MaybeCastStackAddressSpace(Alloca, DestLangAS, ArraySize);
148}
149
150/ CreateTempAlloca - This creates an alloca and inserts it into the entry
151/ block if \p ArraySize is nullptr, otherwise inserts it at the current
152/ insertion point of the builder.
153llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
154 const Twine &Name,
155 llvm::Value *ArraySize) {
156 llvm::AllocaInst *Alloca;
157 if (ArraySize)
158 Alloca = Builder.CreateAlloca(Ty, ArraySize, Name);
159 else
160 Alloca =
161 new llvm::AllocaInst(Ty, CGM.getDataLayout().getAllocaAddrSpace(),
162 ArraySize, Name, AllocaInsertPt->getIterator());
163 if (SanOpts.Mask & SanitizerKind::Address) {
164 Alloca->addAnnotationMetadata({"alloca_name_altered", Name.str()});
165 }
166 if (Allocas) {
167 Allocas->Add(Alloca);
168 }
169 return Alloca;
170}
171
172/ CreateDefaultAlignTempAlloca - This creates an alloca with the
173/ default alignment of the corresponding LLVM type, which is *not*
174/ guaranteed to be related in any way to the expected alignment of
175/ an AST type that might have been lowered to Ty.
177 const Twine &Name) {
178 CharUnits Align =
179 CharUnits::fromQuantity(CGM.getDataLayout().getPrefTypeAlign(Ty));
180 return CreateTempAlloca(Ty, Align, Name);
181}
182
185 return CreateTempAlloca(ConvertType(Ty), Align, Name);
186}
187
189 RawAddress *Alloca) {
190 / FIXME: Should we prefer the preferred type alignment here?
191 return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name, Alloca);
192}
193
195 const Twine &Name,
196 RawAddress *Alloca) {
198 /*ArraySize=*/nullptr, Alloca);
199
200 if (Ty->isConstantMatrixType()) {
201 auto *ArrayTy = cast<llvm::ArrayType>(Result.getElementType());
202 auto *VectorTy = llvm::FixedVectorType::get(ArrayTy->getElementType(),
203 ArrayTy->getNumElements());
204
205 Result = Address(Result.getPointer(), VectorTy, Result.getAlignment(),
207 }
208 return Result;
209}
210
212 CharUnits Align,
213 const Twine &Name) {
214 return CreateTempAllocaWithoutCast(ConvertTypeForMem(Ty), Align, Name);
215}
216
218 const Twine &Name) {
219 return CreateMemTempWithoutCast(Ty, getContext().getTypeAlignInChars(Ty),
220 Name);
221}
222
223/ EvaluateExprAsBool - Perform the usual unary conversions on the specified
224/ expression and compare the result against zero, returning an Int1Ty value.
226 PGO->setCurrentStmt(E);
227 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
228 llvm::Value *MemPtr = EmitScalarExpr(E);
229 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
230 }
231
232 QualType BoolTy = getContext().BoolTy;
233 SourceLocation Loc = E->getExprLoc();
234 CGFPOptionsRAII FPOptsRAII(*this, E);
235 if (!E->getType()->isAnyComplexType())
236 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc);
237
239 Loc);
240}
241
242/ EmitIgnoredExpr - Emit code to compute the specified expression,
243/ ignoring the result.
245 if (E->isPRValue())
246 return (void)EmitAnyExpr(E, AggValueSlot::ignored(), true);
247
248 / if this is a bitfield-resulting conditional operator, we can special case
249 / emit this. The normal 'EmitLValue' version of this is particularly
250 / difficult to codegen for, since creating a single "LValue" for two
251 / different sized arguments here is not particularly doable.
252 if (const auto *CondOp = dyn_cast<AbstractConditionalOperator>(
254 if (CondOp->getObjectKind() == OK_BitField)
255 return EmitIgnoredConditionalOperator(CondOp);
256 }
257
258 / Just emit it as an l-value and drop the result.
259 EmitLValue(E);
260}
261
262/ EmitAnyExpr - Emit code to compute the specified expression which
263/ can have any type. The result is returned as an RValue struct.
264/ If this is an aggregate expression, AggSlot indicates where the
265/ result should be returned.
267 AggValueSlot aggSlot,
268 bool ignoreResult) {
269 switch (getEvaluationKind(E->getType())) {
270 case TEK_Scalar:
271 return RValue::get(EmitScalarExpr(E, ignoreResult));
272 case TEK_Complex:
273 return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
274 case TEK_Aggregate:
275 if (!ignoreResult && aggSlot.isIgnored())
276 aggSlot = CreateAggTemp(E->getType(), "agg-temp");
277 EmitAggExpr(E, aggSlot);
278 return aggSlot.asRValue();
279 }
280 llvm_unreachable("bad evaluation kind");
281}
282
283/ EmitAnyExprToTemp - Similar to EmitAnyExpr(), however, the result will
284/ always be accessible even if no aggregate location is provided.
287
289 AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
290 return EmitAnyExpr(E, AggSlot);
291}
292
293/ EmitAnyExprToMem - Evaluate an expression into a given memory
294/ location.
296 Address Location,
297 Qualifiers Quals,
298 bool IsInit) {
299 / FIXME: This function should take an LValue as an argument.
300 switch (getEvaluationKind(E->getType())) {
301 case TEK_Complex:
303 /*isInit*/ false);
304 return;
305
306 case TEK_Aggregate: {
307 EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
312 return;
313 }
314
315 case TEK_Scalar: {
316 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
317 LValue LV = MakeAddrLValue(Location, E->getType());
319 return;
320 }
321 }
322 llvm_unreachable("bad evaluation kind");
323}
324
326 const Expr *E, LValue LV, AggValueSlot::IsZeroed_t IsZeroed) {
327 QualType Type = LV.getType();
328 switch (getEvaluationKind(Type)) {
329 case TEK_Complex:
330 EmitComplexExprIntoLValue(E, LV, /*isInit*/ true);
331 return;
332 case TEK_Aggregate:
336 AggValueSlot::MayOverlap, IsZeroed));
337 return;
338 case TEK_Scalar:
339 if (LV.isSimple())
340 EmitScalarInit(E, /*D=*/nullptr, LV, /*Captured=*/false);
341 else
343 return;
344 }
345 llvm_unreachable("bad evaluation kind");
346}
347
348static void
350 const Expr *E, Address ReferenceTemporary) {
351 / Objective-C++ ARC:
352 / If we are binding a reference to a temporary that has ownership, we
353 / need to perform retain/release operations on the temporary.
354 /
355 / FIXME: This should be looking at E, not M.
356 if (auto Lifetime = M->getType().getObjCLifetime()) {
357 switch (Lifetime) {
360 / Carry on to normal cleanup handling.
361 break;
362
364 / Nothing to do; cleaned up by an autorelease pool.
365 return;
366
369 switch (StorageDuration Duration = M->getStorageDuration()) {
370 case SD_Static:
371 / Note: we intentionally do not register a cleanup to release
372 / the object on program termination.
373 return;
374
375 case SD_Thread:
376 / FIXME: We should probably register a cleanup in this case.
377 return;
378
379 case SD_Automatic:
383 if (Lifetime == Qualifiers::OCL_Strong) {
384 const ValueDecl *VD = M->getExtendingDecl();
385 bool Precise = isa_and_nonnull<VarDecl>(VD) &&
386 VD->hasAttr<ObjCPreciseLifetimeAttr>();
390 } else {
391 / __weak objects always get EH cleanups; otherwise, exceptions
392 / could cause really nasty crashes instead of mere leaks.
395 }
396 if (Duration == SD_FullExpression)
397 CGF.pushDestroy(CleanupKind, ReferenceTemporary,
398 M->getType(), *Destroy,
400 else
401 CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
402 M->getType(),
403 *Destroy, CleanupKind & EHCleanup);
404 return;
405
406 case SD_Dynamic:
407 llvm_unreachable("temporary cannot have dynamic storage duration");
408 }
409 llvm_unreachable("unknown storage duration");
410 }
411 }
412
414 if (DK != QualType::DK_none) {
415 switch (M->getStorageDuration()) {
416 case SD_Static:
417 case SD_Thread: {
418 CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
419 if (const auto *ClassDecl =
421 ClassDecl && !ClassDecl->hasTrivialDestructor())
422 / Get the destructor for the reference temporary.
423 ReferenceTemporaryDtor = ClassDecl->getDestructor();
424
425 if (!ReferenceTemporaryDtor)
426 return;
427
428 llvm::FunctionCallee CleanupFn;
429 llvm::Constant *CleanupArg;
430 if (E->getType()->isArrayType()) {
432 ReferenceTemporary, E->getType(), CodeGenFunction::destroyCXXObject,
433 CGF.getLangOpts().Exceptions,
434 dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
435 CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
436 } else {
437 CleanupFn = CGF.CGM.getAddrAndTypeOfCXXStructor(
438 GlobalDecl(ReferenceTemporaryDtor, Dtor_Complete));
439 CleanupArg =
440 cast<llvm::Constant>(ReferenceTemporary.emitRawPointer(CGF));
441 }
443 CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
444 } break;
446 CGF.pushDestroy(DK, ReferenceTemporary, E->getType());
447 break;
448 case SD_Automatic:
449 CGF.pushLifetimeExtendedDestroy(DK, ReferenceTemporary, E->getType());
450 break;
451 case SD_Dynamic:
452 llvm_unreachable("temporary cannot have dynamic storage duration");
453 }
454 }
455}
456
459 const Expr *Inner,
460 RawAddress *Alloca = nullptr) {
461 auto &TCG = CGF.getTargetHooks();
462 switch (M->getStorageDuration()) {
464 case SD_Automatic: {
465 / If we have a constant temporary array or record try to promote it into a
466 / constant global under the same rules a normal constant would've been
467 / promoted. This is easier on the optimizer and generally emits fewer
468 / instructions.
469 QualType Ty = Inner->getType();
470 if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
471 (Ty->isArrayType() || Ty->isRecordType()) &&
472 Ty.isConstantStorage(CGF.getContext(), true, false))
473 if (auto Init = ConstantEmitter(CGF).tryEmitAbstract(Inner, Ty)) {
474 auto AS = CGF.CGM.GetGlobalConstantAddressSpace();
475 auto *GV = new llvm::GlobalVariable(
476 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
477 llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp", nullptr,
478 llvm::GlobalValue::NotThreadLocal,
480 CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
481 GV->setAlignment(alignment.getAsAlign());
482 llvm::Constant *C = GV;
483 if (AS != LangAS::Default)
484 C = TCG.performAddrSpaceCast(
485 CGF.CGM, GV, AS,
486 llvm::PointerType::get(
487 CGF.getLLVMContext(),
489 / FIXME: Should we put the new global into a COMDAT?
490 return RawAddress(C, GV->getValueType(), alignment);
491 }
492 return CGF.CreateMemTemp(Ty, "ref.tmp", Alloca);
493 }
494 case SD_Thread:
495 case SD_Static:
496 return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
497
498 case SD_Dynamic:
499 llvm_unreachable("temporary can't have dynamic storage duration");
500 }
501 llvm_unreachable("unknown storage duration");
502}
503
504/ Helper method to check if the underlying ABI is AAPCS
505static bool isAAPCS(const TargetInfo &TargetInfo) {
506 return TargetInfo.getABI().starts_with("aapcs");
507}
508
511 const Expr *E = M->getSubExpr();
512
513 assert((!M->getExtendingDecl() || !isa<VarDecl>(M->getExtendingDecl()) ||
514 !cast<VarDecl>(M->getExtendingDecl())->isARCPseudoStrong()) &&
515 "Reference should never be pseudo-strong!");
516
517 / FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
518 / as that will cause the lifetime adjustment to be lost for ARC
519 auto ownership = M->getType().getObjCLifetime();
520 if (ownership != Qualifiers::OCL_None &&
521 ownership != Qualifiers::OCL_ExplicitNone) {
522 RawAddress Object = createReferenceTemporary(*this, M, E);
523 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
524 llvm::Type *Ty = ConvertTypeForMem(E->getType());
525 Object = Object.withElementType(Ty);
526
527 / createReferenceTemporary will promote the temporary to a global with a
528 / constant initializer if it can. It can only do this to a value of
529 / ARC-manageable type if the value is global and therefore "immune" to
530 / ref-counting operations. Therefore we have no need to emit either a
531 / dynamic initialization or a cleanup and we can just return the address
532 / of the temporary.
533 if (Var->hasInitializer())
534 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
535
536 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
537 }
538 LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
540
541 switch (getEvaluationKind(E->getType())) {
542 default: llvm_unreachable("expected scalar or aggregate expression");
543 case TEK_Scalar:
544 EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
545 break;
546 case TEK_Aggregate: {
548 E->getType().getQualifiers(),
553 break;
554 }
555 }
556
557 pushTemporaryCleanup(*this, M, E, Object);
558 return RefTempDst;
559 }
560
563 E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
564
565 for (const auto &Ignored : CommaLHSs)
566 EmitIgnoredExpr(Ignored);
567
568 if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
569 if (opaque->getType()->isRecordType()) {
570 assert(Adjustments.empty());
571 return EmitOpaqueValueLValue(opaque);
572 }
573 }
574
575 / Create and initialize the reference temporary.
576 RawAddress Alloca = Address::invalid();
577 RawAddress Object = createReferenceTemporary(*this, M, E, &Alloca);
578 if (auto *Var = dyn_cast<llvm::GlobalVariable>(
579 Object.getPointer()->stripPointerCasts())) {
580 llvm::Type *TemporaryType = ConvertTypeForMem(E->getType());
581 Object = Object.withElementType(TemporaryType);
582 / If the temporary is a global and has a constant initializer or is a
583 / constant temporary that we promoted to a global, we may have already
584 / initialized it.
585 if (!Var->hasInitializer()) {
586 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
588 if (RefType.getPointerAuth()) {
589 / Use the qualifier of the reference temporary to sign the pointer.
590 LValue LV = MakeRawAddrLValue(Object.getPointer(), RefType,
591 Object.getAlignment());
592 EmitScalarInit(E, M->getExtendingDecl(), LV, false);
593 } else {
594 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/ true);
595 }
596 }
597 } else {
598 switch (M->getStorageDuration()) {
599 case SD_Automatic:
600 if (EmitLifetimeStart(Alloca.getPointer())) {
602 Alloca);
603 }
604 break;
605
606 case SD_FullExpression: {
607 if (!ShouldEmitLifetimeMarkers)
608 break;
609
610 / Avoid creating a conditional cleanup just to hold an llvm.lifetime.end
611 / marker. Instead, start the lifetime of a conditional temporary earlier
612 / so that it's unconditional. Don't do this with sanitizers which need
613 / more precise lifetime marks. However when inside an "await.suspend"
614 / block, we should always avoid conditional cleanup because it creates
615 / boolean marker that lives across await_suspend, which can destroy coro
616 / frame.
617 ConditionalEvaluation *OldConditional = nullptr;
618 CGBuilderTy::InsertPoint OldIP;
620 ((!SanOpts.has(SanitizerKind::HWAddress) &&
621 !SanOpts.has(SanitizerKind::Memory) &&
622 !CGM.getCodeGenOpts().SanitizeAddressUseAfterScope) ||
623 inSuspendBlock())) {
624 OldConditional = OutermostConditional;
625 OutermostConditional = nullptr;
626
627 OldIP = Builder.saveIP();
628 llvm::BasicBlock *Block = OldConditional->getStartingBlock();
629 Builder.restoreIP(CGBuilderTy::InsertPoint(
630 Block, llvm::BasicBlock::iterator(Block->back())));
631 }
632
633 if (EmitLifetimeStart(Alloca.getPointer())) {
635 }
636
637 if (OldConditional) {
638 OutermostConditional = OldConditional;
639 Builder.restoreIP(OldIP);
640 }
641 break;
642 }
643
644 default:
645 break;
646 }
647 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
648 }
649 pushTemporaryCleanup(*this, M, E, Object);
650
651 / Perform derived-to-base casts and/or field accesses, to get from the
652 / temporary object we created (and, potentially, for which we extended
653 / the lifetime) to the subobject we're binding the reference to.
654 for (SubobjectAdjustment &Adjustment : llvm::reverse(Adjustments)) {
655 switch (Adjustment.Kind) {
657 Object =
658 GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
659 Adjustment.DerivedToBase.BasePath->path_begin(),
660 Adjustment.DerivedToBase.BasePath->path_end(),
661 /*NullCheckValue=*/ false, E->getExprLoc());
662 break;
663
666 LV = EmitLValueForField(LV, Adjustment.Field);
667 assert(LV.isSimple() &&
668 "materialized temporary field is not a simple lvalue");
669 Object = LV.getAddress();
670 break;
671 }
672
674 llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
676 E, Object, Ptr, Adjustment.Ptr.MPT, /*IsInBounds=*/true);
677 break;
678 }
679 }
680 }
681
682 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
683}
684
685RValue
687 / Emit the expression as an lvalue.
688 LValue LV = EmitLValue(E);
689 assert(LV.isSimple());
690 llvm::Value *Value = LV.getPointer(*this);
691
693 / C++11 [dcl.ref]p5 (as amended by core issue 453):
694 / If a glvalue to which a reference is directly bound designates neither
695 / an existing object or function of an appropriate type nor a region of
696 / storage of suitable size and alignment to contain an object of the
697 / reference's type, the behavior is undefined.
698 QualType Ty = E->getType();
700 }
701
702 return RValue::get(Value);
703}
704
705
706/ getAccessedFieldNo - Given an encoded value and a result number, return the
707/ input field number being accessed.
709 const llvm::Constant *Elts) {
710 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
711 ->getZExtValue();
712}
713
714static llvm::Value *emitHashMix(CGBuilderTy &Builder, llvm::Value *Acc,
715 llvm::Value *Ptr) {
716 llvm::Value *A0 =
717 Builder.CreateMul(Ptr, Builder.getInt64(0xbf58476d1ce4e5b9u));
718 llvm::Value *A1 =
719 Builder.CreateXor(A0, Builder.CreateLShr(A0, Builder.getInt64(31)));
720 return Builder.CreateXor(Acc, A1);
721}
722
727
730 return (RD && RD->hasDefinition() && RD->isDynamicClass()) &&
731 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
734}
735
737 return SanOpts.has(SanitizerKind::Null) ||
738 SanOpts.has(SanitizerKind::Alignment) ||
739 SanOpts.has(SanitizerKind::ObjectSize) ||
740 SanOpts.has(SanitizerKind::Vptr);
741}
742
744 llvm::Value *Ptr, QualType Ty,
745 CharUnits Alignment,
746 SanitizerSet SkippedChecks,
747 llvm::Value *ArraySize) {
749 return;
750
751 / Don't check pointers outside the default address space. The null check
752 / isn't correct, the object-size check isn't supported by LLVM, and we can't
753 / communicate the addresses to the runtime handler for the vptr check.
754 if (Ptr->getType()->getPointerAddressSpace())
755 return;
756
757 / Don't check pointers to volatile data. The behavior here is implementation-
758 / defined.
759 if (Ty.isVolatileQualified())
760 return;
761
762 / Quickly determine whether we have a pointer to an alloca. It's possible
763 / to skip null checks, and some alignment checks, for these pointers. This
764 / can reduce compile-time significantly.
765 auto PtrToAlloca = dyn_cast<llvm::AllocaInst>(Ptr->stripPointerCasts());
766
767 llvm::Value *IsNonNull = nullptr;
768 bool IsGuaranteedNonNull =
769 SkippedChecks.has(SanitizerKind::Null) || PtrToAlloca;
770
771 llvm::BasicBlock *Done = nullptr;
772 bool DoneViaNullSanitize = false;
773
774 {
775 auto CheckHandler = SanitizerHandler::TypeMismatch;
776 SanitizerDebugLocation SanScope(this,
777 {SanitizerKind::SO_Null,
778 SanitizerKind::SO_ObjectSize,
779 SanitizerKind::SO_Alignment},
780 CheckHandler);
781
783 Checks;
784
785 llvm::Value *True = llvm::ConstantInt::getTrue(getLLVMContext());
786 bool AllowNullPointers = isNullPointerAllowed(TCK);
787 if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
788 !IsGuaranteedNonNull) {
789 / The glvalue must not be an empty glvalue.
790 IsNonNull = Builder.CreateIsNotNull(Ptr);
791
792 / The IR builder can constant-fold the null check if the pointer points
793 / to a constant.
794 IsGuaranteedNonNull = IsNonNull == True;
795
796 / Skip the null check if the pointer is known to be non-null.
797 if (!IsGuaranteedNonNull) {
798 if (AllowNullPointers) {
799 / When performing pointer casts, it's OK if the value is null.
800 / Skip the remaining checks in that case.
801 Done = createBasicBlock("null");
802 DoneViaNullSanitize = true;
803 llvm::BasicBlock *Rest = createBasicBlock("not.null");
804 Builder.CreateCondBr(IsNonNull, Rest, Done);
805 EmitBlock(Rest);
806 } else {
807 Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::SO_Null));
808 }
809 }
810 }
811
812 if (SanOpts.has(SanitizerKind::ObjectSize) &&
813 !SkippedChecks.has(SanitizerKind::ObjectSize) &&
814 !Ty->isIncompleteType()) {
815 uint64_t TySize = CGM.getMinimumObjectSize(Ty).getQuantity();
816 llvm::Value *Size = llvm::ConstantInt::get(IntPtrTy, TySize);
817 if (ArraySize)
818 Size = Builder.CreateMul(Size, ArraySize);
819
820 / Degenerate case: new X[0] does not need an objectsize check.
821 llvm::Constant *ConstantSize = dyn_cast<llvm::Constant>(Size);
822 if (!ConstantSize || !ConstantSize->isNullValue()) {
823 / The glvalue must refer to a large enough storage region.
824 / FIXME: If Address Sanitizer is enabled, insert dynamic
825 / instrumentation
826 / to check this.
827 / FIXME: Get object address space
828 llvm::Type *Tys[2] = {IntPtrTy, Int8PtrTy};
829 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
830 llvm::Value *Min = Builder.getFalse();
831 llvm::Value *NullIsUnknown = Builder.getFalse();
832 llvm::Value *Dynamic = Builder.getFalse();
833 llvm::Value *LargeEnough = Builder.CreateICmpUGE(
834 Builder.CreateCall(F, {Ptr, Min, NullIsUnknown, Dynamic}), Size);
835 Checks.push_back(
836 std::make_pair(LargeEnough, SanitizerKind::SO_ObjectSize));
837 }
838 }
839
840 llvm::MaybeAlign AlignVal;
841 llvm::Value *PtrAsInt = nullptr;
842
843 if (SanOpts.has(SanitizerKind::Alignment) &&
844 !SkippedChecks.has(SanitizerKind::Alignment)) {
845 AlignVal = Alignment.getAsMaybeAlign();
846 if (!Ty->isIncompleteType() && !AlignVal)
847 AlignVal = CGM.getNaturalTypeAlignment(Ty, nullptr, nullptr,
848 /*ForPointeeType=*/true)
849 .getAsMaybeAlign();
850
851 / The glvalue must be suitably aligned.
852 if (AlignVal && *AlignVal > llvm::Align(1) &&
853 (!PtrToAlloca || PtrToAlloca->getAlign() < *AlignVal)) {
854 PtrAsInt = Builder.CreatePtrToInt(Ptr, IntPtrTy);
855 llvm::Value *Align = Builder.CreateAnd(
856 PtrAsInt, llvm::ConstantInt::get(IntPtrTy, AlignVal->value() - 1));
857 llvm::Value *Aligned =
858 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
859 if (Aligned != True)
860 Checks.push_back(
861 std::make_pair(Aligned, SanitizerKind::SO_Alignment));
862 }
863 }
864
865 if (Checks.size() > 0) {
866 llvm::Constant *StaticData[] = {
868 llvm::ConstantInt::get(Int8Ty, AlignVal ? llvm::Log2(*AlignVal) : 1),
869 llvm::ConstantInt::get(Int8Ty, TCK)};
870 EmitCheck(Checks, CheckHandler, StaticData, PtrAsInt ? PtrAsInt : Ptr);
871 }
872 }
873
874 / If possible, check that the vptr indicates that there is a subobject of
875 / type Ty at offset zero within this object.
876 /
877 / C++11 [basic.life]p5,6:
878 / [For storage which does not refer to an object within its lifetime]
879 / The program has undefined behavior if:
880 / -- the [pointer or glvalue] is used to access a non-static data member
881 / or call a non-static member function
882 if (SanOpts.has(SanitizerKind::Vptr) &&
883 !SkippedChecks.has(SanitizerKind::Vptr) && isVptrCheckRequired(TCK, Ty)) {
884 SanitizerDebugLocation SanScope(this, {SanitizerKind::SO_Vptr},
885 SanitizerHandler::DynamicTypeCacheMiss);
886
887 / Ensure that the pointer is non-null before loading it. If there is no
888 / compile-time guarantee, reuse the run-time null check or emit a new one.
889 if (!IsGuaranteedNonNull) {
890 if (!IsNonNull)
891 IsNonNull = Builder.CreateIsNotNull(Ptr);
892 if (!Done)
893 Done = createBasicBlock("vptr.null");
894 llvm::BasicBlock *VptrNotNull = createBasicBlock("vptr.not.null");
895 Builder.CreateCondBr(IsNonNull, VptrNotNull, Done);
896 EmitBlock(VptrNotNull);
897 }
898
899 / Compute a deterministic hash of the mangled name of the type.
900 SmallString<64> MangledName;
901 llvm::raw_svector_ostream Out(MangledName);
902 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
903 Out);
904
905 / Contained in NoSanitizeList based on the mangled type.
906 if (!CGM.getContext().getNoSanitizeList().containsType(SanitizerKind::Vptr,
907 Out.str())) {
908 / Load the vptr, and mix it with TypeHash.
909 llvm::Value *TypeHash =
910 llvm::ConstantInt::get(Int64Ty, xxh3_64bits(Out.str()));
911
912 llvm::Type *VPtrTy = llvm::PointerType::get(getLLVMContext(), 0);
913 Address VPtrAddr(Ptr, IntPtrTy, getPointerAlign());
914 llvm::Value *VPtrVal = GetVTablePtr(VPtrAddr, VPtrTy,
915 Ty->getAsCXXRecordDecl(),
917 VPtrVal = Builder.CreateBitOrPointerCast(VPtrVal, IntPtrTy);
918
919 llvm::Value *Hash =
920 emitHashMix(Builder, TypeHash, Builder.CreateZExt(VPtrVal, Int64Ty));
921 Hash = Builder.CreateTrunc(Hash, IntPtrTy);
922
923 / Look the hash up in our cache.
924 const int CacheSize = 128;
925 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
926 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
927 "__ubsan_vptr_type_cache");
928 llvm::Value *Slot = Builder.CreateAnd(Hash,
929 llvm::ConstantInt::get(IntPtrTy,
930 CacheSize-1));
931 llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
932 llvm::Value *CacheVal = Builder.CreateAlignedLoad(
933 IntPtrTy, Builder.CreateInBoundsGEP(HashTable, Cache, Indices),
935
936 / If the hash isn't in the cache, call a runtime handler to perform the
937 / hard work of checking whether the vptr is for an object of the right
938 / type. This will either fill in the cache and return, or produce a
939 / diagnostic.
940 llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
941 llvm::Constant *StaticData[] = {
944 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
945 llvm::ConstantInt::get(Int8Ty, TCK)
946 };
947 llvm::Value *DynamicData[] = { Ptr, Hash };
948 EmitCheck(std::make_pair(EqualHash, SanitizerKind::SO_Vptr),
949 SanitizerHandler::DynamicTypeCacheMiss, StaticData,
950 DynamicData);
951 }
952 }
953
954 if (Done) {
955 SanitizerDebugLocation SanScope(
956 this,
957 {DoneViaNullSanitize ? SanitizerKind::SO_Null : SanitizerKind::SO_Vptr},
958 DoneViaNullSanitize ? SanitizerHandler::TypeMismatch
959 : SanitizerHandler::DynamicTypeCacheMiss);
960 Builder.CreateBr(Done);
961 EmitBlock(Done);
962 }
963}
964
966 QualType EltTy) {
968 uint64_t EltSize = C.getTypeSizeInChars(EltTy).getQuantity();
969 if (!EltSize)
970 return nullptr;
971
972 auto *ArrayDeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
973 if (!ArrayDeclRef)
974 return nullptr;
975
976 auto *ParamDecl = dyn_cast<ParmVarDecl>(ArrayDeclRef->getDecl());
977 if (!ParamDecl)
978 return nullptr;
979
980 auto *POSAttr = ParamDecl->getAttr<PassObjectSizeAttr>();
981 if (!POSAttr)
982 return nullptr;
983
984 / Don't load the size if it's a lower bound.
985 int POSType = POSAttr->getType();
986 if (POSType != 0 && POSType != 1)
987 return nullptr;
988
989 / Find the implicit size parameter.
990 auto PassedSizeIt = SizeArguments.find(ParamDecl);
991 if (PassedSizeIt == SizeArguments.end())
992 return nullptr;
993
994 const ImplicitParamDecl *PassedSizeDecl = PassedSizeIt->second;
995 assert(LocalDeclMap.count(PassedSizeDecl) && "Passed size not loadable");
996 Address AddrOfSize = LocalDeclMap.find(PassedSizeDecl)->second;
997 llvm::Value *SizeInBytes = EmitLoadOfScalar(AddrOfSize, /*Volatile=*/false,
998 C.getSizeType(), E->getExprLoc());
999 llvm::Value *SizeOfElement =
1000 llvm::ConstantInt::get(SizeInBytes->getType(), EltSize);
1001 return Builder.CreateUDiv(SizeInBytes, SizeOfElement);
1002}
1003
1004/ If Base is known to point to the start of an array, return the length of
1005/ that array. Return 0 if the length cannot be determined.
1007 const Expr *Base,
1008 QualType &IndexedType,
1010 StrictFlexArraysLevel) {
1011 / For the vector indexing extension, the bound is the number of elements.
1012 if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
1013 IndexedType = Base->getType();
1014 return CGF.Builder.getInt32(VT->getNumElements());
1015 }
1016
1017 Base = Base->IgnoreParens();
1018
1019 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
1020 if (CE->getCastKind() == CK_ArrayToPointerDecay &&
1021 !CE->getSubExpr()->isFlexibleArrayMemberLike(CGF.getContext(),
1022 StrictFlexArraysLevel)) {
1023 CodeGenFunction::SanitizerScope SanScope(&CGF);
1024
1025 IndexedType = CE->getSubExpr()->getType();
1026 const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
1027 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
1028 return CGF.Builder.getInt(CAT->getSize());
1029
1030 if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
1031 return CGF.getVLASize(VAT).NumElts;
1032 / Ignore pass_object_size here. It's not applicable on decayed pointers.
1033 }
1034 }
1035
1036 CodeGenFunction::SanitizerScope SanScope(&CGF);
1037
1038 QualType EltTy{Base->getType()->getPointeeOrArrayElementType(), 0};
1039 if (llvm::Value *POS = CGF.LoadPassedObjectSize(Base, EltTy)) {
1040 IndexedType = Base->getType();
1041 return POS;
1042 }
1043
1044 return nullptr;
1045}
1046
1047namespace {
1048
1049/ \p StructAccessBase returns the base \p Expr of a field access. It returns
1050/ either a \p DeclRefExpr, representing the base pointer to the struct, i.e.:
1051/
1052/ p in p-> a.b.c
1053/
1054/ or a \p MemberExpr, if the \p MemberExpr has the \p RecordDecl we're
1055/ looking for:
1056/
1057/ struct s {
1058/ struct s *ptr;
1059/ int count;
1060/ char array[] __attribute__((counted_by(count)));
1061/ };
1062/
1063/ If we have an expression like \p p->ptr->array[index], we want the
1064/ \p MemberExpr for \p p->ptr instead of \p p.
1065class StructAccessBase
1066 : public ConstStmtVisitor<StructAccessBase, const Expr *> {
1067 const RecordDecl *ExpectedRD;
1068
1069 bool IsExpectedRecordDecl(const Expr *E) const {
1070 QualType Ty = E->getType();
1071 if (Ty->isPointerType())
1072 Ty = Ty->getPointeeType();
1073 return ExpectedRD == Ty->getAsRecordDecl();
1074 }
1075
1076public:
1077 StructAccessBase(const RecordDecl *ExpectedRD) : ExpectedRD(ExpectedRD) {}
1078
1079 /===--------------------------------------------------------------------===/
1080 / Visitor Methods
1081 /===--------------------------------------------------------------------===/
1082
1083 / NOTE: If we build C++ support for counted_by, then we'll have to handle
1084 / horrors like this:
1085 /
1086 / struct S {
1087 / int x, y;
1088 / int blah[] __attribute__((counted_by(x)));
1089 / } s;
1090 /
1091 / int foo(int index, int val) {
1092 / int (S::*IHatePMDs)[] = &S::blah;
1093 / (s.*IHatePMDs)[index] = val;
1094 / }
1095
1096 const Expr *Visit(const Expr *E) {
1097 return ConstStmtVisitor<StructAccessBase, const Expr *>::Visit(E);
1098 }
1099
1100 const Expr *VisitStmt(const Stmt *S) { return nullptr; }
1101
1102 / These are the types we expect to return (in order of most to least
1103 / likely):
1104 /
1105 / 1. DeclRefExpr - This is the expression for the base of the structure.
1106 / It's exactly what we want to build an access to the \p counted_by
1107 / field.
1108 / 2. MemberExpr - This is the expression that has the same \p RecordDecl
1109 / as the flexble array member's lexical enclosing \p RecordDecl. This
1110 / allows us to catch things like: "p->p->array"
1111 / 3. CompoundLiteralExpr - This is for people who create something
1112 / heretical like (struct foo has a flexible array member):
1113 /
1114 / (struct foo){ 1, 2 }.blah[idx];
1115 const Expr *VisitDeclRefExpr(const DeclRefExpr *E) {
1116 return IsExpectedRecordDecl(E) ? E : nullptr;
1117 }
1118 const Expr *VisitMemberExpr(const MemberExpr *E) {
1119 if (IsExpectedRecordDecl(E) && E->isArrow())
1120 return E;
1121 const Expr *Res = Visit(E->getBase());
1122 return !Res && IsExpectedRecordDecl(E) ? E : Res;
1123 }
1124 const Expr *VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
1125 return IsExpectedRecordDecl(E) ? E : nullptr;
1126 }
1127 const Expr *VisitCallExpr(const CallExpr *E) {
1128 return IsExpectedRecordDecl(E) ? E : nullptr;
1129 }
1130
1131 const Expr *VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
1132 if (IsExpectedRecordDecl(E))
1133 return E;
1134 return Visit(E->getBase());
1135 }
1136 const Expr *VisitCastExpr(const CastExpr *E) {
1137 if (E->getCastKind() == CK_LValueToRValue)
1138 return IsExpectedRecordDecl(E) ? E : nullptr;
1139 return Visit(E->getSubExpr());
1140 }
1141 const Expr *VisitParenExpr(const ParenExpr *E) {
1142 return Visit(E->getSubExpr());
1143 }
1144 const Expr *VisitUnaryAddrOf(const UnaryOperator *E) {
1145 return Visit(E->getSubExpr());
1146 }
1147 const Expr *VisitUnaryDeref(const UnaryOperator *E) {
1148 return Visit(E->getSubExpr());
1149 }
1150};
1151
1152} / end anonymous namespace
1153
1155
1157 const FieldDecl *Field,
1158 RecIndicesTy &Indices) {
1159 const CGRecordLayout &Layout = CGF.CGM.getTypes().getCGRecordLayout(RD);
1160 int64_t FieldNo = -1;
1161 for (const FieldDecl *FD : RD->fields()) {
1162 if (!Layout.containsFieldDecl(FD))
1163 / This could happen if the field has a struct type that's empty. I don't
1164 / know why either.
1165 continue;
1166
1167 FieldNo = Layout.getLLVMFieldNo(FD);
1168 if (FD == Field) {
1169 Indices.emplace_back(CGF.Builder.getInt32(FieldNo));
1170 return true;
1171 }
1172
1173 QualType Ty = FD->getType();
1174 if (Ty->isRecordType()) {
1175 if (getGEPIndicesToField(CGF, Ty->getAsRecordDecl(), Field, Indices)) {
1176 if (RD->isUnion())
1177 FieldNo = 0;
1178 Indices.emplace_back(CGF.Builder.getInt32(FieldNo));
1179 return true;
1180 }
1181 }
1182 }
1183
1184 return false;
1185}
1186
1188 const Expr *Base, const FieldDecl *FAMDecl, const FieldDecl *CountDecl) {
1189 const RecordDecl *RD = CountDecl->getParent()->getOuterLexicalRecordContext();
1190
1191 / Find the base struct expr (i.e. p in p->a.b.c.d).
1192 const Expr *StructBase = StructAccessBase(RD).Visit(Base);
1193 if (!StructBase || StructBase->HasSideEffects(getContext()))
1194 return nullptr;
1195
1196 llvm::Value *Res = nullptr;
1197 if (StructBase->getType()->isPointerType()) {
1198 LValueBaseInfo BaseInfo;
1199 TBAAAccessInfo TBAAInfo;
1200 Address Addr = EmitPointerWithAlignment(StructBase, &BaseInfo, &TBAAInfo);
1201 Res = Addr.emitRawPointer(*this);
1202 } else if (StructBase->isLValue()) {
1203 LValue LV = EmitLValue(StructBase);
1204 Address Addr = LV.getAddress();
1205 Res = Addr.emitRawPointer(*this);
1206 } else {
1207 return nullptr;
1208 }
1209
1210 RecIndicesTy Indices;
1211 getGEPIndicesToField(*this, RD, CountDecl, Indices);
1212 if (Indices.empty())
1213 return nullptr;
1214
1215 Indices.push_back(Builder.getInt32(0));
1216 CanQualType T = CGM.getContext().getCanonicalTagType(RD);
1217 return Builder.CreateInBoundsGEP(ConvertType(T), Res,
1218 RecIndicesTy(llvm::reverse(Indices)),
1219 "counted_by.gep");
1220}
1221
1222/ This method is typically called in contexts where we can't generate
1223/ side-effects, like in __builtin_dynamic_object_size. When finding
1224/ expressions, only choose those that have either already been emitted or can
1225/ be loaded without side-effects.
1226/
1227/ - \p FAMDecl: the \p Decl for the flexible array member. It may not be
1228/ within the top-level struct.
1229/ - \p CountDecl: must be within the same non-anonymous struct as \p FAMDecl.
1231 const Expr *Base, const FieldDecl *FAMDecl, const FieldDecl *CountDecl) {
1232 if (llvm::Value *GEP = GetCountedByFieldExprGEP(Base, FAMDecl, CountDecl))
1233 return Builder.CreateAlignedLoad(ConvertType(CountDecl->getType()), GEP,
1234 getIntAlign(), "counted_by.load");
1235 return nullptr;
1236}
1237
1239 const Expr *ArrayExprBase,
1240 llvm::Value *IndexVal, QualType IndexType,
1241 bool Accessed) {
1242 assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
1243 "should not be called unless adding bounds checks");
1244 const LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
1245 getLangOpts().getStrictFlexArraysLevel();
1246 QualType ArrayExprBaseType;
1247 llvm::Value *BoundsVal = getArrayIndexingBound(
1248 *this, ArrayExprBase, ArrayExprBaseType, StrictFlexArraysLevel);
1249
1250 EmitBoundsCheckImpl(ArrayExpr, ArrayExprBaseType, IndexVal, IndexType,
1251 BoundsVal, getContext().getSizeType(), Accessed);
1252}
1253
1255 QualType ArrayBaseType,
1256 llvm::Value *IndexVal,
1257 QualType IndexType,
1258 llvm::Value *BoundsVal,
1259 QualType BoundsType, bool Accessed) {
1260 if (!BoundsVal)
1261 return;
1262
1263 auto CheckKind = SanitizerKind::SO_ArrayBounds;
1264 auto CheckHandler = SanitizerHandler::OutOfBounds;
1265 SanitizerDebugLocation SanScope(this, {CheckKind}, CheckHandler);
1266
1267 / All hail the C implicit type conversion rules!!!
1268 bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
1269 bool BoundsSigned = BoundsType->isSignedIntegerOrEnumerationType();
1270
1271 const ASTContext &Ctx = getContext();
1272 llvm::Type *Ty = ConvertType(
1273 Ctx.getTypeSize(IndexType) >= Ctx.getTypeSize(BoundsType) ? IndexType
1274 : BoundsType);
1275
1276 llvm::Value *IndexInst = Builder.CreateIntCast(IndexVal, Ty, IndexSigned);
1277 llvm::Value *BoundsInst = Builder.CreateIntCast(BoundsVal, Ty, false);
1278
1279 llvm::Constant *StaticData[] = {
1280 EmitCheckSourceLocation(ArrayExpr->getExprLoc()),
1281 EmitCheckTypeDescriptor(ArrayBaseType),
1282 EmitCheckTypeDescriptor(IndexType),
1283 };
1284
1285 llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexInst, BoundsInst)
1286 : Builder.CreateICmpULE(IndexInst, BoundsInst);
1287
1288 if (BoundsSigned) {
1289 / Don't allow a negative bounds.
1290 llvm::Value *Cmp = Builder.CreateICmpSGT(
1291 BoundsVal, llvm::ConstantInt::get(BoundsVal->getType(), 0));
1292 Check = Builder.CreateAnd(Cmp, Check);
1293 }
1294
1295 EmitCheck(std::make_pair(Check, CheckKind), CheckHandler, StaticData,
1296 IndexInst);
1297}
1298
1300 auto ATMD = infer_alloc::getAllocTokenMetadata(AllocType, getContext());
1301 if (!ATMD)
1302 return nullptr;
1303
1304 llvm::MDBuilder MDB(getLLVMContext());
1305 auto *TypeNameMD = MDB.createString(ATMD->TypeName);
1306 auto *ContainsPtrC = Builder.getInt1(ATMD->ContainsPointer);
1307 auto *ContainsPtrMD = MDB.createConstant(ContainsPtrC);
1308
1309 / Format: !{<type-name>, <contains-pointer>}
1310 return llvm::MDNode::get(CGM.getLLVMContext(), {TypeNameMD, ContainsPtrMD});
1311}
1312
1313void CodeGenFunction::EmitAllocToken(llvm::CallBase *CB, QualType AllocType) {
1314 assert(SanOpts.has(SanitizerKind::AllocToken) &&
1315 "Only needed with -fsanitize=alloc-token");
1316 CB->setMetadata(llvm::LLVMContext::MD_alloc_token,
1317 buildAllocToken(AllocType));
1318}
1319
1322 if (!AllocType.isNull())
1323 return buildAllocToken(AllocType);
1324 return nullptr;
1325}
1326
1327void CodeGenFunction::EmitAllocToken(llvm::CallBase *CB, const CallExpr *E) {
1328 assert(SanOpts.has(SanitizerKind::AllocToken) &&
1329 "Only needed with -fsanitize=alloc-token");
1330 if (llvm::MDNode *MDN = buildAllocToken(E))
1331 CB->setMetadata(llvm::LLVMContext::MD_alloc_token, MDN);
1332}
1333
1336 bool isInc, bool isPre) {
1337 ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
1338
1339 llvm::Value *NextVal;
1340 if (isa<llvm::IntegerType>(InVal.first->getType())) {
1341 uint64_t AmountVal = isInc ? 1 : -1;
1342 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
1343
1344 / Add the inc/dec to the real part.
1345 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
1346 } else {
1347 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
1348 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
1349 if (!isInc)
1350 FVal.changeSign();
1351 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
1352
1353 / Add the inc/dec to the real part.
1354 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
1355 }
1356
1357 ComplexPairTy IncVal(NextVal, InVal.second);
1358
1359 / Store the updated result through the lvalue.
1360 EmitStoreOfComplex(IncVal, LV, /*init*/ false);
1361 if (getLangOpts().OpenMP)
1362 CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(*this,
1363 E->getSubExpr());
1364
1365 / If this is a postinc, return the value read from memory, otherwise use the
1366 / updated value.
1367 return isPre ? IncVal : InVal;
1368}
1369
1371 CodeGenFunction *CGF) {
1372 / Bind VLAs in the cast type.
1373 if (CGF && E->getType()->isVariablyModifiedType())
1375
1376 if (CGDebugInfo *DI = getModuleDebugInfo())
1377 DI->EmitExplicitCastType(E->getType());
1378}
1379
1380/===----------------------------------------------------------------------===/
1381/ LValue Expression Emission
1382/===----------------------------------------------------------------------===/
1383
1384static CharUnits getArrayElementAlign(CharUnits arrayAlign, llvm::Value *idx,
1385 CharUnits eltSize) {
1386 / If we have a constant index, we can use the exact offset of the
1387 / element we're accessing.
1388 if (auto *constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
1389 CharUnits offset = constantIdx->getZExtValue() * eltSize;
1390 return arrayAlign.alignmentAtOffset(offset);
1391 }
1392
1393 / Otherwise, use the worst-case alignment for any element.
1394 return arrayAlign.alignmentOfArrayElement(eltSize);
1395}
1396
1397/ Emit pointer + index arithmetic.
1399 const BinaryOperator *BO,
1400 LValueBaseInfo *BaseInfo,
1401 TBAAAccessInfo *TBAAInfo,
1402 KnownNonNull_t IsKnownNonNull) {
1403 assert(BO->isAdditiveOp() && "Expect an addition or subtraction.");
1404 Expr *pointerOperand = BO->getLHS();
1405 Expr *indexOperand = BO->getRHS();
1406 bool isSubtraction = BO->getOpcode() == BO_Sub;
1407
1408 Address BaseAddr = Address::invalid();
1409 llvm::Value *index = nullptr;
1410 / In a subtraction, the LHS is always the pointer.
1411 / Note: do not change the evaluation order.
1412 if (!isSubtraction && !pointerOperand->getType()->isAnyPointerType()) {
1413 std::swap(pointerOperand, indexOperand);
1414 index = CGF.EmitScalarExpr(indexOperand);
1415 BaseAddr = CGF.EmitPointerWithAlignment(pointerOperand, BaseInfo, TBAAInfo,
1417 } else {
1418 BaseAddr = CGF.EmitPointerWithAlignment(pointerOperand, BaseInfo, TBAAInfo,
1420 index = CGF.EmitScalarExpr(indexOperand);
1421 }
1422
1423 llvm::Value *pointer = BaseAddr.getBasePointer();
1424 llvm::Value *Res = CGF.EmitPointerArithmetic(
1425 BO, pointerOperand, pointer, indexOperand, index, isSubtraction);
1426 QualType PointeeTy = BO->getType()->getPointeeType();
1427 CharUnits Align =
1429 CGF.getContext().getTypeSizeInChars(PointeeTy));
1430 return Address(Res, CGF.ConvertTypeForMem(PointeeTy), Align,
1432 /*Offset=*/nullptr, IsKnownNonNull);
1433}
1434
1436 TBAAAccessInfo *TBAAInfo,
1437 KnownNonNull_t IsKnownNonNull,
1438 CodeGenFunction &CGF) {
1439 / We allow this with ObjC object pointers because of fragile ABIs.
1440 assert(E->getType()->isPointerType() ||
1442 E = E->IgnoreParens();
1443
1444 / Casts:
1445 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
1446 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
1447 CGF.CGM.EmitExplicitCastExprType(ECE, &CGF);
1448
1449 switch (CE->getCastKind()) {
1450 / Non-converting casts (but not C's implicit conversion from void*).
1451 case CK_BitCast:
1452 case CK_NoOp:
1453 case CK_AddressSpaceConversion:
1454 if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
1455 if (PtrTy->getPointeeType()->isVoidType())
1456 break;
1457
1458 LValueBaseInfo InnerBaseInfo;
1459 TBAAAccessInfo InnerTBAAInfo;
1461 CE->getSubExpr(), &InnerBaseInfo, &InnerTBAAInfo, IsKnownNonNull);
1462 if (BaseInfo) *BaseInfo = InnerBaseInfo;
1463 if (TBAAInfo) *TBAAInfo = InnerTBAAInfo;
1464
1465 if (isa<ExplicitCastExpr>(CE)) {
1466 LValueBaseInfo TargetTypeBaseInfo;
1467 TBAAAccessInfo TargetTypeTBAAInfo;
1469 E->getType(), &TargetTypeBaseInfo, &TargetTypeTBAAInfo);
1470 if (TBAAInfo)
1471 *TBAAInfo =
1472 CGF.CGM.mergeTBAAInfoForCast(*TBAAInfo, TargetTypeTBAAInfo);
1473 / If the source l-value is opaque, honor the alignment of the
1474 / casted-to type.
1475 if (InnerBaseInfo.getAlignmentSource() != AlignmentSource::Decl) {
1476 if (BaseInfo)
1477 BaseInfo->mergeForCast(TargetTypeBaseInfo);
1478 Addr.setAlignment(Align);
1479 }
1480 }
1481
1482 if (CGF.SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
1483 CE->getCastKind() == CK_BitCast) {
1484 if (auto PT = E->getType()->getAs<PointerType>())
1485 CGF.EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr,
1486 /*MayBeNull=*/true,
1488 CE->getBeginLoc());
1489 }
1490
1491 llvm::Type *ElemTy =
1493 Addr = Addr.withElementType(ElemTy);
1494 if (CE->getCastKind() == CK_AddressSpaceConversion)
1496 Addr, CGF.ConvertType(E->getType()), ElemTy);
1497
1498 return CGF.authPointerToPointerCast(Addr, CE->getSubExpr()->getType(),
1499 CE->getType());
1500 }
1501 break;
1502
1503 / Array-to-pointer decay.
1504 case CK_ArrayToPointerDecay:
1505 return CGF.EmitArrayToPointerDecay(CE->getSubExpr(), BaseInfo, TBAAInfo);
1506
1507 / Derived-to-base conversions.
1508 case CK_UncheckedDerivedToBase:
1509 case CK_DerivedToBase: {
1510 / TODO: Support accesses to members of base classes in TBAA. For now, we
1511 / conservatively pretend that the complete object is of the base class
1512 / type.
1513 if (TBAAInfo)
1514 *TBAAInfo = CGF.CGM.getTBAAAccessInfo(E->getType());
1516 CE->getSubExpr(), BaseInfo, nullptr,
1517 (KnownNonNull_t)(IsKnownNonNull ||
1518 CE->getCastKind() == CK_UncheckedDerivedToBase));
1519 auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
1520 return CGF.GetAddressOfBaseClass(
1521 Addr, Derived, CE->path_begin(), CE->path_end(),
1522 CGF.ShouldNullCheckClassCastValue(CE), CE->getExprLoc());
1523 }
1524
1525 / TODO: Is there any reason to treat base-to-derived conversions
1526 / specially?
1527 default:
1528 break;
1529 }
1530 }
1531
1532 / Unary &.
1533 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1534 if (UO->getOpcode() == UO_AddrOf) {
1535 LValue LV = CGF.EmitLValue(UO->getSubExpr(), IsKnownNonNull);
1536 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
1537 if (TBAAInfo) *TBAAInfo = LV.getTBAAInfo();
1538 return LV.getAddress();
1539 }
1540 }
1541
1542 / std::addressof and variants.
1543 if (auto *Call = dyn_cast<CallExpr>(E)) {
1544 switch (Call->getBuiltinCallee()) {
1545 default:
1546 break;
1547 case Builtin::BIaddressof:
1548 case Builtin::BI__addressof:
1549 case Builtin::BI__builtin_addressof: {
1550 LValue LV = CGF.EmitLValue(Call->getArg(0), IsKnownNonNull);
1551 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
1552 if (TBAAInfo) *TBAAInfo = LV.getTBAAInfo();
1553 return LV.getAddress();
1554 }
1555 }
1556 }
1557
1558 / Pointer arithmetic: pointer +/- index.
1559 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
1560 if (BO->isAdditiveOp())
1561 return emitPointerArithmetic(CGF, BO, BaseInfo, TBAAInfo, IsKnownNonNull);
1562 }
1563
1564 / TODO: conditional operators, comma.
1565
1566 / Otherwise, use the alignment of the type.
1569 /*ForPointeeType=*/true, BaseInfo, TBAAInfo, IsKnownNonNull);
1570}
1571
1572/ EmitPointerWithAlignment - Given an expression of pointer type, try to
1573/ derive a more accurate bound on the alignment of the pointer.
1575 const Expr *E, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo,
1576 KnownNonNull_t IsKnownNonNull) {
1577 Address Addr =
1578 ::EmitPointerWithAlignment(E, BaseInfo, TBAAInfo, IsKnownNonNull, *this);
1579 if (IsKnownNonNull && !Addr.isKnownNonNull())
1580 Addr.setKnownNonNull();
1581 return Addr;
1582}
1583
1585 llvm::Value *V = RV.getScalarVal();
1586 if (auto MPT = T->getAs<MemberPointerType>())
1587 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, V, MPT);
1588 return Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
1589}
1590
1592 if (Ty->isVoidType())
1593 return RValue::get(nullptr);
1594
1595 switch (getEvaluationKind(Ty)) {
1596 case TEK_Complex: {
1597 llvm::Type *EltTy =
1599 llvm::Value *U = llvm::UndefValue::get(EltTy);
1600 return RValue::getComplex(std::make_pair(U, U));
1601 }
1602
1603 / If this is a use of an undefined aggregate type, the aggregate must have an
1604 / identifiable address. Just because the contents of the value are undefined
1605 / doesn't mean that the address can't be taken and compared.
1606 case TEK_Aggregate: {
1607 Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
1608 return RValue::getAggregate(DestPtr);
1609 }
1610
1611 case TEK_Scalar:
1612 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
1613 }
1614 llvm_unreachable("bad evaluation kind");
1615}
1616
1618 const char *Name) {
1619 ErrorUnsupported(E, Name);
1620 return GetUndefRValue(E->getType());
1621}
1622
1624 const char *Name) {
1625 ErrorUnsupported(E, Name);
1626 llvm::Type *ElTy = ConvertType(E->getType());
1627 llvm::Type *Ty = DefaultPtrTy;
1628 return MakeAddrLValue(
1629 Address(llvm::UndefValue::get(Ty), ElTy, CharUnits::One()), E->getType());
1630}
1631
1633 const Expr *Base = Obj;
1634 while (!isa<CXXThisExpr>(Base)) {
1635 / The result of a dynamic_cast can be null.
1637 return false;
1638
1639 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
1640 Base = CE->getSubExpr();
1641 } else if (const auto *PE = dyn_cast<ParenExpr>(Base)) {
1642 Base = PE->getSubExpr();
1643 } else if (const auto *UO = dyn_cast<UnaryOperator>(Base)) {
1644 if (UO->getOpcode() == UO_Extension)
1645 Base = UO->getSubExpr();
1646 else
1647 return false;
1648 } else {
1649 return false;
1650 }
1651 }
1652 return true;
1653}
1654
1656 LValue LV;
1657 if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
1658 LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
1659 else
1660 LV = EmitLValue(E);
1661 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple()) {
1662 SanitizerSet SkippedChecks;
1663 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
1664 bool IsBaseCXXThis = IsWrappedCXXThis(ME->getBase());
1665 if (IsBaseCXXThis)
1666 SkippedChecks.set(SanitizerKind::Alignment, true);
1667 if (IsBaseCXXThis || isa<DeclRefExpr>(ME->getBase()))
1668 SkippedChecks.set(SanitizerKind::Null, true);
1669 }
1670 EmitTypeCheck(TCK, E->getExprLoc(), LV, E->getType(), SkippedChecks);
1671 }
1672 return LV;
1673}
1674
1675/ EmitLValue - Emit code to compute a designator that specifies the location
1676/ of the expression.
1677/
1678/ This can return one of two things: a simple address or a bitfield reference.
1679/ In either case, the LLVM Value* in the LValue structure is guaranteed to be
1680/ an LLVM pointer type.
1681/
1682/ If this returns a bitfield reference, nothing about the pointee type of the
1683/ LLVM value is known: For example, it may not be a pointer to an integer.
1684/
1685/ If this returns a normal address, and if the lvalue's C type is fixed size,
1686/ this method guarantees that the returned pointer type will point to an LLVM
1687/ type of the same size of the lvalue's type. If the lvalue has a variable
1688/ length type, this is not possible.
1689/
1691 KnownNonNull_t IsKnownNonNull) {
1692 / Running with sufficient stack space to avoid deeply nested expressions
1693 / cause a stack overflow.
1694 LValue LV;
1695 CGM.runWithSufficientStackSpace(
1696 E->getExprLoc(), [&] { LV = EmitLValueHelper(E, IsKnownNonNull); });
1697
1698 if (IsKnownNonNull && !LV.isKnownNonNull())
1699 LV.setKnownNonNull();
1700 return LV;
1701}
1702
1704 const ASTContext &Ctx) {
1705 const Expr *SE = E->getSubExpr()->IgnoreImplicit();
1706 if (isa<OpaqueValueExpr>(SE))
1707 return SE->getType();
1708 return cast<CallExpr>(SE)->getCallReturnType(Ctx)->getPointeeType();
1709}
1710
1711LValue CodeGenFunction::EmitLValueHelper(const Expr *E,
1712 KnownNonNull_t IsKnownNonNull) {
1713 ApplyDebugLocation DL(*this, E);
1714 switch (E->getStmtClass()) {
1715 default: return EmitUnsupportedLValue(E, "l-value expression");
1716
1717 case Expr::ObjCPropertyRefExprClass:
1718 llvm_unreachable("cannot emit a property reference directly");
1719
1720 case Expr::ObjCSelectorExprClass:
1722 case Expr::ObjCIsaExprClass:
1724 case Expr::BinaryOperatorClass:
1726 case Expr::CompoundAssignOperatorClass: {
1727 QualType Ty = E->getType();
1728 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1729 Ty = AT->getValueType();
1730 if (!Ty->isAnyComplexType())
1733 }
1734 case Expr::CallExprClass:
1735 case Expr::CXXMemberCallExprClass:
1736 case Expr::CXXOperatorCallExprClass:
1737 case Expr::UserDefinedLiteralClass:
1739 case Expr::CXXRewrittenBinaryOperatorClass:
1740 return EmitLValue(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
1741 IsKnownNonNull);
1742 case Expr::VAArgExprClass:
1744 case Expr::DeclRefExprClass:
1746 case Expr::ConstantExprClass: {
1747 const ConstantExpr *CE = cast<ConstantExpr>(E);
1748 if (llvm::Value *Result = ConstantEmitter(*this).tryEmitConstantExpr(CE)) {
1749 QualType RetType = getConstantExprReferredType(CE, getContext());
1750 return MakeNaturalAlignAddrLValue(Result, RetType);
1751 }
1752 return EmitLValue(cast<ConstantExpr>(E)->getSubExpr(), IsKnownNonNull);
1753 }
1754 case Expr::ParenExprClass:
1755 return EmitLValue(cast<ParenExpr>(E)->getSubExpr(), IsKnownNonNull);
1756 case Expr::GenericSelectionExprClass:
1757 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr(),
1758 IsKnownNonNull);
1759 case Expr::PredefinedExprClass:
1761 case Expr::StringLiteralClass:
1763 case Expr::ObjCEncodeExprClass:
1765 case Expr::PseudoObjectExprClass:
1767 case Expr::InitListExprClass:
1769 case Expr::CXXTemporaryObjectExprClass:
1770 case Expr::CXXConstructExprClass:
1772 case Expr::CXXBindTemporaryExprClass:
1774 case Expr::CXXUuidofExprClass:
1776 case Expr::LambdaExprClass:
1777 return EmitAggExprToLValue(E);
1778
1779 case Expr::ExprWithCleanupsClass: {
1780 const auto *cleanups = cast<ExprWithCleanups>(E);
1781 RunCleanupsScope Scope(*this);
1782 LValue LV = EmitLValue(cleanups->getSubExpr(), IsKnownNonNull);
1783 if (LV.isSimple()) {
1784 / Defend against branches out of gnu statement expressions surrounded by
1785 / cleanups.
1786 Address Addr = LV.getAddress();
1787 llvm::Value *V = Addr.getBasePointer();
1788 Scope.ForceCleanup({&V});
1789 Addr.replaceBasePointer(V);
1790 return LValue::MakeAddr(Addr, LV.getType(), getContext(),
1791 LV.getBaseInfo(), LV.getTBAAInfo());
1792 }
1793 / FIXME: Is it possible to create an ExprWithCleanups that produces a
1794 / bitfield lvalue or some other non-simple lvalue?
1795 return LV;
1796 }
1797
1798 case Expr::CXXDefaultArgExprClass: {
1799 auto *DAE = cast<CXXDefaultArgExpr>(E);
1800 CXXDefaultArgExprScope Scope(*this, DAE);
1801 return EmitLValue(DAE->getExpr(), IsKnownNonNull);
1802 }
1803 case Expr::CXXDefaultInitExprClass: {
1804 auto *DIE = cast<CXXDefaultInitExpr>(E);
1805 CXXDefaultInitExprScope Scope(*this, DIE);
1806 return EmitLValue(DIE->getExpr(), IsKnownNonNull);
1807 }
1808 case Expr::CXXTypeidExprClass:
1810
1811 case Expr::ObjCMessageExprClass:
1813 case Expr::ObjCIvarRefExprClass:
1815 case Expr::StmtExprClass:
1817 case Expr::UnaryOperatorClass:
1819 case Expr::ArraySubscriptExprClass:
1821 case Expr::MatrixSubscriptExprClass:
1823 case Expr::ArraySectionExprClass:
1825 case Expr::ExtVectorElementExprClass:
1827 case Expr::CXXThisExprClass:
1829 case Expr::MemberExprClass:
1831 case Expr::CompoundLiteralExprClass:
1833 case Expr::ConditionalOperatorClass:
1835 case Expr::BinaryConditionalOperatorClass:
1837 case Expr::ChooseExprClass:
1838 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr(), IsKnownNonNull);
1839 case Expr::OpaqueValueExprClass:
1841 case Expr::SubstNonTypeTemplateParmExprClass:
1842 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
1843 IsKnownNonNull);
1844 case Expr::ImplicitCastExprClass:
1845 case Expr::CStyleCastExprClass:
1846 case Expr::CXXFunctionalCastExprClass:
1847 case Expr::CXXStaticCastExprClass:
1848 case Expr::CXXDynamicCastExprClass:
1849 case Expr::CXXReinterpretCastExprClass:
1850 case Expr::CXXConstCastExprClass:
1851 case Expr::CXXAddrspaceCastExprClass:
1852 case Expr::ObjCBridgedCastExprClass:
1853 return EmitCastLValue(cast<CastExpr>(E));
1854
1855 case Expr::MaterializeTemporaryExprClass:
1857
1858 case Expr::CoawaitExprClass:
1860 case Expr::CoyieldExprClass:
1862 case Expr::PackIndexingExprClass:
1863 return EmitLValue(cast<PackIndexingExpr>(E)->getSelectedExpr());
1864 case Expr::HLSLOutArgExprClass:
1865 llvm_unreachable("cannot emit a HLSL out argument directly");
1866 }
1867}
1868
1869/ Given an object of the given canonical type, can we safely copy a
1870/ value out of it based on its initializer?
1872 assert(type.isCanonical());
1873 assert(!type->isReferenceType());
1874
1875 / Must be const-qualified but non-volatile.
1876 Qualifiers qs = type.getLocalQualifiers();
1877 if (!qs.hasConst() || qs.hasVolatile()) return false;
1878
1879 / Otherwise, all object types satisfy this except C++ classes with
1880 / mutable subobjects or non-trivial copy/destroy behavior.
1881 if (const auto *RT = dyn_cast<RecordType>(type))
1882 if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1883 RD = RD->getDefinitionOrSelf();
1884 if (RD->hasMutableFields() || !RD->isTrivial())
1885 return false;
1886 }
1887
1888 return true;
1889}
1890
1891/ Can we constant-emit a load of a reference to a variable of the
1892/ given type? This is different from predicates like
1893/ Decl::mightBeUsableInConstantExpressions because we do want it to apply
1894/ in situations that don't necessarily satisfy the language's rules
1895/ for this (e.g. C++'s ODR-use rules). For example, we want to able
1896/ to do this with const float variables even if those variables
1897/ aren't marked 'constexpr'.
1905 type = type.getCanonicalType();
1906 if (const auto *ref = dyn_cast<ReferenceType>(type)) {
1907 if (isConstantEmittableObjectType(ref->getPointeeType()))
1909 return CEK_AsReferenceOnly;
1910 }
1912 return CEK_AsValueOnly;
1913 return CEK_None;
1914}
1915
1916/ Try to emit a reference to the given value without producing it as
1917/ an l-value. This is just an optimization, but it avoids us needing
1918/ to emit global copies of variables if they're named without triggering
1919/ a formal use in a context where we can't emit a direct reference to them,
1920/ for instance if a block or lambda or a member of a local class uses a
1921/ const int variable or constexpr variable from an enclosing function.
1924 const ValueDecl *Value = RefExpr->getDecl();
1925
1926 / The value needs to be an enum constant or a constant variable.
1928 if (isa<ParmVarDecl>(Value)) {
1929 CEK = CEK_None;
1930 } else if (const auto *var = dyn_cast<VarDecl>(Value)) {
1931 CEK = checkVarTypeForConstantEmission(var->getType());
1932 } else if (isa<EnumConstantDecl>(Value)) {
1933 CEK = CEK_AsValueOnly;
1934 } else {
1935 CEK = CEK_None;
1936 }
1937 if (CEK == CEK_None) return ConstantEmission();
1938
1939 Expr::EvalResult result;
1940 bool resultIsReference;
1941 QualType resultType;
1942
1943 / It's best to evaluate all the way as an r-value if that's permitted.
1944 if (CEK != CEK_AsReferenceOnly &&
1945 RefExpr->EvaluateAsRValue(result, getContext())) {
1946 resultIsReference = false;
1947 resultType = RefExpr->getType().getUnqualifiedType();
1948
1949 / Otherwise, try to evaluate as an l-value.
1950 } else if (CEK != CEK_AsValueOnly &&
1951 RefExpr->EvaluateAsLValue(result, getContext())) {
1952 resultIsReference = true;
1953 resultType = Value->getType();
1954
1955 / Failure.
1956 } else {
1957 return ConstantEmission();
1958 }
1959
1960 / In any case, if the initializer has side-effects, abandon ship.
1961 if (result.HasSideEffects)
1962 return ConstantEmission();
1963
1964 / In CUDA/HIP device compilation, a lambda may capture a reference variable
1965 / referencing a global host variable by copy. In this case the lambda should
1966 / make a copy of the value of the global host variable. The DRE of the
1967 / captured reference variable cannot be emitted as load from the host
1968 / global variable as compile time constant, since the host variable is not
1969 / accessible on device. The DRE of the captured reference variable has to be
1970 / loaded from captures.
1971 if (CGM.getLangOpts().CUDAIsDevice && result.Val.isLValue() &&
1973 auto *MD = dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl);
1974 if (isLambdaMethod(MD) && MD->getOverloadedOperator() == OO_Call) {
1975 const APValue::LValueBase &base = result.Val.getLValueBase();
1976 if (const ValueDecl *D = base.dyn_cast<const ValueDecl *>()) {
1977 if (const VarDecl *VD = dyn_cast<const VarDecl>(D)) {
1978 if (!VD->hasAttr<CUDADeviceAttr>()) {
1979 return ConstantEmission();
1980 }
1981 }
1982 }
1983 }
1984 }
1985
1986 / Emit as a constant.
1987 llvm::Constant *C = ConstantEmitter(*this).emitAbstract(
1988 RefExpr->getLocation(), result.Val, resultType);
1989
1990 / Make sure we emit a debug reference to the global variable.
1991 / This should probably fire even for
1992 if (isa<VarDecl>(Value)) {
1993 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(Value)))
1994 EmitDeclRefExprDbgValue(RefExpr, result.Val);
1995 } else {
1997 EmitDeclRefExprDbgValue(RefExpr, result.Val);
1998 }
1999
2000 / If we emitted a reference constant, we need to dereference that.
2001 if (resultIsReference)
2003
2005}
2006
2008 const MemberExpr *ME) {
2009 if (auto *VD = dyn_cast<VarDecl>(ME->getMemberDecl())) {
2010 / Try to emit static variable member expressions as DREs.
2011 return DeclRefExpr::Create(
2013 /*RefersToEnclosingVariableOrCapture=*/false, ME->getExprLoc(),
2014 ME->getType(), ME->getValueKind(), nullptr, nullptr, ME->isNonOdrUse());
2015 }
2016 return nullptr;
2017}
2018
2022 return tryEmitAsConstant(DRE);
2023 return ConstantEmission();
2024}
2025
2027 const CodeGenFunction::ConstantEmission &Constant, Expr *E) {
2028 assert(Constant && "not a constant");
2029 if (Constant.isReference())
2030 return EmitLoadOfLValue(Constant.getReferenceLValue(*this, E),
2031 E->getExprLoc())
2032 .getScalarVal();
2033 return Constant.getValue();
2034}
2035
2037 SourceLocation Loc) {
2038 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
2039 lvalue.getType(), Loc, lvalue.getBaseInfo(),
2040 lvalue.getTBAAInfo(), lvalue.isNontemporal());
2041}
2042
2044 llvm::APInt &Min, llvm::APInt &End,
2045 bool StrictEnums, bool IsBool) {
2046 const auto *ED = Ty->getAsEnumDecl();
2047 bool IsRegularCPlusPlusEnum =
2048 CGF.getLangOpts().CPlusPlus && StrictEnums && ED && !ED->isFixed();
2049 if (!IsBool && !IsRegularCPlusPlusEnum)
2050 return false;
2051
2052 if (IsBool) {
2053 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
2054 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
2055 } else {
2056 ED->getValueRange(End, Min);
2057 }
2058 return true;
2059}
2060
2061llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
2062 llvm::APInt Min, End;
2063 if (!getRangeForType(*this, Ty, Min, End, CGM.getCodeGenOpts().StrictEnums,
2064 Ty->hasBooleanRepresentation() && !Ty->isVectorType()))
2065 return nullptr;
2066
2067 llvm::MDBuilder MDHelper(getLLVMContext());
2068 return MDHelper.createRange(Min, End);
2069}
2070
2072 SourceLocation Loc) {
2073 if (EmitScalarRangeCheck(Load, Ty, Loc)) {
2074 / In order to prevent the optimizer from throwing away the check, don't
2075 / attach range metadata to the load.
2076 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0) {
2077 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty)) {
2078 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
2079 Load->setMetadata(llvm::LLVMContext::MD_noundef,
2080 llvm::MDNode::get(CGM.getLLVMContext(), {}));
2081 }
2082 }
2083}
2084
2086 SourceLocation Loc) {
2087 bool HasBoolCheck = SanOpts.has(SanitizerKind::Bool);
2088 bool HasEnumCheck = SanOpts.has(SanitizerKind::Enum);
2089 if (!HasBoolCheck && !HasEnumCheck)
2090 return false;
2091
2092 bool IsBool = (Ty->hasBooleanRepresentation() && !Ty->isVectorType()) ||
2093 NSAPI(CGM.getContext()).isObjCBOOLType(Ty);
2094 bool NeedsBoolCheck = HasBoolCheck && IsBool;
2095 bool NeedsEnumCheck = HasEnumCheck && Ty->isEnumeralType();
2096 if (!NeedsBoolCheck && !NeedsEnumCheck)
2097 return false;
2098
2099 / Single-bit booleans don't need to be checked. Special-case this to avoid
2100 / a bit width mismatch when handling bitfield values. This is handled by
2101 / EmitFromMemory for the non-bitfield case.
2102 if (IsBool &&
2103 cast<llvm::IntegerType>(Value->getType())->getBitWidth() == 1)
2104 return false;
2105
2106 if (NeedsEnumCheck &&
2107 getContext().isTypeIgnoredBySanitizer(SanitizerKind::Enum, Ty))
2108 return false;
2109
2110 llvm::APInt Min, End;
2111 if (!getRangeForType(*this, Ty, Min, End, /*StrictEnums=*/true, IsBool))
2112 return true;
2113
2115 NeedsEnumCheck ? SanitizerKind::SO_Enum : SanitizerKind::SO_Bool;
2116
2117 auto &Ctx = getLLVMContext();
2118 auto CheckHandler = SanitizerHandler::LoadInvalidValue;
2119 SanitizerDebugLocation SanScope(this, {Kind}, CheckHandler);
2120 llvm::Value *Check;
2121 --End;
2122 if (!Min) {
2123 Check = Builder.CreateICmpULE(Value, llvm::ConstantInt::get(Ctx, End));
2124 } else {
2125 llvm::Value *Upper =
2126 Builder.CreateICmpSLE(Value, llvm::ConstantInt::get(Ctx, End));
2127 llvm::Value *Lower =
2128 Builder.CreateICmpSGE(Value, llvm::ConstantInt::get(Ctx, Min));
2129 Check = Builder.CreateAnd(Upper, Lower);
2130 }
2131 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc),
2133 EmitCheck(std::make_pair(Check, Kind), CheckHandler, StaticArgs, Value);
2134 return true;
2135}
2136
2138 QualType Ty,
2139 SourceLocation Loc,
2140 LValueBaseInfo BaseInfo,
2141 TBAAAccessInfo TBAAInfo,
2142 bool isNontemporal) {
2143 if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr.getBasePointer()))
2144 if (GV->isThreadLocal())
2145 Addr = Addr.withPointer(Builder.CreateThreadLocalAddress(GV),
2147
2148 if (const auto *ClangVecTy = Ty->getAs<VectorType>()) {
2149 / Boolean vectors use `iN` as storage type.
2150 if (ClangVecTy->isPackedVectorBoolType(getContext())) {
2151 llvm::Type *ValTy = ConvertType(Ty);
2152 unsigned ValNumElems =
2153 cast<llvm::FixedVectorType>(ValTy)->getNumElements();
2154 / Load the `iP` storage object (P is the padded vector size).
2155 auto *RawIntV = Builder.CreateLoad(Addr, Volatile, "load_bits");
2156 const auto *RawIntTy = RawIntV->getType();
2157 assert(RawIntTy->isIntegerTy() && "compressed iN storage for bitvectors");
2158 / Bitcast iP --> <P x i1>.
2159 auto *PaddedVecTy = llvm::FixedVectorType::get(
2160 Builder.getInt1Ty(), RawIntTy->getPrimitiveSizeInBits());
2161 llvm::Value *V = Builder.CreateBitCast(RawIntV, PaddedVecTy);
2162 / Shuffle <P x i1> --> <N x i1> (N is the actual bit size).
2163 V = emitBoolVecConversion(V, ValNumElems, "extractvec");
2164
2165 return EmitFromMemory(V, Ty);
2166 }
2167
2168 / Handles vectors of sizes that are likely to be expanded to a larger size
2169 / to optimize performance.
2170 auto *VTy = cast<llvm::FixedVectorType>(Addr.getElementType());
2171 auto *NewVecTy =
2172 CGM.getABIInfo().getOptimalVectorMemoryType(VTy, getLangOpts());
2173
2174 if (VTy != NewVecTy) {
2175 Address Cast = Addr.withElementType(NewVecTy);
2176 llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVecN");
2177 unsigned OldNumElements = VTy->getNumElements();
2178 SmallVector<int, 16> Mask(OldNumElements);
2179 std::iota(Mask.begin(), Mask.end(), 0);
2180 V = Builder.CreateShuffleVector(V, Mask, "extractVec");
2181 return EmitFromMemory(V, Ty);
2182 }
2183 }
2184
2185 / Atomic operations have to be done on integral types.
2186 LValue AtomicLValue =
2187 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
2188 if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) {
2189 return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal();
2190 }
2191
2192 Addr =
2193 Addr.withElementType(convertTypeForLoadStore(Ty, Addr.getElementType()));
2194
2195 llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
2196 if (isNontemporal) {
2197 llvm::MDNode *Node = llvm::MDNode::get(
2198 Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
2199 Load->setMetadata(llvm::LLVMContext::MD_nontemporal, Node);
2200 }
2201
2202 CGM.DecorateInstructionWithTBAA(Load, TBAAInfo);
2203
2204 maybeAttachRangeForLoad(Load, Ty, Loc);
2205
2206 return EmitFromMemory(Load, Ty);
2207}
2208
2209/ Converts a scalar value from its primary IR type (as returned
2210/ by ConvertType) to its load/store type (as returned by
2211/ convertTypeForLoadStore).
2212llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
2213 if (auto *AtomicTy = Ty->getAs<AtomicType>())
2214 Ty = AtomicTy->getValueType();
2215
2216 if (Ty->isExtVectorBoolType()) {
2217 llvm::Type *StoreTy = convertTypeForLoadStore(Ty, Value->getType());
2218 if (StoreTy->isVectorTy() && StoreTy->getScalarSizeInBits() >
2219 Value->getType()->getScalarSizeInBits())
2220 return Builder.CreateZExt(Value, StoreTy);
2221
2222 / Expand to the memory bit width.
2223 unsigned MemNumElems = StoreTy->getPrimitiveSizeInBits();
2224 / <N x i1> --> <P x i1>.
2225 Value = emitBoolVecConversion(Value, MemNumElems, "insertvec");
2226 / <P x i1> --> iP.
2227 Value = Builder.CreateBitCast(Value, StoreTy);
2228 }
2229
2230 if (Ty->hasBooleanRepresentation() || Ty->isBitIntType()) {
2231 llvm::Type *StoreTy = convertTypeForLoadStore(Ty, Value->getType());
2233 return Builder.CreateIntCast(Value, StoreTy, Signed, "storedv");
2234 }
2235
2236 return Value;
2237}
2238
2239/ Converts a scalar value from its load/store type (as returned
2240/ by convertTypeForLoadStore) to its primary IR type (as returned
2241/ by ConvertType).
2242llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
2243 if (auto *AtomicTy = Ty->getAs<AtomicType>())
2244 Ty = AtomicTy->getValueType();
2245
2247 const auto *RawIntTy = Value->getType();
2248
2249 / Bitcast iP --> <P x i1>.
2250 auto *PaddedVecTy = llvm::FixedVectorType::get(
2251 Builder.getInt1Ty(), RawIntTy->getPrimitiveSizeInBits());
2252 auto *V = Builder.CreateBitCast(Value, PaddedVecTy);
2253 / Shuffle <P x i1> --> <N x i1> (N is the actual bit size).
2254 llvm::Type *ValTy = ConvertType(Ty);
2255 unsigned ValNumElems = cast<llvm::FixedVectorType>(ValTy)->getNumElements();
2256 return emitBoolVecConversion(V, ValNumElems, "extractvec");
2257 }
2258
2259 llvm::Type *ResTy = ConvertType(Ty);
2260 if (Ty->hasBooleanRepresentation() || Ty->isBitIntType() ||
2261 Ty->isExtVectorBoolType())
2262 return Builder.CreateTrunc(Value, ResTy, "loadedv");
2263
2264 return Value;
2265}
2266
2267/ Convert the pointer of \p Addr to a pointer to a vector (the value type of
2268/ MatrixType), if it points to a array (the memory type of MatrixType).
2270 CodeGenFunction &CGF,
2271 bool IsVector = true) {
2272 auto *ArrayTy = dyn_cast<llvm::ArrayType>(Addr.getElementType());
2273 if (ArrayTy && IsVector) {
2274 auto *VectorTy = llvm::FixedVectorType::get(ArrayTy->getElementType(),
2275 ArrayTy->getNumElements());
2276
2277 return Addr.withElementType(VectorTy);
2278 }
2279 auto *VectorTy = dyn_cast<llvm::VectorType>(Addr.getElementType());
2280 if (VectorTy && !IsVector) {
2281 auto *ArrayTy = llvm::ArrayType::get(
2282 VectorTy->getElementType(),
2283 cast<llvm::FixedVectorType>(VectorTy)->getNumElements());
2284
2285 return Addr.withElementType(ArrayTy);
2286 }
2287
2288 return Addr;
2289}
2290
2291/ Emit a store of a matrix LValue. This may require casting the original
2292/ pointer to memory address (ArrayType) to a pointer to the value type
2293/ (VectorType).
2294static void EmitStoreOfMatrixScalar(llvm::Value *value, LValue lvalue,
2295 bool isInit, CodeGenFunction &CGF) {
2296 Address Addr = MaybeConvertMatrixAddress(lvalue.getAddress(), CGF,
2297 value->getType()->isVectorTy());
2298 CGF.EmitStoreOfScalar(value, Addr, lvalue.isVolatile(), lvalue.getType(),
2299 lvalue.getBaseInfo(), lvalue.getTBAAInfo(), isInit,
2300 lvalue.isNontemporal());
2301}
2302
2304 bool Volatile, QualType Ty,
2305 LValueBaseInfo BaseInfo,
2306 TBAAAccessInfo TBAAInfo,
2307 bool isInit, bool isNontemporal) {
2308 if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr.getBasePointer()))
2309 if (GV->isThreadLocal())
2310 Addr = Addr.withPointer(Builder.CreateThreadLocalAddress(GV),
2312
2313 / Handles vectors of sizes that are likely to be expanded to a larger size
2314 / to optimize performance.
2315 llvm::Type *SrcTy = Value->getType();
2316 if (const auto *ClangVecTy = Ty->getAs<VectorType>()) {
2317 if (auto *VecTy = dyn_cast<llvm::FixedVectorType>(SrcTy)) {
2318 auto *NewVecTy =
2319 CGM.getABIInfo().getOptimalVectorMemoryType(VecTy, getLangOpts());
2320 if (!ClangVecTy->isPackedVectorBoolType(getContext()) &&
2321 VecTy != NewVecTy) {
2322 SmallVector<int, 16> Mask(NewVecTy->getNumElements(),
2323 VecTy->getNumElements());
2324 std::iota(Mask.begin(), Mask.begin() + VecTy->getNumElements(), 0);
2325 / Use undef instead of poison for the padding lanes, to make sure no
2326 / padding bits are poisoned, which may break coercion.
2327 Value = Builder.CreateShuffleVector(Value, llvm::UndefValue::get(VecTy),
2328 Mask, "extractVec");
2329 SrcTy = NewVecTy;
2330 }
2331 if (Addr.getElementType() != SrcTy)
2332 Addr = Addr.withElementType(SrcTy);
2333 }
2334 }
2335
2336 Value = EmitToMemory(Value, Ty);
2337
2338 LValue AtomicLValue =
2339 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
2340 if (Ty->isAtomicType() ||
2341 (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
2342 EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
2343 return;
2344 }
2345
2346 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
2348
2349 if (isNontemporal) {
2350 llvm::MDNode *Node =
2351 llvm::MDNode::get(Store->getContext(),
2352 llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
2353 Store->setMetadata(llvm::LLVMContext::MD_nontemporal, Node);
2354 }
2355
2356 CGM.DecorateInstructionWithTBAA(Store, TBAAInfo);
2357}
2358
2359void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
2360 bool isInit) {
2361 if (lvalue.getType()->isConstantMatrixType()) {
2362 EmitStoreOfMatrixScalar(value, lvalue, isInit, *this);
2363 return;
2364 }
2365
2366 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
2367 lvalue.getType(), lvalue.getBaseInfo(),
2368 lvalue.getTBAAInfo(), isInit, lvalue.isNontemporal());
2369}
2370
2371/ Emit a load of a LValue of matrix type. This may require casting the pointer
2372/ to memory address (ArrayType) to a pointer to the value type (VectorType).
2374 CodeGenFunction &CGF) {
2375 assert(LV.getType()->isConstantMatrixType());
2376 Address Addr = MaybeConvertMatrixAddress(LV.getAddress(), CGF);
2377 LV.setAddress(Addr);
2378 return RValue::get(CGF.EmitLoadOfScalar(LV, Loc));
2379}
2380
2382 SourceLocation Loc) {
2383 QualType Ty = LV.getType();
2384 switch (getEvaluationKind(Ty)) {
2385 case TEK_Scalar:
2386 return EmitLoadOfLValue(LV, Loc);
2387 case TEK_Complex:
2388 return RValue::getComplex(EmitLoadOfComplex(LV, Loc));
2389 case TEK_Aggregate:
2390 EmitAggFinalDestCopy(Ty, Slot, LV, EVK_NonRValue);
2391 return Slot.asRValue();
2392 }
2393 llvm_unreachable("bad evaluation kind");
2394}
2395
2396/ EmitLoadOfLValue - Given an expression that represents a value lvalue, this
2397/ method emits the address of the lvalue, then loads the result as an rvalue,
2398/ returning the rvalue.
2400 / Load from __ptrauth.
2401 if (PointerAuthQualifier PtrAuth = LV.getQuals().getPointerAuth()) {
2403 llvm::Value *Value = EmitLoadOfLValue(LV, Loc).getScalarVal();
2404 return RValue::get(EmitPointerAuthUnqualify(PtrAuth, Value, LV.getType(),
2405 LV.getAddress(),
2406 /*known nonnull*/ false));
2407 }
2408
2409 if (LV.isObjCWeak()) {
2410 / load of a __weak object.
2411 Address AddrWeakObj = LV.getAddress();
2412 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
2413 AddrWeakObj));
2414 }
2416 / In MRC mode, we do a load+autorelease.
2417 if (!getLangOpts().ObjCAutoRefCount) {
2419 }
2420
2421 / In ARC mode, we load retained and then consume the value.
2422 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
2423 Object = EmitObjCConsumeObject(LV.getType(), Object);
2424 return RValue::get(Object);
2425 }
2426
2427 if (LV.isSimple()) {
2428 assert(!LV.getType()->isFunctionType());
2429
2430 if (LV.getType()->isConstantMatrixType())
2431 return EmitLoadOfMatrixLValue(LV, Loc, *this);
2432
2433 / Everything needs a load.
2434 return RValue::get(EmitLoadOfScalar(LV, Loc));
2435 }
2436
2437 if (LV.isVectorElt()) {
2438 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
2439 LV.isVolatileQualified());
2440 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
2441 "vecext"));
2442 }
2443
2444 / If this is a reference to a subset of the elements of a vector, either
2445 / shuffle the input or extract/insert them as appropriate.
2446 if (LV.isExtVectorElt()) {
2448 }
2449
2450 / Global Register variables always invoke intrinsics
2451 if (LV.isGlobalReg())
2452 return EmitLoadOfGlobalRegLValue(LV);
2453
2454 if (LV.isMatrixElt()) {
2455 llvm::Value *Idx = LV.getMatrixIdx();
2456 if (CGM.getCodeGenOpts().OptimizationLevel > 0) {
2457 const auto *const MatTy = LV.getType()->castAs<ConstantMatrixType>();
2458 llvm::MatrixBuilder MB(Builder);
2459 MB.CreateIndexAssumption(Idx, MatTy->getNumElementsFlattened());
2460 }
2461 llvm::LoadInst *Load =
2462 Builder.CreateLoad(LV.getMatrixAddress(), LV.isVolatileQualified());
2463 return RValue::get(Builder.CreateExtractElement(Load, Idx, "matrixext"));
2464 }
2465
2466 assert(LV.isBitField() && "Unknown LValue type!");
2467 return EmitLoadOfBitfieldLValue(LV, Loc);
2468}
2469
2471 SourceLocation Loc) {
2472 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
2473
2474 / Get the output type.
2475 llvm::Type *ResLTy = ConvertType(LV.getType());
2476
2477 Address Ptr = LV.getBitFieldAddress();
2478 llvm::Value *Val =
2479 Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
2480
2481 bool UseVolatile = LV.isVolatileQualified() &&
2482 Info.VolatileStorageSize != 0 && isAAPCS(CGM.getTarget());
2483 const unsigned Offset = UseVolatile ? Info.VolatileOffset : Info.Offset;
2484 const unsigned StorageSize =
2485 UseVolatile ? Info.VolatileStorageSize : Info.StorageSize;
2486 if (Info.IsSigned) {
2487 assert(static_cast<unsigned>(Offset + Info.Size) <= StorageSize);
2488 unsigned HighBits = StorageSize - Offset - Info.Size;
2489 if (HighBits)
2490 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
2491 if (Offset + HighBits)
2492 Val = Builder.CreateAShr(Val, Offset + HighBits, "bf.ashr");
2493 } else {
2494 if (Offset)
2495 Val = Builder.CreateLShr(Val, Offset, "bf.lshr");
2496 if (static_cast<unsigned>(Offset) + Info.Size < StorageSize)
2497 Val = Builder.CreateAnd(
2498 Val, llvm::APInt::getLowBitsSet(StorageSize, Info.Size), "bf.clear");
2499 }
2500 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
2501 EmitScalarRangeCheck(Val, LV.getType(), Loc);
2502 return RValue::get(Val);
2503}
2504
2505/ If this is a reference to a subset of the elements of a vector, create an
2506/ appropriate shufflevector.
2508 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
2509 LV.isVolatileQualified());
2510
2511 / HLSL allows treating scalars as one-element vectors. Converting the scalar
2512 / IR value to a vector here allows the rest of codegen to behave as normal.
2513 if (getLangOpts().HLSL && !Vec->getType()->isVectorTy()) {
2514 llvm::Type *DstTy = llvm::FixedVectorType::get(Vec->getType(), 1);
2515 llvm::Value *Zero = llvm::Constant::getNullValue(CGM.Int64Ty);
2516 Vec = Builder.CreateInsertElement(DstTy, Vec, Zero, "cast.splat");
2517 }
2518
2519 const llvm::Constant *Elts = LV.getExtVectorElts();
2520
2521 / If the result of the expression is a non-vector type, we must be extracting
2522 / a single element. Just codegen as an extractelement.
2523 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
2524 if (!ExprVT) {
2525 unsigned InIdx = getAccessedFieldNo(0, Elts);
2526 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
2527
2528 llvm::Value *Element = Builder.CreateExtractElement(Vec, Elt);
2529
2530 llvm::Type *LVTy = ConvertType(LV.getType());
2531 if (Element->getType()->getPrimitiveSizeInBits() >
2532 LVTy->getPrimitiveSizeInBits())
2533 Element = Builder.CreateTrunc(Element, LVTy);
2534
2535 return RValue::get(Element);
2536 }
2537
2538 / Always use shuffle vector to try to retain the original program structure
2539 unsigned NumResultElts = ExprVT->getNumElements();
2540
2542 for (unsigned i = 0; i != NumResultElts; ++i)
2543 Mask.push_back(getAccessedFieldNo(i, Elts));
2544
2545 Vec = Builder.CreateShuffleVector(Vec, Mask);
2546
2547 if (LV.getType()->isExtVectorBoolType())
2548 Vec = Builder.CreateTrunc(Vec, ConvertType(LV.getType()), "truncv");
2549
2550 return RValue::get(Vec);
2551}
2552
2553/ Generates lvalue for partial ext_vector access.
2555 Address VectorAddress = LV.getExtVectorAddress();
2556 QualType EQT = LV.getType()->castAs<VectorType>()->getElementType();
2557 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
2558
2559 Address CastToPointerElement = VectorAddress.withElementType(VectorElementTy);
2560
2561 const llvm::Constant *Elts = LV.getExtVectorElts();
2562 unsigned ix = getAccessedFieldNo(0, Elts);
2563
2564 Address VectorBasePtrPlusIx =
2565 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
2566 "vector.elt");
2567
2568 return VectorBasePtrPlusIx;
2569}
2570
2571/ Load of global named registers are always calls to intrinsics.
2573 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
2574 "Bad type for register variable");
2575 llvm::MDNode *RegName = cast<llvm::MDNode>(
2576 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
2577
2578 / We accept integer and pointer types only
2579 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
2580 llvm::Type *Ty = OrigTy;
2581 if (OrigTy->isPointerTy())
2582 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
2583 llvm::Type *Types[] = { Ty };
2584
2585 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
2586 llvm::Value *Call = Builder.CreateCall(
2587 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
2588 if (OrigTy->isPointerTy())
2589 Call = Builder.CreateIntToPtr(Call, OrigTy);
2590 return RValue::get(Call);
2591}
2592
2593/ EmitStoreThroughLValue - Store the specified rvalue into the specified
2594/ lvalue, where both are guaranteed to the have the same type, and that type
2595/ is 'Ty'.
2597 bool isInit) {
2598 if (!Dst.isSimple()) {
2599 if (Dst.isVectorElt()) {
2600 if (getLangOpts().HLSL) {
2601 / HLSL allows direct access to vector elements, so storing to
2602 / individual elements of a vector through VectorElt is handled as
2603 / separate store instructions.
2604 Address DstAddr = Dst.getVectorAddress();
2605 llvm::Type *DestAddrTy = DstAddr.getElementType();
2606 llvm::Type *ElemTy = DestAddrTy->getScalarType();
2608 CGM.getDataLayout().getPrefTypeAlign(ElemTy));
2609
2610 assert(ElemTy->getScalarSizeInBits() >= 8 &&
2611 "vector element type must be at least byte-sized");
2612
2613 llvm::Value *Val = Src.getScalarVal();
2614 if (Val->getType()->getPrimitiveSizeInBits() <
2615 ElemTy->getScalarSizeInBits())
2616 Val = Builder.CreateZExt(Val, ElemTy->getScalarType());
2617
2618 llvm::Value *Idx = Dst.getVectorIdx();
2619 llvm::Value *Zero = llvm::ConstantInt::get(Int32Ty, 0);
2620 Address DstElemAddr =
2621 Builder.CreateGEP(DstAddr, {Zero, Idx}, DestAddrTy, ElemAlign);
2622 Builder.CreateStore(Val, DstElemAddr, Dst.isVolatileQualified());
2623 return;
2624 }
2625
2626 / Read/modify/write the vector, inserting the new element.
2627 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
2628 Dst.isVolatileQualified());
2629 llvm::Type *VecTy = Vec->getType();
2630 llvm::Value *SrcVal = Src.getScalarVal();
2631
2632 if (SrcVal->getType()->getPrimitiveSizeInBits() <
2633 VecTy->getScalarSizeInBits())
2634 SrcVal = Builder.CreateZExt(SrcVal, VecTy->getScalarType());
2635
2636 auto *IRStoreTy = dyn_cast<llvm::IntegerType>(Vec->getType());
2637 if (IRStoreTy) {
2638 auto *IRVecTy = llvm::FixedVectorType::get(
2639 Builder.getInt1Ty(), IRStoreTy->getPrimitiveSizeInBits());
2640 Vec = Builder.CreateBitCast(Vec, IRVecTy);
2641 / iN --> <N x i1>.
2642 }
2643
2644 / Allow inserting `<1 x T>` into an `<N x T>`. It can happen with scalar
2645 / types which are mapped to vector LLVM IR types (e.g. for implementing
2646 / an ABI).
2647 if (auto *EltTy = dyn_cast<llvm::FixedVectorType>(SrcVal->getType());
2648 EltTy && EltTy->getNumElements() == 1)
2649 SrcVal = Builder.CreateBitCast(SrcVal, EltTy->getElementType());
2650
2651 Vec = Builder.CreateInsertElement(Vec, SrcVal, Dst.getVectorIdx(),
2652 "vecins");
2653 if (IRStoreTy) {
2654 / <N x i1> --> <iN>.
2655 Vec = Builder.CreateBitCast(Vec, IRStoreTy);
2656 }
2657
2658 auto *I = Builder.CreateStore(Vec, Dst.getVectorAddress(),
2659 Dst.isVolatileQualified());
2661 return;
2662 }
2663
2664 / If this is an update of extended vector elements, insert them as
2665 / appropriate.
2666 if (Dst.isExtVectorElt())
2668
2669 if (Dst.isGlobalReg())
2670 return EmitStoreThroughGlobalRegLValue(Src, Dst);
2671
2672 if (Dst.isMatrixElt()) {
2673 llvm::Value *Idx = Dst.getMatrixIdx();
2674 if (CGM.getCodeGenOpts().OptimizationLevel > 0) {
2675 const auto *const MatTy = Dst.getType()->castAs<ConstantMatrixType>();
2676 llvm::MatrixBuilder MB(Builder);
2677 MB.CreateIndexAssumption(Idx, MatTy->getNumElementsFlattened());
2678 }
2679 llvm::Instruction *Load = Builder.CreateLoad(Dst.getMatrixAddress());
2680 llvm::Value *Vec =
2681 Builder.CreateInsertElement(Load, Src.getScalarVal(), Idx, "matins");
2682 auto *I = Builder.CreateStore(Vec, Dst.getMatrixAddress(),
2683 Dst.isVolatileQualified());
2685 return;
2686 }
2687
2688 assert(Dst.isBitField() && "Unknown LValue type");
2689 return EmitStoreThroughBitfieldLValue(Src, Dst);
2690 }
2691
2692 / Handle __ptrauth qualification by re-signing the value.
2693 if (PointerAuthQualifier PointerAuth = Dst.getQuals().getPointerAuth()) {
2694 Src = RValue::get(EmitPointerAuthQualify(PointerAuth, Src.getScalarVal(),
2695 Dst.getType(), Dst.getAddress(),
2696 /*known nonnull*/ false));
2697 }
2698
2699 / There's special magic for assigning into an ARC-qualified l-value.
2700 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
2701 switch (Lifetime) {
2703 llvm_unreachable("present but none");
2704
2706 / nothing special
2707 break;
2708
2710 if (isInit) {
2711 Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal()));
2712 break;
2713 }
2714 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
2715 return;
2716
2718 if (isInit)
2719 / Initialize and then skip the primitive store.
2721 else
2723 /*ignore*/ true);
2724 return;
2725
2728 Src.getScalarVal()));
2729 / fall into the normal path
2730 break;
2731 }
2732 }
2733
2734 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
2735 / load of a __weak object.
2736 Address LvalueDst = Dst.getAddress();
2737 llvm::Value *src = Src.getScalarVal();
2738 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
2739 return;
2740 }
2741
2742 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
2743 / load of a __strong object.
2744 Address LvalueDst = Dst.getAddress();
2745 llvm::Value *src = Src.getScalarVal();
2746 if (Dst.isObjCIvar()) {
2747 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
2748 llvm::Type *ResultType = IntPtrTy;
2750 llvm::Value *RHS = dst.emitRawPointer(*this);
2751 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
2752 llvm::Value *LHS = Builder.CreatePtrToInt(LvalueDst.emitRawPointer(*this),
2753 ResultType, "sub.ptr.lhs.cast");
2754 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
2755 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst, BytesBetween);
2756 } else if (Dst.isGlobalObjCRef()) {
2757 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
2758 Dst.isThreadLocalRef());
2759 }
2760 else
2761 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
2762 return;
2763 }
2764
2765 assert(Src.isScalar() && "Can't emit an agg store with this method");
2766 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
2767}
2768
2770 llvm::Value **Result) {
2771 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
2772 llvm::Type *ResLTy = convertTypeForLoadStore(Dst.getType());
2773 Address Ptr = Dst.getBitFieldAddress();
2774
2775 / Get the source value, truncated to the width of the bit-field.
2776 llvm::Value *SrcVal = Src.getScalarVal();
2777
2778 / Cast the source to the storage type and shift it into place.
2779 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
2780 /*isSigned=*/false);
2781 llvm::Value *MaskedVal = SrcVal;
2782
2783 const bool UseVolatile =
2784 CGM.getCodeGenOpts().AAPCSBitfieldWidth && Dst.isVolatileQualified() &&
2785 Info.VolatileStorageSize != 0 && isAAPCS(CGM.getTarget());
2786 const unsigned StorageSize =
2787 UseVolatile ? Info.VolatileStorageSize : Info.StorageSize;
2788 const unsigned Offset = UseVolatile ? Info.VolatileOffset : Info.Offset;
2789 / See if there are other bits in the bitfield's storage we'll need to load
2790 / and mask together with source before storing.
2791 if (StorageSize != Info.Size) {
2792 assert(StorageSize > Info.Size && "Invalid bitfield size.");
2793 llvm::Value *Val =
2794 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
2795
2796 / Mask the source value as needed.
2797 if (!Dst.getType()->hasBooleanRepresentation())
2798 SrcVal = Builder.CreateAnd(
2799 SrcVal, llvm::APInt::getLowBitsSet(StorageSize, Info.Size),
2800 "bf.value");
2801 MaskedVal = SrcVal;
2802 if (Offset)
2803 SrcVal = Builder.CreateShl(SrcVal, Offset, "bf.shl");
2804
2805 / Mask out the original value.
2806 Val = Builder.CreateAnd(
2807 Val, ~llvm::APInt::getBitsSet(StorageSize, Offset, Offset + Info.Size),
2808 "bf.clear");
2809
2810 / Or together the unchanged values and the source value.
2811 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
2812 } else {
2813 assert(Offset == 0);
2814 / According to the AACPS:
2815 / When a volatile bit-field is written, and its container does not overlap
2816 / with any non-bit-field member, its container must be read exactly once
2817 / and written exactly once using the access width appropriate to the type
2818 / of the container. The two accesses are not atomic.
2819 if (Dst.isVolatileQualified() && isAAPCS(CGM.getTarget()) &&
2820 CGM.getCodeGenOpts().ForceAAPCSBitfieldLoad)
2821 Builder.CreateLoad(Ptr, true, "bf.load");
2822 }
2823
2824 / Write the new value back out.
2825 auto *I = Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
2826 addInstToCurrentSourceAtom(I, SrcVal);
2827
2828 / Return the new value of the bit-field, if requested.
2829 if (Result) {
2830 llvm::Value *ResultVal = MaskedVal;
2831
2832 / Sign extend the value if needed.
2833 if (Info.IsSigned) {
2834 assert(Info.Size <= StorageSize);
2835 unsigned HighBits = StorageSize - Info.Size;
2836 if (HighBits) {
2837 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
2838 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
2839 }
2840 }
2841
2842 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
2843 "bf.result.cast");
2844 *Result = EmitFromMemory(ResultVal, Dst.getType());
2845 }
2846}
2847
2849 LValue Dst) {
2850 llvm::Value *SrcVal = Src.getScalarVal();
2851 Address DstAddr = Dst.getExtVectorAddress();
2852 const llvm::Constant *Elts = Dst.getExtVectorElts();
2853 if (DstAddr.getElementType()->getScalarSizeInBits() >
2854 SrcVal->getType()->getScalarSizeInBits())
2855 SrcVal = Builder.CreateZExt(
2856 SrcVal, convertTypeForLoadStore(Dst.getType(), SrcVal->getType()));
2857
2858 if (getLangOpts().HLSL) {
2859 llvm::Type *DestAddrTy = DstAddr.getElementType();
2860 / HLSL allows storing to scalar values through ExtVector component LValues.
2861 / To support this we need to handle the case where the destination address
2862 / is a scalar.
2863 if (!DestAddrTy->isVectorTy()) {
2864 assert(!Dst.getType()->isVectorType() &&
2865 "this should only occur for non-vector l-values");
2866 Builder.CreateStore(SrcVal, DstAddr, Dst.isVolatileQualified());
2867 return;
2868 }
2869
2870 / HLSL allows direct access to vector elements, so storing to individual
2871 / elements of a vector through ExtVector is handled as separate store
2872 / instructions.
2873 / If we are updating multiple elements, Dst and Src are vectors; for
2874 / a single element update they are scalars.
2875 const VectorType *VTy = Dst.getType()->getAs<VectorType>();
2876 unsigned NumSrcElts = VTy ? VTy->getNumElements() : 1;
2878 CGM.getDataLayout().getPrefTypeAlign(DestAddrTy->getScalarType()));
2879 llvm::Value *Zero = llvm::ConstantInt::get(Int32Ty, 0);
2880
2881 for (unsigned I = 0; I != NumSrcElts; ++I) {
2882 llvm::Value *Val = VTy ? Builder.CreateExtractElement(
2883 SrcVal, llvm::ConstantInt::get(Int32Ty, I))
2884 : SrcVal;
2885 unsigned FieldNo = getAccessedFieldNo(I, Elts);
2886 Address DstElemAddr = Address::invalid();
2887 if (FieldNo == 0)
2888 DstElemAddr = DstAddr.withAlignment(ElemAlign);
2889 else
2890 DstElemAddr = Builder.CreateGEP(
2891 DstAddr, {Zero, llvm::ConstantInt::get(Int32Ty, FieldNo)},
2892 DestAddrTy, ElemAlign);
2893 Builder.CreateStore(Val, DstElemAddr, Dst.isVolatileQualified());
2894 }
2895 return;
2896 }
2897
2898 / This access turns into a read/modify/write of the vector. Load the input
2899 / value now.
2900 llvm::Value *Vec = Builder.CreateLoad(DstAddr, Dst.isVolatileQualified());
2901 llvm::Type *VecTy = Vec->getType();
2902
2903 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
2904 unsigned NumSrcElts = VTy->getNumElements();
2905 unsigned NumDstElts = cast<llvm::FixedVectorType>(VecTy)->getNumElements();
2906 if (NumDstElts == NumSrcElts) {
2907 / Use shuffle vector is the src and destination are the same number of
2908 / elements and restore the vector mask since it is on the side it will be
2909 / stored.
2910 SmallVector<int, 4> Mask(NumDstElts);
2911 for (unsigned i = 0; i != NumSrcElts; ++i)
2912 Mask[getAccessedFieldNo(i, Elts)] = i;
2913
2914 Vec = Builder.CreateShuffleVector(SrcVal, Mask);
2915 } else if (NumDstElts > NumSrcElts) {
2916 / Extended the source vector to the same length and then shuffle it
2917 / into the destination.
2918 / FIXME: since we're shuffling with undef, can we just use the indices
2919 / into that? This could be simpler.
2920 SmallVector<int, 4> ExtMask;
2921 for (unsigned i = 0; i != NumSrcElts; ++i)
2922 ExtMask.push_back(i);
2923 ExtMask.resize(NumDstElts, -1);
2924 llvm::Value *ExtSrcVal = Builder.CreateShuffleVector(SrcVal, ExtMask);
2925 / build identity
2927 for (unsigned i = 0; i != NumDstElts; ++i)
2928 Mask.push_back(i);
2929
2930 / When the vector size is odd and .odd or .hi is used, the last element
2931 / of the Elts constant array will be one past the size of the vector.
2932 / Ignore the last element here, if it is greater than the mask size.
2933 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
2934 NumSrcElts--;
2935
2936 / modify when what gets shuffled in
2937 for (unsigned i = 0; i != NumSrcElts; ++i)
2938 Mask[getAccessedFieldNo(i, Elts)] = i + NumDstElts;
2939 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, Mask);
2940 } else {
2941 / We should never shorten the vector
2942 llvm_unreachable("unexpected shorten vector length");
2943 }
2944 } else {
2945 / If the Src is a scalar (not a vector), and the target is a vector it must
2946 / be updating one element.
2947 unsigned InIdx = getAccessedFieldNo(0, Elts);
2948 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
2949
2950 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
2951 }
2952
2953 Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
2954 Dst.isVolatileQualified());
2955}
2956
2957/ Store of global named registers are always calls to intrinsics.
2959 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
2960 "Bad type for register variable");
2961 llvm::MDNode *RegName = cast<llvm::MDNode>(
2962 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
2963 assert(RegName && "Register LValue is not metadata");
2964
2965 / We accept integer and pointer types only
2966 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
2967 llvm::Type *Ty = OrigTy;
2968 if (OrigTy->isPointerTy())
2969 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
2970 llvm::Type *Types[] = { Ty };
2971
2972 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
2973 llvm::Value *Value = Src.getScalarVal();
2974 if (OrigTy->isPointerTy())
2975 Value = Builder.CreatePtrToInt(Value, Ty);
2976 Builder.CreateCall(
2977 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
2978}
2979
2980/ setObjCGCLValueClass - sets class of the lvalue for the purpose of
2981/ generating write-barries API. It is currently a global, ivar,
2982/ or neither.
2983static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
2984 LValue &LV,
2985 bool IsMemberAccess=false) {
2986 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
2987 return;
2988
2989 if (isa<ObjCIvarRefExpr>(E)) {
2990 QualType ExpTy = E->getType();
2991 if (IsMemberAccess && ExpTy->isPointerType()) {
2992 / If ivar is a structure pointer, assigning to field of
2993 / this struct follows gcc's behavior and makes it a non-ivar
2994 / writer-barrier conservatively.
2995 ExpTy = ExpTy->castAs<PointerType>()->getPointeeType();
2996 if (ExpTy->isRecordType()) {
2997 LV.setObjCIvar(false);
2998 return;
2999 }
3000 }
3001 LV.setObjCIvar(true);
3002 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
3003 LV.setBaseIvarExp(Exp->getBase());
3004 LV.setObjCArray(E->getType()->isArrayType());
3005 return;
3006 }
3007
3008 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
3009 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
3010 if (VD->hasGlobalStorage()) {
3011 LV.setGlobalObjCRef(true);
3012 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
3013 }
3014 }
3015 LV.setObjCArray(E->getType()->isArrayType());
3016 return;
3017 }
3018
3019 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
3020 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
3021 return;
3022 }
3023
3024 if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
3025 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
3026 if (LV.isObjCIvar()) {
3027 / If cast is to a structure pointer, follow gcc's behavior and make it
3028 / a non-ivar write-barrier.
3029 QualType ExpTy = E->getType();
3030 if (ExpTy->isPointerType())
3031 ExpTy = ExpTy->castAs<PointerType>()->getPointeeType();
3032 if (ExpTy->isRecordType())
3033 LV.setObjCIvar(false);
3034 }
3035 return;
3036 }
3037
3038 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
3039 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
3040 return;
3041 }
3042
3043 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
3044 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
3045 return;
3046 }
3047
3048 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
3049 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
3050 return;
3051 }
3052
3053 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
3054 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
3055 return;
3056 }
3057
3058 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
3059 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
3060 if (LV.isObjCIvar() && !LV.isObjCArray())
3061 / Using array syntax to assigning to what an ivar points to is not
3062 / same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
3063 LV.setObjCIvar(false);
3064 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
3065 / Using array syntax to assigning to what global points to is not
3066 / same as assigning to the global itself. {id *G;} G[i] = 0;
3067 LV.setGlobalObjCRef(false);
3068 return;
3069 }
3070
3071 if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
3072 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
3073 / We don't know if member is an 'ivar', but this flag is looked at
3074 / only in the context of LV.isObjCIvar().
3075 LV.setObjCArray(E->getType()->isArrayType());
3076 return;
3077 }
3078}
3079
3081 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
3082 llvm::Type *RealVarTy, SourceLocation Loc) {
3083 if (CGF.CGM.getLangOpts().OpenMPIRBuilder)
3085 CGF, VD, Addr, Loc);
3086 else
3087 Addr =
3088 CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
3089
3090 Addr = Addr.withElementType(RealVarTy);
3092}
3093
3095 const VarDecl *VD, QualType T) {
3096 std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
3097 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
3098 / Return an invalid address if variable is MT_To (or MT_Enter starting with
3099 / OpenMP 5.2) and unified memory is not enabled. For all other cases: MT_Link
3100 / and MT_To (or MT_Enter) with unified memory, return a valid address.
3101 if (!Res || ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3102 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
3104 return Address::invalid();
3105 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
3106 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3107 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
3109 "Expected link clause OR to clause with unified memory enabled.");
3110 QualType PtrTy = CGF.getContext().getPointerType(VD->getType());
3112 return CGF.EmitLoadOfPointer(Addr, PtrTy->castAs<PointerType>());
3113}
3114
3115Address
3117 LValueBaseInfo *PointeeBaseInfo,
3118 TBAAAccessInfo *PointeeTBAAInfo) {
3119 llvm::LoadInst *Load =
3120 Builder.CreateLoad(RefLVal.getAddress(), RefLVal.isVolatile());
3121 CGM.DecorateInstructionWithTBAA(Load, RefLVal.getTBAAInfo());
3122 QualType PTy = RefLVal.getType()->getPointeeType();
3123 CharUnits Align = CGM.getNaturalTypeAlignment(
3124 PTy, PointeeBaseInfo, PointeeTBAAInfo, /*ForPointeeType=*/true);
3125 if (!PTy->isIncompleteType()) {
3126 llvm::LLVMContext &Ctx = getLLVMContext();
3127 llvm::MDBuilder MDB(Ctx);
3128 / Emit !nonnull metadata
3129 if (CGM.getTypes().getTargetAddressSpace(PTy) == 0 &&
3130 !CGM.getCodeGenOpts().NullPointerIsValid)
3131 Load->setMetadata(llvm::LLVMContext::MD_nonnull,
3132 llvm::MDNode::get(Ctx, {}));
3133 / Emit !align metadata
3134 if (PTy->isObjectType()) {
3135 auto AlignVal = Align.getQuantity();
3136 if (AlignVal > 1) {
3137 Load->setMetadata(
3138 llvm::LLVMContext::MD_align,
3139 llvm::MDNode::get(Ctx, MDB.createConstant(llvm::ConstantInt::get(
3140 Builder.getInt64Ty(), AlignVal))));
3141 }
3142 }
3143 }
3144 return makeNaturalAddressForPointer(Load, PTy, Align,
3145 /*ForPointeeType=*/true, PointeeBaseInfo,
3146 PointeeTBAAInfo);
3147}
3148
3150 LValueBaseInfo PointeeBaseInfo;
3151 TBAAAccessInfo PointeeTBAAInfo;
3152 Address PointeeAddr = EmitLoadOfReference(RefLVal, &PointeeBaseInfo,
3153 &PointeeTBAAInfo);
3154 return MakeAddrLValue(PointeeAddr, RefLVal.getType()->getPointeeType(),
3155 PointeeBaseInfo, PointeeTBAAInfo);
3156}
3157
3159 const PointerType *PtrTy,
3160 LValueBaseInfo *BaseInfo,
3161 TBAAAccessInfo *TBAAInfo) {
3162 llvm::Value *Addr = Builder.CreateLoad(Ptr);
3163 return makeNaturalAddressForPointer(Addr, PtrTy->getPointeeType(),
3164 CharUnits(), /*ForPointeeType=*/true,
3165 BaseInfo, TBAAInfo);
3166}
3167
3169 const PointerType *PtrTy) {
3170 LValueBaseInfo BaseInfo;
3171 TBAAAccessInfo TBAAInfo;
3172 Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &BaseInfo, &TBAAInfo);
3173 return MakeAddrLValue(Addr, PtrTy->getPointeeType(), BaseInfo, TBAAInfo);
3174}
3175
3177 const Expr *E, const VarDecl *VD) {
3178 QualType T = E->getType();
3179
3180 / If it's thread_local, emit a call to its wrapper function instead.
3181 if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
3183 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
3184 / Check if the variable is marked as declare target with link clause in
3185 / device codegen.
3186 if (CGF.getLangOpts().OpenMPIsTargetDevice) {
3188 if (Addr.isValid())
3190 }
3191
3192 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
3193
3194 if (VD->getTLSKind() != VarDecl::TLS_None)
3195 V = CGF.Builder.CreateThreadLocalAddress(V);
3196
3197 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
3198 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
3199 Address Addr(V, RealVarTy, Alignment);
3200 / Emit reference to the private copy of the variable if it is an OpenMP
3201 / threadprivate variable.
3202 if (CGF.getLangOpts().OpenMP && !CGF.getLangOpts().OpenMPSimd &&
3203 VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
3204 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
3205 E->getExprLoc());
3206 }
3207 LValue LV = VD->getType()->isReferenceType() ?
3211 setObjCGCLValueClass(CGF.getContext(), E, LV);
3212 return LV;
3213}
3214
3216 llvm::Type *Ty) {
3217 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
3218 if (FD->hasAttr<WeakRefAttr>()) {
3220 return aliasee.getPointer();
3221 }
3222
3223 llvm::Constant *V = GetAddrOfFunction(GD, Ty);
3224 return V;
3225}
3226
3227static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF, const Expr *E,
3228 GlobalDecl GD) {
3229 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
3230 llvm::Constant *V = CGF.CGM.getFunctionPointer(GD);
3231 QualType ETy = E->getType();
3233 if (auto *GV = dyn_cast<llvm::GlobalValue>(V))
3234 V = llvm::NoCFIValue::get(GV);
3235 }
3236 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
3237 return CGF.MakeAddrLValue(V, ETy, Alignment, AlignmentSource::Decl);
3238}
3239
3241 llvm::Value *ThisValue) {
3242
3243 return CGF.EmitLValueForLambdaField(FD, ThisValue);
3244}
3245
3246/ Named Registers are named metadata pointing to the register name
3247/ which will be read from/written to as an argument to the intrinsic
3248/ @llvm.read/write_register.
3249/ So far, only the name is being passed down, but other options such as
3250/ register type, allocation type or even optimization options could be
3251/ passed down via the metadata node.
3252static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
3253 SmallString<64> Name("llvm.named.register.");
3254 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
3255 assert(Asm->getLabel().size() < 64-Name.size() &&
3256 "Register name too big");
3257 Name.append(Asm->getLabel());
3258 llvm::NamedMDNode *M =
3259 CGM.getModule().getOrInsertNamedMetadata(Name);
3260 if (M->getNumOperands() == 0) {
3261 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
3262 Asm->getLabel());
3263 llvm::Metadata *Ops[] = {Str};
3264 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
3265 }
3266
3267 CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
3268
3269 llvm::Value *Ptr =
3270 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
3271 return LValue::MakeGlobalReg(Ptr, Alignment, VD->getType());
3272}
3273
3274/ Determine whether we can emit a reference to \p VD from the current
3275/ context, despite not necessarily having seen an odr-use of the variable in
3276/ this context.
3278 const DeclRefExpr *E,
3279 const VarDecl *VD) {
3280 / For a variable declared in an enclosing scope, do not emit a spurious
3281 / reference even if we have a capture, as that will emit an unwarranted
3282 / reference to our capture state, and will likely generate worse code than
3283 / emitting a local copy.
3285 return false;
3286
3287 / For a local declaration declared in this function, we can always reference
3288 / it even if we don't have an odr-use.
3289 if (VD->hasLocalStorage()) {
3290 return VD->getDeclContext() ==
3291 dyn_cast_or_null<DeclContext>(CGF.CurCodeDecl);
3292 }
3293
3294 / For a global declaration, we can emit a reference to it if we know
3295 / for sure that we are able to emit a definition of it.
3296 VD = VD->getDefinition(CGF.getContext());
3297 if (!VD)
3298 return false;
3299
3300 / Don't emit a spurious reference if it might be to a variable that only
3301 / exists on a different device / target.
3302 / FIXME: This is unnecessarily broad. Check whether this would actually be a
3303 / cross-target reference.
3304 if (CGF.getLangOpts().OpenMP || CGF.getLangOpts().CUDA ||
3305 CGF.getLangOpts().OpenCL) {
3306 return false;
3307 }
3308
3309 / We can emit a spurious reference only if the linkage implies that we'll
3310 / be emitting a non-interposable symbol that will be retained until link
3311 / time.
3312 switch (CGF.CGM.getLLVMLinkageVarDefinition(VD)) {
3313 case llvm::GlobalValue::ExternalLinkage:
3314 case llvm::GlobalValue::LinkOnceODRLinkage:
3315 case llvm::GlobalValue::WeakODRLinkage:
3316 case llvm::GlobalValue::InternalLinkage:
3317 case llvm::GlobalValue::PrivateLinkage:
3318 return true;
3319 default:
3320 return false;
3321 }
3322}
3323
3325 const NamedDecl *ND = E->getDecl();
3326 QualType T = E->getType();
3327
3328 assert(E->isNonOdrUse() != NOUR_Unevaluated &&
3329 "should not emit an unevaluated operand");
3330
3331 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
3332 / Global Named registers access via intrinsics only
3333 if (VD->getStorageClass() == SC_Register &&
3334 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
3335 return EmitGlobalNamedRegister(VD, CGM);
3336
3337 / If this DeclRefExpr does not constitute an odr-use of the variable,
3338 / we're not permitted to emit a reference to it in general, and it might
3339 / not be captured if capture would be necessary for a use. Emit the
3340 / constant value directly instead.
3341 if (E->isNonOdrUse() == NOUR_Constant &&
3342 (VD->getType()->isReferenceType() ||
3343 !canEmitSpuriousReferenceToVariable(*this, E, VD))) {
3344 VD->getAnyInitializer(VD);
3345 llvm::Constant *Val = ConstantEmitter(*this).emitAbstract(
3346 E->getLocation(), *VD->evaluateValue(), VD->getType());
3347 assert(Val && "failed to emit constant expression");
3348
3350 if (!VD->getType()->isReferenceType()) {
3351 / Spill the constant value to a global.
3352 Addr = CGM.createUnnamedGlobalFrom(*VD, Val,
3353 getContext().getDeclAlign(VD));
3354 llvm::Type *VarTy = getTypes().ConvertTypeForMem(VD->getType());
3355 auto *PTy = llvm::PointerType::get(
3356 getLLVMContext(), getTypes().getTargetAddressSpace(VD->getType()));
3357 Addr = Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, PTy, VarTy);
3358 } else {
3359 / Should we be using the alignment of the constant pointer we emitted?
3360 CharUnits Alignment =
3361 CGM.getNaturalTypeAlignment(E->getType(),
3362 /* BaseInfo= */ nullptr,
3363 /* TBAAInfo= */ nullptr,
3364 /* forPointeeType= */ true);
3365 Addr = makeNaturalAddressForPointer(Val, T, Alignment);
3366 }
3368 }
3369
3370 / FIXME: Handle other kinds of non-odr-use DeclRefExprs.
3371
3372 / Check for captured variables.
3374 VD = VD->getCanonicalDecl();
3375 if (auto *FD = LambdaCaptureFields.lookup(VD))
3376 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
3377 if (CapturedStmtInfo) {
3378 auto I = LocalDeclMap.find(VD);
3379 if (I != LocalDeclMap.end()) {
3380 LValue CapLVal;
3381 if (VD->getType()->isReferenceType())
3382 CapLVal = EmitLoadOfReferenceLValue(I->second, VD->getType(),
3384 else
3385 CapLVal = MakeAddrLValue(I->second, T);
3386 / Mark lvalue as nontemporal if the variable is marked as nontemporal
3387 / in simd context.
3388 if (getLangOpts().OpenMP &&
3389 CGM.getOpenMPRuntime().isNontemporalDecl(VD))
3390 CapLVal.setNontemporal(/*Value=*/true);
3391 return CapLVal;
3392 }
3393 LValue CapLVal =
3394 EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
3395 CapturedStmtInfo->getContextValue());
3396 Address LValueAddress = CapLVal.getAddress();
3397 CapLVal = MakeAddrLValue(Address(LValueAddress.emitRawPointer(*this),
3398 LValueAddress.getElementType(),
3399 getContext().getDeclAlign(VD)),
3400 CapLVal.getType(),
3402 CapLVal.getTBAAInfo());
3403 / Mark lvalue as nontemporal if the variable is marked as nontemporal
3404 / in simd context.
3405 if (getLangOpts().OpenMP &&
3406 CGM.getOpenMPRuntime().isNontemporalDecl(VD))
3407 CapLVal.setNontemporal(/*Value=*/true);
3408 return CapLVal;
3409 }
3410
3411 assert(isa<BlockDecl>(CurCodeDecl));
3412 Address addr = GetAddrOfBlockDecl(VD);
3413 return MakeAddrLValue(addr, T, AlignmentSource::Decl);
3414 }
3415 }
3416
3417 / FIXME: We should be able to assert this for FunctionDecls as well!
3418 / FIXME: We should be able to assert this for all DeclRefExprs, not just
3419 / those with a valid source location.
3420 assert((ND->isUsed(false) || !isa<VarDecl>(ND) || E->isNonOdrUse() ||
3421 !E->getLocation().isValid()) &&
3422 "Should not use decl without marking it used!");
3423
3424 if (ND->hasAttr<WeakRefAttr>()) {
3425 const auto *VD = cast<ValueDecl>(ND);
3426 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
3427 return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl);
3428 }
3429
3430 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
3431 / Check if this is a global variable.
3432 if (VD->hasLinkage() || VD->isStaticDataMember())
3433 return EmitGlobalVarDeclLValue(*this, E, VD);
3434
3435 Address addr = Address::invalid();
3436
3437 / The variable should generally be present in the local decl map.
3438 auto iter = LocalDeclMap.find(VD);
3439 if (iter != LocalDeclMap.end()) {
3440 addr = iter->second;
3441
3442 / Otherwise, it might be static local we haven't emitted yet for
3443 / some reason; most likely, because it's in an outer function.
3444 } else if (VD->isStaticLocal()) {
3445 llvm::Constant *var = CGM.getOrCreateStaticVarDecl(
3446 *VD, CGM.getLLVMLinkageVarDefinition(VD));
3447 addr = Address(
3448 var, ConvertTypeForMem(VD->getType()), getContext().getDeclAlign(VD));
3449
3450 / No other cases for now.
3451 } else {
3452 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
3453 }
3454
3455 / Handle threadlocal function locals.
3456 if (VD->getTLSKind() != VarDecl::TLS_None)
3457 addr = addr.withPointer(
3458 Builder.CreateThreadLocalAddress(addr.getBasePointer()),
3460
3461 / Check for OpenMP threadprivate variables.
3462 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd &&
3463 VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
3465 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
3466 E->getExprLoc());
3467 }
3468
3469 / Drill into block byref variables.
3470 bool isBlockByref = VD->isEscapingByref();
3471 if (isBlockByref) {
3472 addr = emitBlockByrefAddress(addr, VD);
3473 }
3474
3475 / Drill into reference types.
3476 LValue LV = VD->getType()->isReferenceType() ?
3479
3480 bool isLocalStorage = VD->hasLocalStorage();
3481
3482 bool NonGCable = isLocalStorage &&
3483 !VD->getType()->isReferenceType() &&
3484 !isBlockByref;
3485 if (NonGCable) {
3487 LV.setNonGC(true);
3488 }
3489
3490 bool isImpreciseLifetime =
3491 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
3492 if (isImpreciseLifetime)
3495 return LV;
3496 }
3497
3498 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
3499 return EmitFunctionDeclLValue(*this, E, FD);
3500
3501 / FIXME: While we're emitting a binding from an enclosing scope, all other
3502 / DeclRefExprs we see should be implicitly treated as if they also refer to
3503 / an enclosing scope.
3504 if (const auto *BD = dyn_cast<BindingDecl>(ND)) {
3506 auto *FD = LambdaCaptureFields.lookup(BD);
3507 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
3508 }
3509 / Suppress debug location updates when visiting the binding, since the
3510 / binding may emit instructions that would otherwise be associated with the
3511 / binding itself, rather than the expression referencing the binding. (this
3512 / leads to jumpy debug stepping behavior where the location/debugger jump
3513 / back to the binding declaration, then back to the expression referencing
3514 / the binding)
3516 return EmitLValue(BD->getBinding(), NotKnownNonNull);
3517 }
3518
3519 / We can form DeclRefExprs naming GUID declarations when reconstituting
3520 / non-type template parameters into expressions.
3521 if (const auto *GD = dyn_cast<MSGuidDecl>(ND))
3522 return MakeAddrLValue(CGM.GetAddrOfMSGuidDecl(GD), T,
3524
3525 if (const auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
3526 auto ATPO = CGM.GetAddrOfTemplateParamObject(TPO);
3527 auto AS = getLangASFromTargetAS(ATPO.getAddressSpace());
3528
3529 if (AS != T.getAddressSpace()) {
3530 auto TargetAS = getContext().getTargetAddressSpace(T.getAddressSpace());
3531 auto PtrTy = llvm::PointerType::get(CGM.getLLVMContext(), TargetAS);
3532 auto ASC = getTargetHooks().performAddrSpaceCast(CGM, ATPO.getPointer(),
3533 AS, PtrTy);
3534 ATPO = ConstantAddress(ASC, ATPO.getElementType(), ATPO.getAlignment());
3535 }
3536
3537 return MakeAddrLValue(ATPO, T, AlignmentSource::Decl);
3538 }
3539
3540 llvm_unreachable("Unhandled DeclRefExpr");
3541}
3542
3544 / __extension__ doesn't affect lvalue-ness.
3545 if (E->getOpcode() == UO_Extension)
3546 return EmitLValue(E->getSubExpr());
3547
3549 switch (E->getOpcode()) {
3550 default: llvm_unreachable("Unknown unary operator lvalue!");
3551 case UO_Deref: {
3553 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
3554
3555 LValueBaseInfo BaseInfo;
3556 TBAAAccessInfo TBAAInfo;
3558 &TBAAInfo);
3559 LValue LV = MakeAddrLValue(Addr, T, BaseInfo, TBAAInfo);
3561
3562 / We should not generate __weak write barrier on indirect reference
3563 / of a pointer to object; as in void foo (__weak id *param); *param = 0;
3564 / But, we continue to generate __strong write barrier on indirect write
3565 / into a pointer to object.
3566 if (getLangOpts().ObjC &&
3567 getLangOpts().getGC() != LangOptions::NonGC &&
3568 LV.isObjCWeak())
3570 return LV;
3571 }
3572 case UO_Real:
3573 case UO_Imag: {
3574 LValue LV = EmitLValue(E->getSubExpr());
3575 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
3576
3577 / __real is valid on scalars. This is a faster way of testing that.
3578 / __imag can only produce an rvalue on scalars.
3579 if (E->getOpcode() == UO_Real &&
3580 !LV.getAddress().getElementType()->isStructTy()) {
3581 assert(E->getSubExpr()->getType()->isArithmeticType());
3582 return LV;
3583 }
3584
3585 QualType T = ExprTy->castAs<ComplexType>()->getElementType();
3586
3587 Address Component =
3588 (E->getOpcode() == UO_Real
3591 LValue ElemLV = MakeAddrLValue(Component, T, LV.getBaseInfo(),
3592 CGM.getTBAAInfoForSubobject(LV, T));
3593 ElemLV.getQuals().addQualifiers(LV.getQuals());
3594 return ElemLV;
3595 }
3596 case UO_PreInc:
3597 case UO_PreDec: {
3598 LValue LV = EmitLValue(E->getSubExpr());
3599 bool isInc = E->getOpcode() == UO_PreInc;
3600
3601 if (E->getType()->isAnyComplexType())
3602 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
3603 else
3604 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
3605 return LV;
3606 }
3607 }
3608}
3609
3611 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
3613}
3614
3616 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
3618}
3619
3621 auto SL = E->getFunctionName();
3622 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
3623 StringRef FnName = CurFn->getName();
3624 FnName.consume_front("\01");
3625 StringRef NameItems[] = {
3627 std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
3628 if (auto *BD = dyn_cast_or_null<BlockDecl>(CurCodeDecl)) {
3629 std::string Name = std::string(SL->getString());
3630 if (!Name.empty()) {
3631 unsigned Discriminator =
3632 CGM.getCXXABI().getMangleContext().getBlockId(BD, true);
3633 if (Discriminator)
3634 Name += "_" + Twine(Discriminator + 1).str();
3635 auto C = CGM.GetAddrOfConstantCString(Name, GVName);
3637 } else {
3638 auto C = CGM.GetAddrOfConstantCString(std::string(FnName), GVName);
3640 }
3641 }
3642 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
3644}
3645
3646/ Emit a type description suitable for use by a runtime sanitizer library. The
3647/ format of a type descriptor is
3648/
3649/ \code
3650/ { i16 TypeKind, i16 TypeInfo }
3651/ \endcode
3652/
3653/ followed by an array of i8 containing the type name with extra information
3654/ for BitInt. TypeKind is TK_Integer(0) for an integer, TK_Float(1) for a
3655/ floating point value, TK_BitInt(2) for BitInt and TK_Unknown(0xFFFF) for
3656/ anything else.
3658 / Only emit each type's descriptor once.
3659 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
3660 return C;
3661
3662 uint16_t TypeKind = TK_Unknown;
3663 uint16_t TypeInfo = 0;
3664 bool IsBitInt = false;
3665
3666 if (T->isIntegerType()) {
3667 TypeKind = TK_Integer;
3668 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
3669 (T->isSignedIntegerType() ? 1 : 0);
3670 / Follow suggestion from discussion of issue 64100.
3671 / So we can write the exact amount of bits in TypeName after '\0'
3672 / making it <diagnostic-like type name>.'\0'.<32-bit width>.
3673 if (T->isSignedIntegerType() && T->getAs<BitIntType>()) {
3674 / Do a sanity checks as we are using 32-bit type to store bit length.
3675 assert(getContext().getTypeSize(T) > 0 &&
3676 " non positive amount of bits in __BitInt type");
3677 assert(getContext().getTypeSize(T) <= 0xFFFFFFFF &&
3678 " too many bits in __BitInt type");
3679
3680 / Redefine TypeKind with the actual __BitInt type if we have signed
3681 / BitInt.
3682 TypeKind = TK_BitInt;
3683 IsBitInt = true;
3684 }
3685 } else if (T->isFloatingType()) {
3686 TypeKind = TK_Float;
3688 }
3689
3690 / Format the type name as if for a diagnostic, including quotes and
3691 / optionally an 'aka'.
3692 SmallString<32> Buffer;
3693 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
3694 (intptr_t)T.getAsOpaquePtr(), StringRef(),
3695 StringRef(), {}, Buffer, {});
3696
3697 if (IsBitInt) {
3698 / The Structure is: 0 to end the string, 32 bit unsigned integer in target
3699 / endianness, zero.
3700 char S[6] = {'\0', '\0'};
3701 const auto *EIT = T->castAs<BitIntType>();
3702 uint32_t Bits = EIT->getNumBits();
3703 llvm::support::endian::write32(S + 1, Bits,
3704 getTarget().isBigEndian()
3705 ? llvm::endianness::big
3706 : llvm::endianness::little);
3707 StringRef Str = StringRef(S, sizeof(S) / sizeof(decltype(S[0])));
3708 Buffer.append(Str);
3709 }
3710
3711 llvm::Constant *Components[] = {
3712 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
3713 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
3714 };
3715 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
3716
3717 auto *GV = new llvm::GlobalVariable(
3718 CGM.getModule(), Descriptor->getType(),
3719 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
3720 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3721 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
3722
3723 / Remember the descriptor for this type.
3724 CGM.setTypeDescriptorInMap(T, GV);
3725
3726 return GV;
3727}
3728
3729llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
3730 llvm::Type *TargetTy = IntPtrTy;
3731
3732 if (V->getType() == TargetTy)
3733 return V;
3734
3735 / Floating-point types which fit into intptr_t are bitcast to integers
3736 / and then passed directly (after zero-extension, if necessary).
3737 if (V->getType()->isFloatingPointTy()) {
3738 unsigned Bits = V->getType()->getPrimitiveSizeInBits().getFixedValue();
3739 if (Bits <= TargetTy->getIntegerBitWidth())
3740 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
3741 Bits));
3742 }
3743
3744 / Integers which fit in intptr_t are zero-extended and passed directly.
3745 if (V->getType()->isIntegerTy() &&
3746 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
3747 return Builder.CreateZExt(V, TargetTy);
3748
3749 / Pointers are passed directly, everything else is passed by address.
3750 if (!V->getType()->isPointerTy()) {
3751 RawAddress Ptr = CreateDefaultAlignTempAlloca(V->getType());
3752 Builder.CreateStore(V, Ptr);
3753 V = Ptr.getPointer();
3754 }
3755 return Builder.CreatePtrToInt(V, TargetTy);
3756}
3757
3758/ Emit a representation of a SourceLocation for passing to a handler
3759/ in a sanitizer runtime library. The format for this data is:
3760/ \code
3761/ struct SourceLocation {
3762/ const char *Filename;
3763/ int32_t Line, Column;
3764/ };
3765/ \endcode
3766/ For an invalid SourceLocation, the Filename pointer is null.
3768 llvm::Constant *Filename;
3769 int Line, Column;
3770
3772 if (PLoc.isValid()) {
3773 StringRef FilenameString = PLoc.getFilename();
3774
3775 int PathComponentsToStrip =
3776 CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
3777 if (PathComponentsToStrip < 0) {
3778 assert(PathComponentsToStrip != INT_MIN);
3779 int PathComponentsToKeep = -PathComponentsToStrip;
3780 auto I = llvm::sys::path::rbegin(FilenameString);
3781 auto E = llvm::sys::path::rend(FilenameString);
3782 while (I != E && --PathComponentsToKeep)
3783 ++I;
3784
3785 FilenameString = FilenameString.substr(I - E);
3786 } else if (PathComponentsToStrip > 0) {
3787 auto I = llvm::sys::path::begin(FilenameString);
3788 auto E = llvm::sys::path::end(FilenameString);
3789 while (I != E && PathComponentsToStrip--)
3790 ++I;
3791
3792 if (I != E)
3793 FilenameString =
3794 FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
3795 else
3796 FilenameString = llvm::sys::path::filename(FilenameString);
3797 }
3798
3799 auto FilenameGV =
3800 CGM.GetAddrOfConstantCString(std::string(FilenameString), ".src");
3801 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
3803 FilenameGV.getPointer()->stripPointerCasts()));
3804 Filename = FilenameGV.getPointer();
3805 Line = PLoc.getLine();
3806 Column = PLoc.getColumn();
3807 } else {
3808 Filename = llvm::Constant::getNullValue(Int8PtrTy);
3809 Line = Column = 0;
3810 }
3811
3812 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
3813 Builder.getInt32(Column)};
3814
3815 return llvm::ConstantStruct::getAnon(Data);
3816}
3817
3818namespace {
3819/ Specify under what conditions this check can be recovered
3820enum class CheckRecoverableKind {
3821 / Always terminate program execution if this check fails.
3823 / Check supports recovering, runtime has both fatal (noreturn) and
3824 / non-fatal handlers for this check.
3825 Recoverable,
3826 / Runtime conditionally aborts, always need to support recovery.
3828};
3829}
3830
3831static CheckRecoverableKind
3833 if (Ordinal == SanitizerKind::SO_Vptr)
3834 return CheckRecoverableKind::AlwaysRecoverable;
3835 else if (Ordinal == SanitizerKind::SO_Return ||
3836 Ordinal == SanitizerKind::SO_Unreachable)
3837 return CheckRecoverableKind::Unrecoverable;
3838 else
3839 return CheckRecoverableKind::Recoverable;
3840}
3841
3842namespace {
3843struct SanitizerHandlerInfo {
3844 char const *const Name;
3845 unsigned Version;
3846};
3847}
3848
3849const SanitizerHandlerInfo SanitizerHandlers[] = {
3850#define SANITIZER_CHECK(Enum, Name, Version, Msg) {#Name, Version},
3852#undef SANITIZER_CHECK
3853};
3854
3856 llvm::FunctionType *FnType,
3858 SanitizerHandler CheckHandler,
3859 CheckRecoverableKind RecoverKind, bool IsFatal,
3860 llvm::BasicBlock *ContBB, bool NoMerge) {
3861 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
3862 std::optional<ApplyDebugLocation> DL;
3863 if (!CGF.Builder.getCurrentDebugLocation()) {
3864 / Ensure that the call has at least an artificial debug location.
3865 DL.emplace(CGF, SourceLocation());
3866 }
3867 bool NeedsAbortSuffix =
3868 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
3869 bool MinimalRuntime = CGF.CGM.getCodeGenOpts().SanitizeMinimalRuntime;
3870 bool HandlerPreserveAllRegs =
3871 CGF.CGM.getCodeGenOpts().SanitizeHandlerPreserveAllRegs;
3872 const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler];
3873 const StringRef CheckName = CheckInfo.Name;
3874 std::string FnName = "__ubsan_handle_" + CheckName.str();
3875 if (CheckInfo.Version && !MinimalRuntime)
3876 FnName += "_v" + llvm::utostr(CheckInfo.Version);
3877 if (MinimalRuntime)
3878 FnName += "_minimal";
3879 if (NeedsAbortSuffix)
3880 FnName += "_abort";
3881 if (HandlerPreserveAllRegs && !NeedsAbortSuffix)
3882 FnName += "_preserve";
3883 bool MayReturn =
3884 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
3885
3886 llvm::AttrBuilder B(CGF.getLLVMContext());
3887 if (!MayReturn) {
3888 B.addAttribute(llvm::Attribute::NoReturn)
3889 .addAttribute(llvm::Attribute::NoUnwind);
3890 }
3891 B.addUWTableAttr(llvm::UWTableKind::Default);
3892
3893 llvm::FunctionCallee Fn = CGF.CGM.CreateRuntimeFunction(
3894 FnType, FnName,
3895 llvm::AttributeList::get(CGF.getLLVMContext(),
3896 llvm::AttributeList::FunctionIndex, B),
3897 /*Local=*/true);
3898 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
3899 NoMerge = NoMerge || !CGF.CGM.getCodeGenOpts().OptimizationLevel ||
3900 (CGF.CurCodeDecl && CGF.CurCodeDecl->hasAttr<OptimizeNoneAttr>());
3901 if (NoMerge)
3902 HandlerCall->addFnAttr(llvm::Attribute::NoMerge);
3903 if (HandlerPreserveAllRegs && !NeedsAbortSuffix) {
3904 / N.B. there is also a clang::CallingConv which is not what we want here.
3905 HandlerCall->setCallingConv(llvm::CallingConv::PreserveAll);
3906 }
3907 if (!MayReturn) {
3908 HandlerCall->setDoesNotReturn();
3909 CGF.Builder.CreateUnreachable();
3910 } else {
3911 CGF.Builder.CreateBr(ContBB);
3912 }
3913}
3914
3916 ArrayRef<std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>> Checked,
3917 SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs,
3918 ArrayRef<llvm::Value *> DynamicArgs, const TrapReason *TR) {
3919 assert(IsSanitizerScope);
3920 assert(Checked.size() > 0);
3921 assert(CheckHandler >= 0 &&
3922 size_t(CheckHandler) < std::size(SanitizerHandlers));
3923 const StringRef CheckName = SanitizerHandlers[CheckHandler].Name;
3924
3925 llvm::Value *FatalCond = nullptr;
3926 llvm::Value *RecoverableCond = nullptr;
3927 llvm::Value *TrapCond = nullptr;
3928 bool NoMerge = false;
3929 / Expand checks into:
3930 / (Check1 || !allow_ubsan_check) && (Check2 || !allow_ubsan_check) ...
3931 / We need separate allow_ubsan_check intrinsics because they have separately
3932 / specified cutoffs.
3933 / This expression looks expensive but will be simplified after
3934 / LowerAllowCheckPass.
3935 for (auto &[Check, Ord] : Checked) {
3936 llvm::Value *GuardedCheck = Check;
3938 (CGM.getCodeGenOpts().SanitizeSkipHotCutoffs[Ord] > 0)) {
3939 llvm::Value *Allow = Builder.CreateCall(
3940 CGM.getIntrinsic(llvm::Intrinsic::allow_ubsan_check),
3941 llvm::ConstantInt::get(CGM.Int8Ty, Ord));
3942 GuardedCheck = Builder.CreateOr(Check, Builder.CreateNot(Allow));
3943 }
3944
3945 / -fsanitize-trap= overrides -fsanitize-recover=.
3946 llvm::Value *&Cond = CGM.getCodeGenOpts().SanitizeTrap.has(Ord) ? TrapCond
3947 : CGM.getCodeGenOpts().SanitizeRecover.has(Ord)
3948 ? RecoverableCond
3949 : FatalCond;
3950 Cond = Cond ? Builder.CreateAnd(Cond, GuardedCheck) : GuardedCheck;
3951
3952 if (!CGM.getCodeGenOpts().SanitizeMergeHandlers.has(Ord))
3953 NoMerge = true;
3954 }
3955
3956 if (TrapCond)
3957 EmitTrapCheck(TrapCond, CheckHandler, NoMerge, TR);
3958 if (!FatalCond && !RecoverableCond)
3959 return;
3960
3961 llvm::Value *JointCond;
3962 if (FatalCond && RecoverableCond)
3963 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
3964 else
3965 JointCond = FatalCond ? FatalCond : RecoverableCond;
3966 assert(JointCond);
3967
3968 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
3969 assert(SanOpts.has(Checked[0].second));
3970#ifndef NDEBUG
3971 for (int i = 1, n = Checked.size(); i < n; ++i) {
3972 assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
3973 "All recoverable kinds in a single check must be same!");
3974 assert(SanOpts.has(Checked[i].second));
3975 }
3976#endif
3977
3978 llvm::BasicBlock *Cont = createBasicBlock("cont");
3979 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
3980 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
3981 / Give hint that we very much don't expect to execute the handler
3982 llvm::MDBuilder MDHelper(getLLVMContext());
3983 llvm::MDNode *Node = MDHelper.createLikelyBranchWeights();
3984 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
3985 EmitBlock(Handlers);
3986
3987 / Clear arguments for the MinimalRuntime handler.
3988 if (CGM.getCodeGenOpts().SanitizeMinimalRuntime) {
3989 StaticArgs = {};
3990 DynamicArgs = {};
3991 }
3992
3993 / Handler functions take an i8* pointing to the (handler-specific) static
3994 / information block, followed by a sequence of intptr_t arguments
3995 / representing operand values.
3998
3999 Args.reserve(DynamicArgs.size() + 1);
4000 ArgTypes.reserve(DynamicArgs.size() + 1);
4001
4002 / Emit handler arguments and create handler function type.
4003 if (!StaticArgs.empty()) {
4004 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
4005 auto *InfoPtr = new llvm::GlobalVariable(
4006 CGM.getModule(), Info->getType(),
4007 / Non-constant global is used in a handler to deduplicate reports.
4008 / TODO: change deduplication logic and make it constant.
4009 /*isConstant=*/false, llvm::GlobalVariable::PrivateLinkage, Info, "",
4010 nullptr, llvm::GlobalVariable::NotThreadLocal,
4011 CGM.getDataLayout().getDefaultGlobalsAddressSpace());
4012 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4013 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
4014 Args.push_back(InfoPtr);
4015 ArgTypes.push_back(Args.back()->getType());
4016 }
4017
4018 for (llvm::Value *DynamicArg : DynamicArgs) {
4019 Args.push_back(EmitCheckValue(DynamicArg));
4020 ArgTypes.push_back(IntPtrTy);
4021 }
4022
4023 llvm::FunctionType *FnType =
4024 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
4025
4026 if (!FatalCond || !RecoverableCond) {
4027 / Simple case: we need to generate a single handler call, either
4028 / fatal, or non-fatal.
4029 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind,
4030 (FatalCond != nullptr), Cont, NoMerge);
4031 } else {
4032 / Emit two handler calls: first one for set of unrecoverable checks,
4033 / another one for recoverable.
4034 llvm::BasicBlock *NonFatalHandlerBB =
4035 createBasicBlock("non_fatal." + CheckName);
4036 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
4037 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
4038 EmitBlock(FatalHandlerBB);
4039 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true,
4040 NonFatalHandlerBB, NoMerge);
4041 EmitBlock(NonFatalHandlerBB);
4042 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false,
4043 Cont, NoMerge);
4044 }
4045
4046 EmitBlock(Cont);
4047}
4048
4050 SanitizerKind::SanitizerOrdinal Ordinal, llvm::Value *Cond,
4051 llvm::ConstantInt *TypeId, llvm::Value *Ptr,
4052 ArrayRef<llvm::Constant *> StaticArgs) {
4053 llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
4054
4055 llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
4056 llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
4057
4058 llvm::MDBuilder MDHelper(getLLVMContext());
4059 llvm::MDNode *Node = MDHelper.createLikelyBranchWeights();
4060 BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
4061
4062 EmitBlock(CheckBB);
4063
4064 bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Ordinal);
4065
4066 llvm::CallInst *CheckCall;
4067 llvm::FunctionCallee SlowPathFn;
4068 if (WithDiag) {
4069 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
4070 auto *InfoPtr =
4071 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
4072 llvm::GlobalVariable::PrivateLinkage, Info);
4073 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4074 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
4075
4076 SlowPathFn = CGM.getModule().getOrInsertFunction(
4077 "__cfi_slowpath_diag",
4078 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy},
4079 false));
4080 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr, InfoPtr});
4081 } else {
4082 SlowPathFn = CGM.getModule().getOrInsertFunction(
4083 "__cfi_slowpath",
4084 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
4085 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
4086 }
4087
4088 CGM.setDSOLocal(
4089 cast<llvm::GlobalValue>(SlowPathFn.getCallee()->stripPointerCasts()));
4090 CheckCall->setDoesNotThrow();
4091
4092 EmitBlock(Cont);
4093}
4094
4095/ Emit a stub for __cfi_check function so that the linker knows about this
4096/ symbol in LTO mode.
4098 llvm::Module *M = &CGM.getModule();
4099 ASTContext &C = getContext();
4100 QualType QInt64Ty = C.getIntTypeForBitwidth(64, false);
4101
4103 ImplicitParamDecl ArgCallsiteTypeId(C, QInt64Ty, ImplicitParamKind::Other);
4104 ImplicitParamDecl ArgAddr(C, C.VoidPtrTy, ImplicitParamKind::Other);
4105 ImplicitParamDecl ArgCFICheckFailData(C, C.VoidPtrTy,
4107 FnArgs.push_back(&ArgCallsiteTypeId);
4108 FnArgs.push_back(&ArgAddr);
4109 FnArgs.push_back(&ArgCFICheckFailData);
4110 const CGFunctionInfo &FI =
4111 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, FnArgs);
4112
4113 llvm::Function *F = llvm::Function::Create(
4114 llvm::FunctionType::get(VoidTy, {Int64Ty, VoidPtrTy}, false),
4115 llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M);
4116 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, F, /*IsThunk=*/false);
4117 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, F);
4118 F->setAlignment(llvm::Align(4096));
4119 CGM.setDSOLocal(F);
4120
4121 llvm::LLVMContext &Ctx = M->getContext();
4122 llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F);
4123 / CrossDSOCFI pass is not executed if there is no executable code.
4124 SmallVector<llvm::Value*> Args{F->getArg(2), F->getArg(1)};
4125 llvm::CallInst::Create(M->getFunction("__cfi_check_fail"), Args, "", BB);
4126 llvm::ReturnInst::Create(Ctx, nullptr, BB);
4127}
4128
4129/ This function is basically a switch over the CFI failure kind, which is
4130/ extracted from CFICheckFailData (1st function argument). Each case is either
4131/ llvm.trap or a call to one of the two runtime handlers, based on
4132/ -fsanitize-trap and -fsanitize-recover settings. Default case (invalid
4133/ failure kind) traps, but this should really never happen. CFICheckFailData
4134/ can be nullptr if the calling module has -fsanitize-trap behavior for this
4135/ check kind; in this case __cfi_check_fail traps as well.
4137 auto CheckHandler = SanitizerHandler::CFICheckFail;
4138 / TODO: the SanitizerKind is not yet determined for this check (and might
4139 / not even be available, if Data == nullptr). However, we still want to
4140 / annotate the instrumentation. We approximate this by using all the CFI
4141 / kinds.
4142 SanitizerDebugLocation SanScope(
4143 this,
4144 {SanitizerKind::SO_CFIVCall, SanitizerKind::SO_CFINVCall,
4145 SanitizerKind::SO_CFIDerivedCast, SanitizerKind::SO_CFIUnrelatedCast,
4146 SanitizerKind::SO_CFIICall},
4147 CheckHandler);
4148 FunctionArgList Args;
4153 Args.push_back(&ArgData);
4154 Args.push_back(&ArgAddr);
4155
4156 const CGFunctionInfo &FI =
4157 CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
4158
4159 llvm::Function *F = llvm::Function::Create(
4160 llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
4161 llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
4162
4163 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, F, /*IsThunk=*/false);
4164 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, F);
4165 F->setVisibility(llvm::GlobalValue::HiddenVisibility);
4166
4167 StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
4168 SourceLocation());
4169
4171
4172 / This function is not affected by NoSanitizeList. This function does
4173 / not have a source location, but "src:*" would still apply. Revert any
4174 / changes to SanOpts made in StartFunction.
4175 SanOpts = CGM.getLangOpts().Sanitize;
4176
4177 llvm::Value *Data =
4178 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
4179 CGM.getContext().VoidPtrTy, ArgData.getLocation());
4180 llvm::Value *Addr =
4181 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
4182 CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
4183
4184 / Data == nullptr means the calling module has trap behaviour for this check.
4185 llvm::Value *DataIsNotNullPtr =
4186 Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
4187 / TODO: since there is no data, we don't know the CheckKind, and therefore
4188 / cannot inspect CGM.getCodeGenOpts().SanitizeMergeHandlers. We default to
4189 / NoMerge = false. Users can disable merging by disabling optimization.
4190 EmitTrapCheck(DataIsNotNullPtr, SanitizerHandler::CFICheckFail,
4191 /*NoMerge=*/false);
4192
4193 llvm::StructType *SourceLocationTy =
4194 llvm::StructType::get(VoidPtrTy, Int32Ty);
4195 llvm::StructType *CfiCheckFailDataTy =
4196 llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy);
4197
4198 llvm::Value *V = Builder.CreateConstGEP2_32(
4199 CfiCheckFailDataTy, Builder.CreatePointerCast(Data, DefaultPtrTy), 0, 0);
4200
4201 Address CheckKindAddr(V, Int8Ty, getIntAlign());
4202 llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
4203
4204 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
4205 CGM.getLLVMContext(),
4206 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
4207 llvm::Value *ValidVtable = Builder.CreateZExt(
4208 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
4209 {Addr, AllVtables}),
4210 IntPtrTy);
4211
4212 const std::pair<int, SanitizerKind::SanitizerOrdinal> CheckKinds[] = {
4213 {CFITCK_VCall, SanitizerKind::SO_CFIVCall},
4214 {CFITCK_NVCall, SanitizerKind::SO_CFINVCall},
4215 {CFITCK_DerivedCast, SanitizerKind::SO_CFIDerivedCast},
4216 {CFITCK_UnrelatedCast, SanitizerKind::SO_CFIUnrelatedCast},
4217 {CFITCK_ICall, SanitizerKind::SO_CFIICall}};
4218
4219 for (auto CheckKindOrdinalPair : CheckKinds) {
4220 int Kind = CheckKindOrdinalPair.first;
4221 SanitizerKind::SanitizerOrdinal Ordinal = CheckKindOrdinalPair.second;
4222
4223 / TODO: we could apply SanitizerAnnotateDebugInfo(Ordinal) instead of
4224 / relying on the SanitizerScope with all CFI ordinals
4225
4226 llvm::Value *Cond =
4227 Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
4228 if (CGM.getLangOpts().Sanitize.has(Ordinal))
4229 EmitCheck(std::make_pair(Cond, Ordinal), SanitizerHandler::CFICheckFail,
4230 {}, {Data, Addr, ValidVtable});
4231 else
4232 / TODO: we can't rely on CGM.getCodeGenOpts().SanitizeMergeHandlers.
4233 / Although the compiler allows SanitizeMergeHandlers to be set
4234 / independently of CGM.getLangOpts().Sanitize, Driver/SanitizerArgs.cpp
4235 / requires that SanitizeMergeHandlers is a subset of Sanitize.
4236 EmitTrapCheck(Cond, CheckHandler, /*NoMerge=*/false);
4237 }
4238
4240 / The only reference to this function will be created during LTO link.
4241 / Make sure it survives until then.
4242 CGM.addUsedGlobal(F);
4243}
4244
4246 if (SanOpts.has(SanitizerKind::Unreachable)) {
4247 auto CheckOrdinal = SanitizerKind::SO_Unreachable;
4248 auto CheckHandler = SanitizerHandler::BuiltinUnreachable;
4249 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
4250 EmitCheck(std::make_pair(static_cast<llvm::Value *>(Builder.getFalse()),
4251 CheckOrdinal),
4252 CheckHandler, EmitCheckSourceLocation(Loc), {});
4253 }
4254 Builder.CreateUnreachable();
4255}
4256
4257void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked,
4258 SanitizerHandler CheckHandlerID,
4259 bool NoMerge, const TrapReason *TR) {
4260 llvm::BasicBlock *Cont = createBasicBlock("cont");
4261
4262 / If we're optimizing, collapse all calls to trap down to just one per
4263 / check-type per function to save on code size.
4264 if ((int)TrapBBs.size() <= CheckHandlerID)
4265 TrapBBs.resize(CheckHandlerID + 1);
4266
4267 llvm::BasicBlock *&TrapBB = TrapBBs[CheckHandlerID];
4268
4269 llvm::DILocation *TrapLocation = Builder.getCurrentDebugLocation();
4270 llvm::StringRef TrapMessage;
4271 llvm::StringRef TrapCategory;
4272 auto DebugTrapReasonKind = CGM.getCodeGenOpts().getSanitizeDebugTrapReasons();
4273 if (TR && !TR->isEmpty() &&
4274 DebugTrapReasonKind ==
4276 TrapMessage = TR->getMessage();
4277 TrapCategory = TR->getCategory();
4278 } else {
4279 TrapMessage = GetUBSanTrapForHandler(CheckHandlerID);
4280 TrapCategory = "Undefined Behavior Sanitizer";
4281 }
4282
4283 if (getDebugInfo() && !TrapMessage.empty() &&
4284 DebugTrapReasonKind !=
4286 TrapLocation) {
4287 TrapLocation = getDebugInfo()->CreateTrapFailureMessageFor(
4288 TrapLocation, TrapCategory, TrapMessage);
4289 }
4290
4291 NoMerge = NoMerge || !CGM.getCodeGenOpts().OptimizationLevel ||
4292 (CurCodeDecl && CurCodeDecl->hasAttr<OptimizeNoneAttr>());
4293
4294 llvm::MDBuilder MDHelper(getLLVMContext());
4295 if (TrapBB && !NoMerge) {
4296 auto Call = TrapBB->begin();
4297 assert(isa<llvm::CallInst>(Call) && "Expected call in trap BB");
4298
4299 Call->applyMergedLocation(Call->getDebugLoc(), TrapLocation);
4300
4301 Builder.CreateCondBr(Checked, Cont, TrapBB,
4302 MDHelper.createLikelyBranchWeights());
4303 } else {
4304 TrapBB = createBasicBlock("trap");
4305 Builder.CreateCondBr(Checked, Cont, TrapBB,
4306 MDHelper.createLikelyBranchWeights());
4307 EmitBlock(TrapBB);
4308
4309 ApplyDebugLocation applyTrapDI(*this, TrapLocation);
4310
4311 llvm::CallInst *TrapCall =
4312 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::ubsantrap),
4313 llvm::ConstantInt::get(CGM.Int8Ty, CheckHandlerID));
4314
4315 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
4316 auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
4317 CGM.getCodeGenOpts().TrapFuncName);
4318 TrapCall->addFnAttr(A);
4319 }
4320 if (NoMerge)
4321 TrapCall->addFnAttr(llvm::Attribute::NoMerge);
4322 TrapCall->setDoesNotReturn();
4323 TrapCall->setDoesNotThrow();
4324 Builder.CreateUnreachable();
4325 }
4326
4327 EmitBlock(Cont);
4328}
4329
4330llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
4331 llvm::CallInst *TrapCall =
4332 Builder.CreateCall(CGM.getIntrinsic(IntrID));
4333
4334 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
4335 auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
4336 CGM.getCodeGenOpts().TrapFuncName);
4337 TrapCall->addFnAttr(A);
4338 }
4339
4341 TrapCall->addFnAttr(llvm::Attribute::NoMerge);
4342 return TrapCall;
4343}
4344
4346 LValueBaseInfo *BaseInfo,
4347 TBAAAccessInfo *TBAAInfo) {
4348 assert(E->getType()->isArrayType() &&
4349 "Array to pointer decay must have array source type!");
4350
4351 / Expressions of array type can't be bitfields or vector elements.
4352 LValue LV = EmitLValue(E);
4353 Address Addr = LV.getAddress();
4354
4355 / If the array type was an incomplete type, we need to make sure
4356 / the decay ends up being the right type.
4357 llvm::Type *NewTy = ConvertType(E->getType());
4358 Addr = Addr.withElementType(NewTy);
4359
4360 / Note that VLA pointers are always decayed, so we don't need to do
4361 / anything here.
4362 if (!E->getType()->isVariableArrayType()) {
4363 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
4364 "Expected pointer to array");
4365 Addr = Builder.CreateConstArrayGEP(Addr, 0, "arraydecay");
4366 }
4367
4368 / The result of this decay conversion points to an array element within the
4369 / base lvalue. However, since TBAA currently does not support representing
4370 / accesses to elements of member arrays, we conservatively represent accesses
4371 / to the pointee object as if it had no any base lvalue specified.
4372 / TODO: Support TBAA for member arrays.
4374 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
4375 if (TBAAInfo) *TBAAInfo = CGM.getTBAAAccessInfo(EltType);
4376
4377 return Addr.withElementType(ConvertTypeForMem(EltType));
4378}
4379
4380/ isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
4381/ array to pointer, return the array subexpression.
4382static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
4383 / If this isn't just an array->pointer decay, bail out.
4384 const auto *CE = dyn_cast<CastExpr>(E);
4385 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
4386 return nullptr;
4387
4388 / If this is a decay from variable width array, bail out.
4389 const Expr *SubExpr = CE->getSubExpr();
4390 if (SubExpr->getType()->isVariableArrayType())
4391 return nullptr;
4392
4393 return SubExpr;
4394}
4395
4397 llvm::Type *elemType,
4398 llvm::Value *ptr,
4399 ArrayRef<llvm::Value*> indices,
4400 bool inbounds,
4401 bool signedIndices,
4402 SourceLocation loc,
4403 const llvm::Twine &name = "arrayidx") {
4404 if (inbounds) {
4405 return CGF.EmitCheckedInBoundsGEP(elemType, ptr, indices, signedIndices,
4407 name);
4408 } else {
4409 return CGF.Builder.CreateGEP(elemType, ptr, indices, name);
4410 }
4411}
4412
4415 llvm::Type *elementType, bool inbounds,
4416 bool signedIndices, SourceLocation loc,
4417 CharUnits align,
4418 const llvm::Twine &name = "arrayidx") {
4419 if (inbounds) {
4420 return CGF.EmitCheckedInBoundsGEP(addr, indices, elementType, signedIndices,
4422 align, name);
4423 } else {
4424 return CGF.Builder.CreateGEP(addr, indices, elementType, align, name);
4425 }
4426}
4427
4429 const VariableArrayType *vla) {
4430 QualType eltType;
4431 do {
4432 eltType = vla->getElementType();
4433 } while ((vla = ctx.getAsVariableArrayType(eltType)));
4434 return eltType;
4435}
4436
4438 return D && D->hasAttr<BPFPreserveStaticOffsetAttr>();
4439}
4440
4441static bool hasBPFPreserveStaticOffset(const Expr *E) {
4442 if (!E)
4443 return false;
4444 QualType PointeeType = E->getType()->getPointeeType();
4445 if (PointeeType.isNull())
4446 return false;
4447 if (const auto *BaseDecl = PointeeType->getAsRecordDecl())
4448 return hasBPFPreserveStaticOffset(BaseDecl);
4449 return false;
4450}
4451
4452/ Wraps Addr with a call to llvm.preserve.static.offset intrinsic.
4454 Address &Addr) {
4455 if (!CGF.getTarget().getTriple().isBPF())
4456 return Addr;
4457
4458 llvm::Function *Fn =
4459 CGF.CGM.getIntrinsic(llvm::Intrinsic::preserve_static_offset);
4460 llvm::CallInst *Call = CGF.Builder.CreateCall(Fn, {Addr.emitRawPointer(CGF)});
4461 return Address(Call, Addr.getElementType(), Addr.getAlignment());
4462}
4463
4464/ Given an array base, check whether its member access belongs to a record
4465/ with preserve_access_index attribute or not.
4466static bool IsPreserveAIArrayBase(CodeGenFunction &CGF, const Expr *ArrayBase) {
4467 if (!ArrayBase || !CGF.getDebugInfo())
4468 return false;
4469
4470 / Only support base as either a MemberExpr or DeclRefExpr.
4471 / DeclRefExpr to cover cases like:
4472 / struct s { int a; int b[10]; };
4473 / struct s *p;
4474 / p[1].a
4475 / p[1] will generate a DeclRefExpr and p[1].a is a MemberExpr.
4476 / p->b[5] is a MemberExpr example.
4477 const Expr *E = ArrayBase->IgnoreImpCasts();
4478 if (const auto *ME = dyn_cast<MemberExpr>(E))
4479 return ME->getMemberDecl()->hasAttr<BPFPreserveAccessIndexAttr>();
4480
4481 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
4482 const auto *VarDef = dyn_cast<VarDecl>(DRE->getDecl());
4483 if (!VarDef)
4484 return false;
4485
4486 const auto *PtrT = VarDef->getType()->getAs<PointerType>();
4487 if (!PtrT)
4488 return false;
4489
4490 const auto *PointeeT = PtrT->getPointeeType()
4492 if (const auto *RecT = dyn_cast<RecordType>(PointeeT))
4493 return RecT->getDecl()
4494 ->getMostRecentDecl()
4495 ->hasAttr<BPFPreserveAccessIndexAttr>();
4496 return false;
4497 }
4498
4499 return false;
4500}
4501
4504 QualType eltType, bool inbounds,
4505 bool signedIndices, SourceLocation loc,
4506 QualType *arrayType = nullptr,
4507 const Expr *Base = nullptr,
4508 const llvm::Twine &name = "arrayidx") {
4509 / All the indices except that last must be zero.
4510#ifndef NDEBUG
4511 for (auto *idx : indices.drop_back())
4512 assert(isa<llvm::ConstantInt>(idx) &&
4513 cast<llvm::ConstantInt>(idx)->isZero());
4514#endif
4515
4516 / Determine the element size of the statically-sized base. This is
4517 / the thing that the indices are expressed in terms of.
4518 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
4519 eltType = getFixedSizeElementType(CGF.getContext(), vla);
4520 }
4521
4522 / We can use that to compute the best alignment of the element.
4523 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
4524 CharUnits eltAlign =
4525 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
4526
4528 addr = wrapWithBPFPreserveStaticOffset(CGF, addr);
4529
4530 llvm::Value *eltPtr;
4531 auto LastIndex = dyn_cast<llvm::ConstantInt>(indices.back());
4532 if (!LastIndex ||
4534 addr = emitArraySubscriptGEP(CGF, addr, indices,
4535 CGF.ConvertTypeForMem(eltType), inbounds,
4536 signedIndices, loc, eltAlign, name);
4537 return addr;
4538 } else {
4539 / Remember the original array subscript for bpf target
4540 unsigned idx = LastIndex->getZExtValue();
4541 llvm::DIType *DbgInfo = nullptr;
4542 if (arrayType)
4543 DbgInfo = CGF.getDebugInfo()->getOrCreateStandaloneType(*arrayType, loc);
4544 eltPtr = CGF.Builder.CreatePreserveArrayAccessIndex(
4545 addr.getElementType(), addr.emitRawPointer(CGF), indices.size() - 1,
4546 idx, DbgInfo);
4547 }
4548
4549 return Address(eltPtr, CGF.ConvertTypeForMem(eltType), eltAlign);
4550}
4551
4552namespace {
4553
4554/ StructFieldAccess is a simple visitor class to grab the first l-value to
4555/ r-value cast Expr.
4556struct StructFieldAccess
4557 : public ConstStmtVisitor<StructFieldAccess, const Expr *> {
4558 const Expr *VisitCastExpr(const CastExpr *E) {
4559 if (E->getCastKind() == CK_LValueToRValue)
4560 return E;
4561 return Visit(E->getSubExpr());
4562 }
4563 const Expr *VisitParenExpr(const ParenExpr *E) {
4564 return Visit(E->getSubExpr());
4565 }
4566};
4567
4568} / end anonymous namespace
4569
4570/ The offset of a field from the beginning of the record.
4572 const FieldDecl *Field, int64_t &Offset) {
4573 ASTContext &Ctx = CGF.getContext();
4574 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(RD);
4575 unsigned FieldNo = 0;
4576
4577 for (const FieldDecl *FD : RD->fields()) {
4578 if (FD == Field) {
4579 Offset += Layout.getFieldOffset(FieldNo);
4580 return true;
4581 }
4582
4583 QualType Ty = FD->getType();
4584 if (Ty->isRecordType())
4585 if (getFieldOffsetInBits(CGF, Ty->getAsRecordDecl(), Field, Offset)) {
4586 Offset += Layout.getFieldOffset(FieldNo);
4587 return true;
4588 }
4589
4590 if (!RD->isUnion())
4591 ++FieldNo;
4592 }
4593
4594 return false;
4595}
4596
4597/ Returns the relative offset difference between \p FD1 and \p FD2.
4598/ \code
4599/ offsetof(struct foo, FD1) - offsetof(struct foo, FD2)
4600/ \endcode
4601/ Both fields must be within the same struct.
4602static std::optional<int64_t> getOffsetDifferenceInBits(CodeGenFunction &CGF,
4603 const FieldDecl *FD1,
4604 const FieldDecl *FD2) {
4605 const RecordDecl *FD1OuterRec =
4607 const RecordDecl *FD2OuterRec =
4609
4610 if (FD1OuterRec != FD2OuterRec)
4611 / Fields must be within the same RecordDecl.
4612 return std::optional<int64_t>();
4613
4614 int64_t FD1Offset = 0;
4615 if (!getFieldOffsetInBits(CGF, FD1OuterRec, FD1, FD1Offset))
4616 return std::optional<int64_t>();
4617
4618 int64_t FD2Offset = 0;
4619 if (!getFieldOffsetInBits(CGF, FD2OuterRec, FD2, FD2Offset))
4620 return std::optional<int64_t>();
4621
4622 return std::make_optional<int64_t>(FD1Offset - FD2Offset);
4623}
4624
4625/ EmitCountedByBoundsChecking - If the array being accessed has a "counted_by"
4626/ attribute, generate bounds checking code. The "count" field is at the top
4627/ level of the struct or in an anonymous struct, that's also at the top level.
4628/ Future expansions may allow the "count" to reside at any place in the
4629/ struct, but the value of "counted_by" will be a "simple" path to the count,
4630/ i.e. "a.b.count", so we shouldn't need the full force of EmitLValue or
4631/ similar to emit the correct GEP.
4633 const Expr *ArrayExpr, QualType ArrayType, Address ArrayInst,
4634 QualType IndexType, llvm::Value *IndexVal, bool Accessed,
4635 bool FlexibleArray) {
4636 const auto *ME = dyn_cast<MemberExpr>(ArrayExpr->IgnoreImpCasts());
4637 if (!ME || !ME->getMemberDecl()->getType()->isCountAttributedType())
4638 return;
4639
4640 const LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
4641 getLangOpts().getStrictFlexArraysLevel();
4642 if (FlexibleArray &&
4643 !ME->isFlexibleArrayMemberLike(getContext(), StrictFlexArraysLevel))
4644 return;
4645
4646 const FieldDecl *FD = cast<FieldDecl>(ME->getMemberDecl());
4647 const FieldDecl *CountFD = FD->findCountedByField();
4648 if (!CountFD)
4649 return;
4650
4651 if (std::optional<int64_t> Diff =
4652 getOffsetDifferenceInBits(*this, CountFD, FD)) {
4653 if (!ArrayInst.isValid()) {
4654 / An invalid Address indicates we're checking a pointer array access.
4655 / Emit the checked L-Value here.
4656 LValue LV = EmitCheckedLValue(ArrayExpr, TCK_MemberAccess);
4657 ArrayInst = LV.getAddress();
4658 }
4659
4660 / FIXME: The 'static_cast' is necessary, otherwise the result turns into a
4661 / uint64_t, which messes things up if we have a negative offset difference.
4662 Diff = *Diff / static_cast<int64_t>(CGM.getContext().getCharWidth());
4663
4664 / Create a GEP with the byte offset between the counted object and the
4665 / count and use that to load the count value.
4666 ArrayInst = Builder.CreatePointerBitCastOrAddrSpaceCast(ArrayInst,
4667 Int8PtrTy, Int8Ty);
4668
4669 llvm::Type *BoundsType = ConvertType(CountFD->getType());
4670 llvm::Value *BoundsVal =
4671 Builder.CreateInBoundsGEP(Int8Ty, ArrayInst.emitRawPointer(*this),
4672 Builder.getInt32(*Diff), ".counted_by.gep");
4673 BoundsVal = Builder.CreateAlignedLoad(BoundsType, BoundsVal, getIntAlign(),
4674 ".counted_by.load");
4675
4676 / Now emit the bounds checking.
4677 EmitBoundsCheckImpl(ArrayExpr, ArrayType, IndexVal, IndexType, BoundsVal,
4678 CountFD->getType(), Accessed);
4679 }
4680}
4681
4683 bool Accessed) {
4684 / The index must always be an integer, which is not an aggregate. Emit it
4685 / in lexical order (this complexity is, sadly, required by C++17).
4686 llvm::Value *IdxPre =
4687 (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr;
4688 bool SignedIndices = false;
4689 auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
4690 auto *Idx = IdxPre;
4691 if (E->getLHS() != E->getIdx()) {
4692 assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
4693 Idx = EmitScalarExpr(E->getIdx());
4694 }
4695
4696 QualType IdxTy = E->getIdx()->getType();
4697 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
4698 SignedIndices |= IdxSigned;
4699
4700 if (SanOpts.has(SanitizerKind::ArrayBounds))
4701 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
4702
4703 / Extend or truncate the index type to 32 or 64-bits.
4704 if (Promote && Idx->getType() != IntPtrTy)
4705 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
4706
4707 return Idx;
4708 };
4709 IdxPre = nullptr;
4710
4711 / If the base is a vector type, then we are forming a vector element lvalue
4712 / with this subscript.
4713 if (E->getBase()->getType()->isSubscriptableVectorType() &&
4715 / Emit the vector as an lvalue to get its address.
4716 LValue LHS = EmitLValue(E->getBase());
4717 auto *Idx = EmitIdxAfterBase(/*Promote*/false);
4718 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
4719 return LValue::MakeVectorElt(LHS.getAddress(), Idx, E->getBase()->getType(),
4720 LHS.getBaseInfo(), TBAAAccessInfo());
4721 }
4722
4723 / The HLSL runtime handles subscript expressions on global resource arrays
4724 / and objects with HLSL buffer layouts.
4725 if (getLangOpts().HLSL) {
4726 std::optional<LValue> LV;
4727 if (E->getType()->isHLSLResourceRecord() ||
4729 LV = CGM.getHLSLRuntime().emitResourceArraySubscriptExpr(E, *this);
4730 } else if (E->getType().getAddressSpace() == LangAS::hlsl_constant) {
4731 LV = CGM.getHLSLRuntime().emitBufferArraySubscriptExpr(E, *this,
4732 EmitIdxAfterBase);
4733 }
4734 if (LV.has_value())
4735 return *LV;
4736 }
4737
4738 / All the other cases basically behave like simple offsetting.
4739
4740 / Handle the extvector case we ignored above.
4742 LValue LV = EmitLValue(E->getBase());
4743 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
4745
4746 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
4747 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true,
4748 SignedIndices, E->getExprLoc());
4749 return MakeAddrLValue(Addr, EltType, LV.getBaseInfo(),
4750 CGM.getTBAAInfoForSubobject(LV, EltType));
4751 }
4752
4753 LValueBaseInfo EltBaseInfo;
4754 TBAAAccessInfo EltTBAAInfo;
4756 if (const VariableArrayType *vla =
4757 getContext().getAsVariableArrayType(E->getType())) {
4758 / The base must be a pointer, which is not an aggregate. Emit
4759 / it. It needs to be emitted first in case it's what captures
4760 / the VLA bounds.
4761 Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
4762 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
4763
4764 / The element count here is the total number of non-VLA elements.
4765 llvm::Value *numElements = getVLASize(vla).NumElts;
4766
4767 / Effectively, the multiply by the VLA size is part of the GEP.
4768 / GEP indexes are signed, and scaling an index isn't permitted to
4769 / signed-overflow, so we use the same semantics for our explicit
4770 / multiply. We suppress this if overflow is not undefined behavior.
4771 if (getLangOpts().PointerOverflowDefined) {
4772 Idx = Builder.CreateMul(Idx, numElements);
4773 } else {
4774 Idx = Builder.CreateNSWMul(Idx, numElements);
4775 }
4776
4777 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
4778 !getLangOpts().PointerOverflowDefined,
4779 SignedIndices, E->getExprLoc());
4780
4781 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
4782 / Indexing over an interface, as in "NSString *P; P[4];"
4783
4784 / Emit the base pointer.
4785 Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
4786 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
4787
4788 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
4789 llvm::Value *InterfaceSizeVal =
4790 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
4791
4792 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
4793
4794 / We don't necessarily build correct LLVM struct types for ObjC
4795 / interfaces, so we can't rely on GEP to do this scaling
4796 / correctly, so we need to cast to i8*. FIXME: is this actually
4797 / true? A lot of other things in the fragile ABI would break...
4798 llvm::Type *OrigBaseElemTy = Addr.getElementType();
4799
4800 / Do the GEP.
4801 CharUnits EltAlign =
4802 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
4803 llvm::Value *EltPtr =
4804 emitArraySubscriptGEP(*this, Int8Ty, Addr.emitRawPointer(*this),
4805 ScaledIdx, false, SignedIndices, E->getExprLoc());
4806 Addr = Address(EltPtr, OrigBaseElemTy, EltAlign);
4807 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
4808 / If this is A[i] where A is an array, the frontend will have decayed the
4809 / base to be a ArrayToPointerDecay implicit cast. While correct, it is
4810 / inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
4811 / "gep x, i" here. Emit one "gep A, 0, i".
4812 assert(Array->getType()->isArrayType() &&
4813 "Array to pointer decay must have array source type!");
4814 LValue ArrayLV;
4815 / For simple multidimensional array indexing, set the 'accessed' flag for
4816 / better bounds-checking of the base expression.
4817 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
4818 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
4819 else
4820 ArrayLV = EmitLValue(Array);
4821 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
4822
4823 if (SanOpts.has(SanitizerKind::ArrayBounds))
4824 EmitCountedByBoundsChecking(Array, Array->getType(), ArrayLV.getAddress(),
4825 E->getIdx()->getType(), Idx, Accessed,
4826 /*FlexibleArray=*/true);
4827
4828 / Propagate the alignment from the array itself to the result.
4829 QualType arrayType = Array->getType();
4831 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
4832 E->getType(), !getLangOpts().PointerOverflowDefined, SignedIndices,
4833 E->getExprLoc(), &arrayType, E->getBase());
4834 EltBaseInfo = ArrayLV.getBaseInfo();
4835 if (!CGM.getCodeGenOpts().NewStructPathTBAA) {
4836 / Since CodeGenTBAA::getTypeInfoHelper only handles array types for
4837 / new struct path TBAA, we must a use a plain access.
4838 EltTBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, E->getType());
4839 } else if (ArrayLV.getTBAAInfo().isMayAlias()) {
4840 EltTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
4841 } else if (ArrayLV.getTBAAInfo().isIncomplete()) {
4842 / The array element is complete, even if the array is not.
4843 EltTBAAInfo = CGM.getTBAAAccessInfo(E->getType());
4844 } else {
4845 / The TBAA access info from the array (base) lvalue is ordinary. We will
4846 / adapt it to create access info for the element.
4847 EltTBAAInfo = ArrayLV.getTBAAInfo();
4848
4849 / We retain the TBAA struct path (BaseType and Offset members) from the
4850 / array. In the TBAA representation, we map any array access to the
4851 / element at index 0, as the index is generally a runtime value. This
4852 / element has the same offset in the base type as the array itself.
4853 / If the array lvalue had no base type, there is no point trying to
4854 / generate one, since an array itself is not a valid base type.
4855
4856 / We also retain the access type from the base lvalue, but the access
4857 / size must be updated to the size of an individual element.
4858 EltTBAAInfo.Size =
4860 }
4861 } else {
4862 / The base must be a pointer; emit it with an estimate of its alignment.
4863 Address BaseAddr =
4864 EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
4865 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
4866 QualType ptrType = E->getBase()->getType();
4867 Addr = emitArraySubscriptGEP(*this, BaseAddr, Idx, E->getType(),
4868 !getLangOpts().PointerOverflowDefined,
4869 SignedIndices, E->getExprLoc(), &ptrType,
4870 E->getBase());
4871
4872 if (SanOpts.has(SanitizerKind::ArrayBounds)) {
4873 StructFieldAccess Visitor;
4874 const Expr *Base = Visitor.Visit(E->getBase());
4875
4876 if (const auto *CE = dyn_cast_if_present<CastExpr>(Base);
4877 CE && CE->getCastKind() == CK_LValueToRValue)
4879 E->getIdx()->getType(), Idx, Accessed,
4880 /*FlexibleArray=*/false);
4881 }
4882 }
4883
4884 LValue LV = MakeAddrLValue(Addr, E->getType(), EltBaseInfo, EltTBAAInfo);
4885
4886 if (getLangOpts().ObjC &&
4887 getLangOpts().getGC() != LangOptions::NonGC) {
4890 }
4891 return LV;
4892}
4893
4895 llvm::Value *Idx = EmitScalarExpr(E);
4896 if (Idx->getType() == IntPtrTy)
4897 return Idx;
4898 bool IsSigned = E->getType()->isSignedIntegerOrEnumerationType();
4899 return Builder.CreateIntCast(Idx, IntPtrTy, IsSigned);
4900}
4901
4903 assert(
4904 !E->isIncomplete() &&
4905 "incomplete matrix subscript expressions should be rejected during Sema");
4906 LValue Base = EmitLValue(E->getBase());
4907
4908 / Extend or truncate the index type to 32 or 64-bits if needed.
4909 llvm::Value *RowIdx = EmitMatrixIndexExpr(E->getRowIdx());
4910 llvm::Value *ColIdx = EmitMatrixIndexExpr(E->getColumnIdx());
4911
4912 llvm::Value *NumRows = Builder.getIntN(
4913 RowIdx->getType()->getScalarSizeInBits(),
4915 llvm::Value *FinalIdx =
4916 Builder.CreateAdd(Builder.CreateMul(ColIdx, NumRows), RowIdx);
4917 return LValue::MakeMatrixElt(
4918 MaybeConvertMatrixAddress(Base.getAddress(), *this), FinalIdx,
4919 E->getBase()->getType(), Base.getBaseInfo(), TBAAAccessInfo());
4920}
4921
4923 LValueBaseInfo &BaseInfo,
4924 TBAAAccessInfo &TBAAInfo,
4925 QualType BaseTy, QualType ElTy,
4926 bool IsLowerBound) {
4927 LValue BaseLVal;
4928 if (auto *ASE = dyn_cast<ArraySectionExpr>(Base->IgnoreParenImpCasts())) {
4929 BaseLVal = CGF.EmitArraySectionExpr(ASE, IsLowerBound);
4930 if (BaseTy->isArrayType()) {
4931 Address Addr = BaseLVal.getAddress();
4932 BaseInfo = BaseLVal.getBaseInfo();
4933
4934 / If the array type was an incomplete type, we need to make sure
4935 / the decay ends up being the right type.
4936 llvm::Type *NewTy = CGF.ConvertType(BaseTy);
4937 Addr = Addr.withElementType(NewTy);
4938
4939 / Note that VLA pointers are always decayed, so we don't need to do
4940 / anything here.
4941 if (!BaseTy->isVariableArrayType()) {
4942 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
4943 "Expected pointer to array");
4944 Addr = CGF.Builder.CreateConstArrayGEP(Addr, 0, "arraydecay");
4945 }
4946
4947 return Addr.withElementType(CGF.ConvertTypeForMem(ElTy));
4948 }
4949 LValueBaseInfo TypeBaseInfo;
4950 TBAAAccessInfo TypeTBAAInfo;
4951 CharUnits Align =
4952 CGF.CGM.getNaturalTypeAlignment(ElTy, &TypeBaseInfo, &TypeTBAAInfo);
4953 BaseInfo.mergeForCast(TypeBaseInfo);
4954 TBAAInfo = CGF.CGM.mergeTBAAInfoForCast(TBAAInfo, TypeTBAAInfo);
4955 return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress()),
4956 CGF.ConvertTypeForMem(ElTy), Align);
4957 }
4958 return CGF.EmitPointerWithAlignment(Base, &BaseInfo, &TBAAInfo);
4959}
4960
4962 bool IsLowerBound) {
4963
4964 assert(!E->isOpenACCArraySection() &&
4965 "OpenACC Array section codegen not implemented");
4966
4968 QualType ResultExprTy;
4969 if (auto *AT = getContext().getAsArrayType(BaseTy))
4970 ResultExprTy = AT->getElementType();
4971 else
4972 ResultExprTy = BaseTy->getPointeeType();
4973 llvm::Value *Idx = nullptr;
4974 if (IsLowerBound || E->getColonLocFirst().isInvalid()) {
4975 / Requesting lower bound or upper bound, but without provided length and
4976 / without ':' symbol for the default length -> length = 1.
4977 / Idx = LowerBound ?: 0;
4978 if (auto *LowerBound = E->getLowerBound()) {
4979 Idx = Builder.CreateIntCast(
4980 EmitScalarExpr(LowerBound), IntPtrTy,
4981 LowerBound->getType()->hasSignedIntegerRepresentation());
4982 } else
4983 Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
4984 } else {
4985 / Try to emit length or lower bound as constant. If this is possible, 1
4986 / is subtracted from constant length or lower bound. Otherwise, emit LLVM
4987 / IR (LB + Len) - 1.
4988 auto &C = CGM.getContext();
4989 auto *Length = E->getLength();
4990 llvm::APSInt ConstLength;
4991 if (Length) {
4992 / Idx = LowerBound + Length - 1;
4993 if (std::optional<llvm::APSInt> CL = Length->getIntegerConstantExpr(C)) {
4994 ConstLength = CL->zextOrTrunc(PointerWidthInBits);
4995 Length = nullptr;
4996 }
4997 auto *LowerBound = E->getLowerBound();
4998 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
4999 if (LowerBound) {
5000 if (std::optional<llvm::APSInt> LB =
5001 LowerBound->getIntegerConstantExpr(C)) {
5002 ConstLowerBound = LB->zextOrTrunc(PointerWidthInBits);
5003 LowerBound = nullptr;
5004 }
5005 }
5006 if (!Length)
5007 --ConstLength;
5008 else if (!LowerBound)
5009 --ConstLowerBound;
5010
5011 if (Length || LowerBound) {
5012 auto *LowerBoundVal =
5013 LowerBound
5014 ? Builder.CreateIntCast(
5015 EmitScalarExpr(LowerBound), IntPtrTy,
5016 LowerBound->getType()->hasSignedIntegerRepresentation())
5017 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
5018 auto *LengthVal =
5019 Length
5020 ? Builder.CreateIntCast(
5021 EmitScalarExpr(Length), IntPtrTy,
5022 Length->getType()->hasSignedIntegerRepresentation())
5023 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
5024 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
5025 /*HasNUW=*/false,
5026 !getLangOpts().PointerOverflowDefined);
5027 if (Length && LowerBound) {
5028 Idx = Builder.CreateSub(
5029 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
5030 /*HasNUW=*/false, !getLangOpts().PointerOverflowDefined);
5031 }
5032 } else
5033 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
5034 } else {
5035 / Idx = ArraySize - 1;
5036 QualType ArrayTy = BaseTy->isPointerType()
5038 : BaseTy;
5039 if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
5040 Length = VAT->getSizeExpr();
5041 if (std::optional<llvm::APSInt> L = Length->getIntegerConstantExpr(C)) {
5042 ConstLength = *L;
5043 Length = nullptr;
5044 }
5045 } else {
5046 auto *CAT = C.getAsConstantArrayType(ArrayTy);
5047 assert(CAT && "unexpected type for array initializer");
5048 ConstLength = CAT->getSize();
5049 }
5050 if (Length) {
5051 auto *LengthVal = Builder.CreateIntCast(
5052 EmitScalarExpr(Length), IntPtrTy,
5053 Length->getType()->hasSignedIntegerRepresentation());
5054 Idx = Builder.CreateSub(
5055 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
5056 /*HasNUW=*/false, !getLangOpts().PointerOverflowDefined);
5057 } else {
5058 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
5059 --ConstLength;
5060 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
5061 }
5062 }
5063 }
5064 assert(Idx);
5065
5066 Address EltPtr = Address::invalid();
5067 LValueBaseInfo BaseInfo;
5068 TBAAAccessInfo TBAAInfo;
5069 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
5070 / The base must be a pointer, which is not an aggregate. Emit
5071 / it. It needs to be emitted first in case it's what captures
5072 / the VLA bounds.
5073 Address Base =
5074 emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, TBAAInfo,
5075 BaseTy, VLA->getElementType(), IsLowerBound);
5076 / The element count here is the total number of non-VLA elements.
5077 llvm::Value *NumElements = getVLASize(VLA).NumElts;
5078
5079 / Effectively, the multiply by the VLA size is part of the GEP.
5080 / GEP indexes are signed, and scaling an index isn't permitted to
5081 / signed-overflow, so we use the same semantics for our explicit
5082 / multiply. We suppress this if overflow is not undefined behavior.
5083 if (getLangOpts().PointerOverflowDefined)
5084 Idx = Builder.CreateMul(Idx, NumElements);
5085 else
5086 Idx = Builder.CreateNSWMul(Idx, NumElements);
5087 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
5088 !getLangOpts().PointerOverflowDefined,
5089 /*signedIndices=*/false, E->getExprLoc());
5090 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
5091 / If this is A[i] where A is an array, the frontend will have decayed the
5092 / base to be a ArrayToPointerDecay implicit cast. While correct, it is
5093 / inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
5094 / "gep x, i" here. Emit one "gep A, 0, i".
5095 assert(Array->getType()->isArrayType() &&
5096 "Array to pointer decay must have array source type!");
5097 LValue ArrayLV;
5098 / For simple multidimensional array indexing, set the 'accessed' flag for
5099 / better bounds-checking of the base expression.
5100 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
5101 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
5102 else
5103 ArrayLV = EmitLValue(Array);
5104
5105 / Propagate the alignment from the array itself to the result.
5106 EltPtr = emitArraySubscriptGEP(
5107 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
5108 ResultExprTy, !getLangOpts().PointerOverflowDefined,
5109 /*signedIndices=*/false, E->getExprLoc());
5110 BaseInfo = ArrayLV.getBaseInfo();
5111 TBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, ResultExprTy);
5112 } else {
5113 Address Base =
5114 emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, TBAAInfo, BaseTy,
5115 ResultExprTy, IsLowerBound);
5116 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
5117 !getLangOpts().PointerOverflowDefined,
5118 /*signedIndices=*/false, E->getExprLoc());
5119 }
5120
5121 return MakeAddrLValue(EltPtr, ResultExprTy, BaseInfo, TBAAInfo);
5122}
5123
5126 / Emit the base vector as an l-value.
5127 LValue Base;
5128
5129 / ExtVectorElementExpr's base can either be a vector or pointer to vector.
5130 if (E->isArrow()) {
5131 / If it is a pointer to a vector, emit the address and form an lvalue with
5132 / it.
5133 LValueBaseInfo BaseInfo;
5134 TBAAAccessInfo TBAAInfo;
5135 Address Ptr = EmitPointerWithAlignment(E->getBase(), &BaseInfo, &TBAAInfo);
5136 const auto *PT = E->getBase()->getType()->castAs<PointerType>();
5137 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), BaseInfo, TBAAInfo);
5138 Base.getQuals().removeObjCGCAttr();
5139 } else if (E->getBase()->isGLValue()) {
5140 / Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
5141 / emit the base as an lvalue.
5142 assert(E->getBase()->getType()->isVectorType());
5143 Base = EmitLValue(E->getBase());
5144 } else {
5145 / Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
5146 assert(E->getBase()->getType()->isVectorType() &&
5147 "Result must be a vector");
5148 llvm::Value *Vec = EmitScalarExpr(E->getBase());
5149
5150 / Store the vector to memory (because LValue wants an address).
5151 Address VecMem = CreateMemTemp(E->getBase()->getType());
5152 / need to zero extend an hlsl boolean vector to store it back to memory
5153 QualType Ty = E->getBase()->getType();
5154 llvm::Type *LTy = convertTypeForLoadStore(Ty, Vec->getType());
5155 if (LTy->getScalarSizeInBits() > Vec->getType()->getScalarSizeInBits())
5156 Vec = Builder.CreateZExt(Vec, LTy);
5157 Builder.CreateStore(Vec, VecMem);
5159 }
5160
5161 QualType type =
5162 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
5163
5164 / Encode the element access list into a vector of unsigned indices.
5166 E->getEncodedElementAccess(Indices);
5167
5168 if (Base.isSimple()) {
5169 llvm::Constant *CV =
5170 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
5171 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
5172 Base.getBaseInfo(), TBAAAccessInfo());
5173 }
5174 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
5175
5176 llvm::Constant *BaseElts = Base.getExtVectorElts();
5178
5179 for (unsigned Index : Indices)
5180 CElts.push_back(BaseElts->getAggregateElement(Index));
5181 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
5182 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
5183 Base.getBaseInfo(), TBAAAccessInfo());
5184}
5185
5187 const Expr *UnderlyingBaseExpr = E->IgnoreParens();
5188 while (auto *BaseMemberExpr = dyn_cast<MemberExpr>(UnderlyingBaseExpr))
5189 UnderlyingBaseExpr = BaseMemberExpr->getBase()->IgnoreParens();
5190 return getContext().isSentinelNullExpr(UnderlyingBaseExpr);
5191}
5192
5194 if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, E)) {
5196 return EmitDeclRefLValue(DRE);
5197 }
5198 if (getLangOpts().HLSL &&
5200 / We have an HLSL buffer - emit using HLSL's layout rules.
5201 return CGM.getHLSLRuntime().emitBufferMemberExpr(*this, E);
5202 }
5203
5204 Expr *BaseExpr = E->getBase();
5205 / Check whether the underlying base pointer is a constant null.
5206 / If so, we do not set inbounds flag for GEP to avoid breaking some
5207 / old-style offsetof idioms.
5208 bool IsInBounds = !getLangOpts().PointerOverflowDefined &&
5210 / If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
5211 LValue BaseLV;
5212 if (E->isArrow()) {
5213 LValueBaseInfo BaseInfo;
5214 TBAAAccessInfo TBAAInfo;
5215 Address Addr = EmitPointerWithAlignment(BaseExpr, &BaseInfo, &TBAAInfo);
5216 QualType PtrTy = BaseExpr->getType()->getPointeeType();
5217 SanitizerSet SkippedChecks;
5218 bool IsBaseCXXThis = IsWrappedCXXThis(BaseExpr);
5219 if (IsBaseCXXThis)
5220 SkippedChecks.set(SanitizerKind::Alignment, true);
5221 if (IsBaseCXXThis || isa<DeclRefExpr>(BaseExpr))
5222 SkippedChecks.set(SanitizerKind::Null, true);
5224 /*Alignment=*/CharUnits::Zero(), SkippedChecks);
5225 BaseLV = MakeAddrLValue(Addr, PtrTy, BaseInfo, TBAAInfo);
5226 } else
5227 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
5228
5229 NamedDecl *ND = E->getMemberDecl();
5230 if (auto *Field = dyn_cast<FieldDecl>(ND)) {
5231 LValue LV = EmitLValueForField(BaseLV, Field, IsInBounds);
5233 if (getLangOpts().OpenMP) {
5234 / If the member was explicitly marked as nontemporal, mark it as
5235 / nontemporal. If the base lvalue is marked as nontemporal, mark access
5236 / to children as nontemporal too.
5237 if ((IsWrappedCXXThis(BaseExpr) &&
5238 CGM.getOpenMPRuntime().isNontemporalDecl(Field)) ||
5239 BaseLV.isNontemporal())
5240 LV.setNontemporal(/*Value=*/true);
5241 }
5242 return LV;
5243 }
5244
5245 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
5246 return EmitFunctionDeclLValue(*this, E, FD);
5247
5248 llvm_unreachable("Unhandled member declaration!");
5249}
5250
5251/ Given that we are currently emitting a lambda, emit an l-value for
5252/ one of its members.
5253/
5255 llvm::Value *ThisValue) {
5256 bool HasExplicitObjectParameter = false;
5257 const auto *MD = dyn_cast_if_present<CXXMethodDecl>(CurCodeDecl);
5258 if (MD) {
5259 HasExplicitObjectParameter = MD->isExplicitObjectMemberFunction();
5260 assert(MD->getParent()->isLambda());
5261 assert(MD->getParent() == Field->getParent());
5262 }
5263 LValue LambdaLV;
5264 if (HasExplicitObjectParameter) {
5265 const VarDecl *D = cast<CXXMethodDecl>(CurCodeDecl)->getParamDecl(0);
5266 auto It = LocalDeclMap.find(D);
5267 assert(It != LocalDeclMap.end() && "explicit parameter not loaded?");
5268 Address AddrOfExplicitObject = It->getSecond();
5269 if (D->getType()->isReferenceType())
5270 LambdaLV = EmitLoadOfReferenceLValue(AddrOfExplicitObject, D->getType(),
5272 else
5273 LambdaLV = MakeAddrLValue(AddrOfExplicitObject,
5275
5276 / Make sure we have an lvalue to the lambda itself and not a derived class.
5277 auto *ThisTy = D->getType().getNonReferenceType()->getAsCXXRecordDecl();
5278 auto *LambdaTy = cast<CXXRecordDecl>(Field->getParent());
5279 if (ThisTy != LambdaTy) {
5280 const CXXCastPath &BasePathArray = getContext().LambdaCastPaths.at(MD);
5282 LambdaLV.getAddress(), ThisTy, BasePathArray.begin(),
5283 BasePathArray.end(), /*NullCheckValue=*/false, SourceLocation());
5285 LambdaLV = MakeAddrLValue(Base, T);
5286 }
5287 } else {
5288 CanQualType LambdaTagType =
5289 getContext().getCanonicalTagType(Field->getParent());
5290 LambdaLV = MakeNaturalAlignAddrLValue(ThisValue, LambdaTagType);
5291 }
5292 return EmitLValueForField(LambdaLV, Field);
5293}
5294
5296 return EmitLValueForLambdaField(Field, CXXABIThisValue);
5297}
5298
5299/ Get the field index in the debug info. The debug info structure/union
5300/ will ignore the unnamed bitfields.
5302 unsigned FieldIndex) {
5303 unsigned I = 0, Skipped = 0;
5304
5305 for (auto *F : Rec->getDefinition()->fields()) {
5306 if (I == FieldIndex)
5307 break;
5308 if (F->isUnnamedBitField())
5309 Skipped++;
5310 I++;
5311 }
5312
5313 return FieldIndex - Skipped;
5314}
5315
5316/ Get the address of a zero-sized field within a record. The resulting
5317/ address doesn't necessarily have the right type.
5319 const FieldDecl *Field,
5320 bool IsInBounds) {
5322 CGF.getContext().getFieldOffset(Field));
5323 if (Offset.isZero())
5324 return Base;
5325 Base = Base.withElementType(CGF.Int8Ty);
5326 if (!IsInBounds)
5327 return CGF.Builder.CreateConstByteGEP(Base, Offset);
5328 return CGF.Builder.CreateConstInBoundsByteGEP(Base, Offset);
5329}
5330
5331/ Drill down to the storage of a field without walking into
5332/ reference types.
5333/
5334/ The resulting address doesn't necessarily have the right type.
5336 const FieldDecl *field, bool IsInBounds) {
5337 if (isEmptyFieldForLayout(CGF.getContext(), field))
5338 return emitAddrOfZeroSizeField(CGF, base, field, IsInBounds);
5339
5340 const RecordDecl *rec = field->getParent();
5341
5342 unsigned idx =
5343 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
5344
5345 if (!IsInBounds)
5346 return CGF.Builder.CreateConstGEP2_32(base, 0, idx, field->getName());
5347
5348 return CGF.Builder.CreateStructGEP(base, idx, field->getName());
5349}
5350
5352 Address addr, const FieldDecl *field) {
5353 const RecordDecl *rec = field->getParent();
5354 llvm::DIType *DbgInfo = CGF.getDebugInfo()->getOrCreateStandaloneType(
5355 base.getType(), rec->getLocation());
5356
5357 unsigned idx =
5358 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
5359
5361 addr, idx, CGF.getDebugInfoFIndex(rec, field->getFieldIndex()), DbgInfo);
5362}
5363
5364static bool hasAnyVptr(const QualType Type, const ASTContext &Context) {
5365 const auto *RD = Type.getTypePtr()->getAsCXXRecordDecl();
5366 if (!RD)
5367 return false;
5368
5369 if (RD->isDynamicClass())
5370 return true;
5371
5372 for (const auto &Base : RD->bases())
5373 if (hasAnyVptr(Base.getType(), Context))
5374 return true;
5375
5376 for (const FieldDecl *Field : RD->fields())
5377 if (hasAnyVptr(Field->getType(), Context))
5378 return true;
5379
5380 return false;
5381}
5382
5384 bool IsInBounds) {
5385 LValueBaseInfo BaseInfo = base.getBaseInfo();
5386
5387 if (field->isBitField()) {
5388 const CGRecordLayout &RL =
5389 CGM.getTypes().getCGRecordLayout(field->getParent());
5390 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
5391 const bool UseVolatile = isAAPCS(CGM.getTarget()) &&
5392 CGM.getCodeGenOpts().AAPCSBitfieldWidth &&
5393 Info.VolatileStorageSize != 0 &&
5394 field->getType()
5397 Address Addr = base.getAddress();
5398 unsigned Idx = RL.getLLVMFieldNo(field);
5399 const RecordDecl *rec = field->getParent();
5402 if (!UseVolatile) {
5403 if (!IsInPreservedAIRegion &&
5404 (!getDebugInfo() || !rec->hasAttr<BPFPreserveAccessIndexAttr>())) {
5405 if (Idx != 0) {
5406 / For structs, we GEP to the field that the record layout suggests.
5407 if (!IsInBounds)
5408 Addr = Builder.CreateConstGEP2_32(Addr, 0, Idx, field->getName());
5409 else
5410 Addr = Builder.CreateStructGEP(Addr, Idx, field->getName());
5411 }
5412 } else {
5413 llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateRecordType(
5414 getContext().getCanonicalTagType(rec), rec->getLocation());
5415 Addr = Builder.CreatePreserveStructAccessIndex(
5416 Addr, Idx, getDebugInfoFIndex(rec, field->getFieldIndex()),
5417 DbgInfo);
5418 }
5419 }
5420 const unsigned SS =
5421 UseVolatile ? Info.VolatileStorageSize : Info.StorageSize;
5422 / Get the access type.
5423 llvm::Type *FieldIntTy = llvm::Type::getIntNTy(getLLVMContext(), SS);
5424 Addr = Addr.withElementType(FieldIntTy);
5425 if (UseVolatile) {
5426 const unsigned VolatileOffset = Info.VolatileStorageOffset.getQuantity();
5427 if (VolatileOffset)
5428 Addr = Builder.CreateConstInBoundsGEP(Addr, VolatileOffset);
5429 }
5430
5431 QualType fieldType =
5432 field->getType().withCVRQualifiers(base.getVRQualifiers());
5433 / TODO: Support TBAA for bit fields.
5434 LValueBaseInfo FieldBaseInfo(BaseInfo.getAlignmentSource());
5435 return LValue::MakeBitfield(Addr, Info, fieldType, FieldBaseInfo,
5436 TBAAAccessInfo());
5437 }
5438
5439 / Fields of may-alias structures are may-alias themselves.
5440 / FIXME: this should get propagated down through anonymous structs
5441 / and unions.
5442 QualType FieldType = field->getType();
5443 const RecordDecl *rec = field->getParent();
5444 AlignmentSource BaseAlignSource = BaseInfo.getAlignmentSource();
5445 LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(BaseAlignSource));
5446 TBAAAccessInfo FieldTBAAInfo;
5447 if (base.getTBAAInfo().isMayAlias() ||
5448 rec->hasAttr<MayAliasAttr>() || FieldType->isVectorType()) {
5449 FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
5450 } else if (rec->isUnion()) {
5451 / TODO: Support TBAA for unions.
5452 FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
5453 } else {
5454 / If no base type been assigned for the base access, then try to generate
5455 / one for this base lvalue.
5456 FieldTBAAInfo = base.getTBAAInfo();
5457 if (!FieldTBAAInfo.BaseType) {
5458 FieldTBAAInfo.BaseType = CGM.getTBAABaseTypeInfo(base.getType());
5459 assert(!FieldTBAAInfo.Offset &&
5460 "Nonzero offset for an access with no base type!");
5461 }
5462
5463 / Adjust offset to be relative to the base type.
5464 const ASTRecordLayout &Layout =
5466 unsigned CharWidth = getContext().getCharWidth();
5467 if (FieldTBAAInfo.BaseType)
5468 FieldTBAAInfo.Offset +=
5469 Layout.getFieldOffset(field->getFieldIndex()) / CharWidth;
5470
5471 / Update the final access type and size.
5472 FieldTBAAInfo.AccessType = CGM.getTBAATypeInfo(FieldType);
5473 FieldTBAAInfo.Size =
5475 }
5476
5477 Address addr = base.getAddress();
5479 addr = wrapWithBPFPreserveStaticOffset(*this, addr);
5480 if (auto *ClassDef = dyn_cast<CXXRecordDecl>(rec)) {
5481 if (CGM.getCodeGenOpts().StrictVTablePointers &&
5482 ClassDef->isDynamicClass()) {
5483 / Getting to any field of dynamic object requires stripping dynamic
5484 / information provided by invariant.group. This is because accessing
5485 / fields may leak the real address of dynamic object, which could result
5486 / in miscompilation when leaked pointer would be compared.
5487 auto *stripped =
5488 Builder.CreateStripInvariantGroup(addr.emitRawPointer(*this));
5489 addr = Address(stripped, addr.getElementType(), addr.getAlignment());
5490 }
5491 }
5492
5493 unsigned RecordCVR = base.getVRQualifiers();
5494 if (rec->isUnion()) {
5495 / For unions, there is no pointer adjustment.
5496 if (CGM.getCodeGenOpts().StrictVTablePointers &&
5497 hasAnyVptr(FieldType, getContext()))
5498 / Because unions can easily skip invariant.barriers, we need to add
5499 / a barrier every time CXXRecord field with vptr is referenced.
5500 addr = Builder.CreateLaunderInvariantGroup(addr);
5501
5503 (getDebugInfo() && rec->hasAttr<BPFPreserveAccessIndexAttr>())) {
5504 / Remember the original union field index
5505 llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateStandaloneType(base.getType(),
5506 rec->getLocation());
5507 addr =
5508 Address(Builder.CreatePreserveUnionAccessIndex(
5509 addr.emitRawPointer(*this),
5510 getDebugInfoFIndex(rec, field->getFieldIndex()), DbgInfo),
5511 addr.getElementType(), addr.getAlignment());
5512 }
5513
5514 if (FieldType->isReferenceType())
5515 addr = addr.withElementType(CGM.getTypes().ConvertTypeForMem(FieldType));
5516 } else {
5517 if (!IsInPreservedAIRegion &&
5518 (!getDebugInfo() || !rec->hasAttr<BPFPreserveAccessIndexAttr>()))
5519 / For structs, we GEP to the field that the record layout suggests.
5520 addr = emitAddrOfFieldStorage(*this, addr, field, IsInBounds);
5521 else
5522 / Remember the original struct field index
5523 addr = emitPreserveStructAccess(*this, base, addr, field);
5524 }
5525
5526 / If this is a reference field, load the reference right now.
5527 if (FieldType->isReferenceType()) {
5528 LValue RefLVal =
5529 MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo);
5530 if (RecordCVR & Qualifiers::Volatile)
5531 RefLVal.getQuals().addVolatile();
5532 addr = EmitLoadOfReference(RefLVal, &FieldBaseInfo, &FieldTBAAInfo);
5533
5534 / Qualifiers on the struct don't apply to the referencee.
5535 RecordCVR = 0;
5536 FieldType = FieldType->getPointeeType();
5537 }
5538
5539 / Make sure that the address is pointing to the right type. This is critical
5540 / for both unions and structs.
5541 addr = addr.withElementType(CGM.getTypes().ConvertTypeForMem(FieldType));
5542
5543 if (field->hasAttr<AnnotateAttr>())
5544 addr = EmitFieldAnnotations(field, addr);
5545
5546 LValue LV = MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo);
5547 LV.getQuals().addCVRQualifiers(RecordCVR);
5548
5549 / __weak attribute on a field is ignored.
5552
5553 return LV;
5554}
5555
5556LValue
5558 const FieldDecl *Field) {
5559 QualType FieldType = Field->getType();
5560
5561 if (!FieldType->isReferenceType())
5562 return EmitLValueForField(Base, Field);
5563
5565 *this, Base.getAddress(), Field,
5566 /*IsInBounds=*/!getLangOpts().PointerOverflowDefined);
5567
5568 / Make sure that the address is pointing to the right type.
5569 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
5570 V = V.withElementType(llvmType);
5571
5572 / TODO: Generate TBAA information that describes this access as a structure
5573 / member access and not just an access to an object of the field's type. This
5574 / should be similar to what we do in EmitLValueForField().
5575 LValueBaseInfo BaseInfo = Base.getBaseInfo();
5576 AlignmentSource FieldAlignSource = BaseInfo.getAlignmentSource();
5577 LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(FieldAlignSource));
5578 return MakeAddrLValue(V, FieldType, FieldBaseInfo,
5579 CGM.getTBAAInfoForSubobject(Base, FieldType));
5580}
5581
5583 if (E->isFileScope()) {
5584 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
5585 return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
5586 }
5587 if (E->getType()->isVariablyModifiedType())
5588 / make sure to emit the VLA size.
5590
5591 Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
5592 const Expr *InitExpr = E->getInitializer();
5594
5595 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
5596 /*Init*/ true);
5597
5598 / Block-scope compound literals are destroyed at the end of the enclosing
5599 / scope in C.
5600 if (!getLangOpts().CPlusPlus)
5603 E->getType(), getDestroyer(DtorKind),
5604 DtorKind & EHCleanup);
5605
5606 return Result;
5607}
5608
5610 if (!E->isGLValue())
5611 / Initializing an aggregate temporary in C++11: T{...}.
5612 return EmitAggExprToLValue(E);
5613
5614 / An lvalue initializer list must be initializing a reference.
5615 assert(E->isTransparent() && "non-transparent glvalue init list");
5616 return EmitLValue(E->getInit(0));
5617}
5618
5619/ Emit the operand of a glvalue conditional operator. This is either a glvalue
5620/ or a (possibly-parenthesized) throw-expression. If this is a throw, no
5621/ LValue is returned and the current block has been terminated.
5622static std::optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
5623 const Expr *Operand) {
5624 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
5625 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
5626 return std::nullopt;
5627 }
5628
5629 return CGF.EmitLValue(Operand);
5630}
5631
5632namespace {
5633/ Handle the case where the condition is a constant evaluatable simple integer,
5634/ which means we don't have to separately handle the true/false blocks.
5635std::optional<LValue> HandleConditionalOperatorLValueSimpleCase(
5636 CodeGenFunction &CGF, const AbstractConditionalOperator *E) {
5637 const Expr *condExpr = E->getCond();
5638 bool CondExprBool;
5639 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
5640 const Expr *Live = E->getTrueExpr(), *Dead = E->getFalseExpr();
5641 if (!CondExprBool)
5642 std::swap(Live, Dead);
5643
5644 if (!CGF.ContainsLabel(Dead)) {
5645 / If the true case is live, we need to track its region.
5646 if (CondExprBool)
5648 CGF.markStmtMaybeUsed(Dead);
5649 / If a throw expression we emit it and return an undefined lvalue
5650 / because it can't be used.
5651 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Live->IgnoreParens())) {
5652 CGF.EmitCXXThrowExpr(ThrowExpr);
5653 llvm::Type *ElemTy = CGF.ConvertType(Dead->getType());
5654 llvm::Type *Ty = CGF.DefaultPtrTy;
5655 return CGF.MakeAddrLValue(
5656 Address(llvm::UndefValue::get(Ty), ElemTy, CharUnits::One()),
5657 Dead->getType());
5658 }
5659 return CGF.EmitLValue(Live);
5660 }
5661 }
5662 return std::nullopt;
5663}
5664struct ConditionalInfo {
5665 llvm::BasicBlock *lhsBlock, *rhsBlock;
5666 std::optional<LValue> LHS, RHS;
5667};
5668
5669/ Create and generate the 3 blocks for a conditional operator.
5670/ Leaves the 'current block' in the continuation basic block.
5671template<typename FuncTy>
5672ConditionalInfo EmitConditionalBlocks(CodeGenFunction &CGF,
5673 const AbstractConditionalOperator *E,
5674 const FuncTy &BranchGenFunc) {
5675 ConditionalInfo Info{CGF.createBasicBlock("cond.true"),
5676 CGF.createBasicBlock("cond.false"), std::nullopt,
5677 std::nullopt};
5678 llvm::BasicBlock *endBlock = CGF.createBasicBlock("cond.end");
5679
5681 CGF.EmitBranchOnBoolExpr(E->getCond(), Info.lhsBlock, Info.rhsBlock,
5682 CGF.getProfileCount(E));
5683
5684 / Any temporaries created here are conditional.
5685 CGF.EmitBlock(Info.lhsBlock);
5687 eval.begin(CGF);
5688 Info.LHS = BranchGenFunc(CGF, E->getTrueExpr());
5689 eval.end(CGF);
5690 Info.lhsBlock = CGF.Builder.GetInsertBlock();
5691
5692 if (Info.LHS)
5693 CGF.Builder.CreateBr(endBlock);
5694
5695 / Any temporaries created here are conditional.
5696 CGF.EmitBlock(Info.rhsBlock);
5697 eval.begin(CGF);
5698 Info.RHS = BranchGenFunc(CGF, E->getFalseExpr());
5699 eval.end(CGF);
5700 Info.rhsBlock = CGF.Builder.GetInsertBlock();
5701 CGF.EmitBlock(endBlock);
5702
5703 return Info;
5704}
5705} / namespace
5706
5708 const AbstractConditionalOperator *E) {
5709 if (!E->isGLValue()) {
5710 / ?: here should be an aggregate.
5711 assert(hasAggregateEvaluationKind(E->getType()) &&
5712 "Unexpected conditional operator!");
5713 return (void)EmitAggExprToLValue(E);
5714 }
5715
5716 OpaqueValueMapping binding(*this, E);
5717 if (HandleConditionalOperatorLValueSimpleCase(*this, E))
5718 return;
5719
5720 EmitConditionalBlocks(*this, E, [](CodeGenFunction &CGF, const Expr *E) {
5721 CGF.EmitIgnoredExpr(E);
5722 return LValue{};
5723 });
5724}
5727 if (!expr->isGLValue()) {
5728 / ?: here should be an aggregate.
5729 assert(hasAggregateEvaluationKind(expr->getType()) &&
5730 "Unexpected conditional operator!");
5731 return EmitAggExprToLValue(expr);
5732 }
5733
5734 OpaqueValueMapping binding(*this, expr);
5735 if (std::optional<LValue> Res =
5736 HandleConditionalOperatorLValueSimpleCase(*this, expr))
5737 return *Res;
5738
5739 ConditionalInfo Info = EmitConditionalBlocks(
5740 *this, expr, [](CodeGenFunction &CGF, const Expr *E) {
5741 return EmitLValueOrThrowExpression(CGF, E);
5742 });
5743
5744 if ((Info.LHS && !Info.LHS->isSimple()) ||
5745 (Info.RHS && !Info.RHS->isSimple()))
5746 return EmitUnsupportedLValue(expr, "conditional operator");
5747
5748 if (Info.LHS && Info.RHS) {
5749 Address lhsAddr = Info.LHS->getAddress();
5750 Address rhsAddr = Info.RHS->getAddress();
5752 lhsAddr, rhsAddr, Info.lhsBlock, Info.rhsBlock,
5753 Builder.GetInsertBlock(), expr->getType());
5754 AlignmentSource alignSource =
5755 std::max(Info.LHS->getBaseInfo().getAlignmentSource(),
5756 Info.RHS->getBaseInfo().getAlignmentSource());
5757 TBAAAccessInfo TBAAInfo = CGM.mergeTBAAInfoForConditionalOperator(
5758 Info.LHS->getTBAAInfo(), Info.RHS->getTBAAInfo());
5759 return MakeAddrLValue(result, expr->getType(), LValueBaseInfo(alignSource),
5760 TBAAInfo);
5761 } else {
5762 assert((Info.LHS || Info.RHS) &&
5763 "both operands of glvalue conditional are throw-expressions?");
5764 return Info.LHS ? *Info.LHS : *Info.RHS;
5765 }
5766}
5767
5768/ EmitCastLValue - Casts are never lvalues unless that cast is to a reference
5769/ type. If the cast is to a reference, we can have the usual lvalue result,
5770/ otherwise if a cast is needed by the code generator in an lvalue context,
5771/ then it must mean that we need the address of an aggregate in order to
5772/ access one of its members. This can happen for all the reasons that casts
5773/ are permitted with aggregate result, including noop aggregate casts, and
5774/ cast from scalar to union.
5776 auto RestoreCurCast =
5777 llvm::make_scope_exit([this, Prev = CurCast] { CurCast = Prev; });
5778 CurCast = E;
5779 switch (E->getCastKind()) {
5780 case CK_ToVoid:
5781 case CK_BitCast:
5782 case CK_LValueToRValueBitCast:
5783 case CK_ArrayToPointerDecay:
5784 case CK_FunctionToPointerDecay:
5785 case CK_NullToMemberPointer:
5786 case CK_NullToPointer:
5787 case CK_IntegralToPointer:
5788 case CK_PointerToIntegral:
5789 case CK_PointerToBoolean:
5790 case CK_IntegralCast:
5791 case CK_BooleanToSignedIntegral:
5792 case CK_IntegralToBoolean:
5793 case CK_IntegralToFloating:
5794 case CK_FloatingToIntegral:
5795 case CK_FloatingToBoolean:
5796 case CK_FloatingCast:
5797 case CK_FloatingRealToComplex:
5798 case CK_FloatingComplexToReal:
5799 case CK_FloatingComplexToBoolean:
5800 case CK_FloatingComplexCast:
5801 case CK_FloatingComplexToIntegralComplex:
5802 case CK_IntegralRealToComplex:
5803 case CK_IntegralComplexToReal:
5804 case CK_IntegralComplexToBoolean:
5805 case CK_IntegralComplexCast:
5806 case CK_IntegralComplexToFloatingComplex:
5807 case CK_DerivedToBaseMemberPointer:
5808 case CK_BaseToDerivedMemberPointer:
5809 case CK_MemberPointerToBoolean:
5810 case CK_ReinterpretMemberPointer:
5811 case CK_AnyPointerToBlockPointerCast:
5812 case CK_ARCProduceObject:
5813 case CK_ARCConsumeObject:
5814 case CK_ARCReclaimReturnedObject:
5815 case CK_ARCExtendBlockObject:
5816 case CK_CopyAndAutoreleaseBlockObject:
5817 case CK_IntToOCLSampler:
5818 case CK_FloatingToFixedPoint:
5819 case CK_FixedPointToFloating:
5820 case CK_FixedPointCast:
5821 case CK_FixedPointToBoolean:
5822 case CK_FixedPointToIntegral:
5823 case CK_IntegralToFixedPoint:
5824 case CK_MatrixCast:
5825 case CK_HLSLVectorTruncation:
5826 case CK_HLSLMatrixTruncation:
5827 case CK_HLSLArrayRValue:
5828 case CK_HLSLElementwiseCast:
5829 case CK_HLSLAggregateSplatCast:
5830 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
5831
5832 case CK_Dependent:
5833 llvm_unreachable("dependent cast kind in IR gen!");
5834
5835 case CK_BuiltinFnToFnPtr:
5836 llvm_unreachable("builtin functions are handled elsewhere");
5837
5838 / These are never l-values; just use the aggregate emission code.
5839 case CK_NonAtomicToAtomic:
5840 case CK_AtomicToNonAtomic:
5841 return EmitAggExprToLValue(E);
5842
5843 case CK_Dynamic: {
5844 LValue LV = EmitLValue(E->getSubExpr());
5845 Address V = LV.getAddress();
5846 const auto *DCE = cast<CXXDynamicCastExpr>(E);
5848 }
5849
5850 case CK_ConstructorConversion:
5851 case CK_UserDefinedConversion:
5852 case CK_CPointerToObjCPointerCast:
5853 case CK_BlockPointerToObjCPointerCast:
5854 case CK_LValueToRValue:
5855 return EmitLValue(E->getSubExpr());
5856
5857 case CK_NoOp: {
5858 / CK_NoOp can model a qualification conversion, which can remove an array
5859 / bound and change the IR type.
5860 / FIXME: Once pointee types are removed from IR, remove this.
5861 LValue LV = EmitLValue(E->getSubExpr());
5862 / Propagate the volatile qualifer to LValue, if exist in E.
5864 LV.getQuals() = E->getType().getQualifiers();
5865 if (LV.isSimple()) {
5866 Address V = LV.getAddress();
5867 if (V.isValid()) {
5868 llvm::Type *T = ConvertTypeForMem(E->getType());
5869 if (V.getElementType() != T)
5870 LV.setAddress(V.withElementType(T));
5871 }
5872 }
5873 return LV;
5874 }
5875
5876 case CK_UncheckedDerivedToBase:
5877 case CK_DerivedToBase: {
5878 auto *DerivedClassDecl = E->getSubExpr()->getType()->castAsCXXRecordDecl();
5879 LValue LV = EmitLValue(E->getSubExpr());
5880 Address This = LV.getAddress();
5881
5882 / Perform the derived-to-base conversion
5884 This, DerivedClassDecl, E->path_begin(), E->path_end(),
5885 /*NullCheckValue=*/false, E->getExprLoc());
5886
5887 / TODO: Support accesses to members of base classes in TBAA. For now, we
5888 / conservatively pretend that the complete object is of the base class
5889 / type.
5890 return MakeAddrLValue(Base, E->getType(), LV.getBaseInfo(),
5891 CGM.getTBAAInfoForSubobject(LV, E->getType()));
5892 }
5893 case CK_ToUnion:
5894 return EmitAggExprToLValue(E);
5895 case CK_BaseToDerived: {
5896 auto *DerivedClassDecl = E->getType()->castAsCXXRecordDecl();
5897 LValue LV = EmitLValue(E->getSubExpr());
5898
5899 / Perform the base-to-derived conversion
5901 LV.getAddress(), DerivedClassDecl, E->path_begin(), E->path_end(),
5902 /*NullCheckValue=*/false);
5903
5904 / C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
5905 / performed and the object is not of the derived type.
5908 E->getType());
5909
5910 if (SanOpts.has(SanitizerKind::CFIDerivedCast))
5911 EmitVTablePtrCheckForCast(E->getType(), Derived,
5912 /*MayBeNull=*/false, CFITCK_DerivedCast,
5913 E->getBeginLoc());
5914
5915 return MakeAddrLValue(Derived, E->getType(), LV.getBaseInfo(),
5916 CGM.getTBAAInfoForSubobject(LV, E->getType()));
5917 }
5918 case CK_LValueBitCast: {
5919 / This must be a reinterpret_cast (or c-style equivalent).
5920 const auto *CE = cast<ExplicitCastExpr>(E);
5921
5922 CGM.EmitExplicitCastExprType(CE, this);
5923 LValue LV = EmitLValue(E->getSubExpr());
5925 ConvertTypeForMem(CE->getTypeAsWritten()->getPointeeType()));
5926
5927 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
5929 /*MayBeNull=*/false, CFITCK_UnrelatedCast,
5930 E->getBeginLoc());
5931
5932 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
5933 CGM.getTBAAInfoForSubobject(LV, E->getType()));
5934 }
5935 case CK_AddressSpaceConversion: {
5936 LValue LV = EmitLValue(E->getSubExpr());
5937 QualType DestTy = getContext().getPointerType(E->getType());
5938 llvm::Value *V = getTargetHooks().performAddrSpaceCast(
5939 *this, LV.getPointer(*this),
5940 E->getSubExpr()->getType().getAddressSpace(), ConvertType(DestTy));
5942 LV.getAddress().getAlignment()),
5943 E->getType(), LV.getBaseInfo(), LV.getTBAAInfo());
5944 }
5945 case CK_ObjCObjectLValueCast: {
5946 LValue LV = EmitLValue(E->getSubExpr());
5948 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
5949 CGM.getTBAAInfoForSubobject(LV, E->getType()));
5950 }
5951 case CK_ZeroToOCLOpaqueType:
5952 llvm_unreachable("NULL to OpenCL opaque type lvalue cast is not valid");
5953
5954 case CK_VectorSplat: {
5955 / LValue results of vector splats are only supported in HLSL.
5956 if (!getLangOpts().HLSL)
5957 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
5958 return EmitLValue(E->getSubExpr());
5959 }
5960 }
5961
5962 llvm_unreachable("Unhandled lvalue cast kind?");
5963}
5964
5969
5970std::pair<LValue, LValue>
5972 / Emitting the casted temporary through an opaque value.
5973 LValue BaseLV = EmitLValue(E->getArgLValue());
5975
5976 QualType ExprTy = E->getType();
5977 Address OutTemp = CreateIRTemp(ExprTy);
5978 LValue TempLV = MakeAddrLValue(OutTemp, ExprTy);
5979
5980 if (E->isInOut())
5982 TempLV);
5983
5985 return std::make_pair(BaseLV, TempLV);
5986}
5987
5989 CallArgList &Args, QualType Ty) {
5990
5991 auto [BaseLV, TempLV] = EmitHLSLOutArgLValues(E, Ty);
5992
5993 llvm::Value *Addr = TempLV.getAddress().getBasePointer();
5994 llvm::Type *ElTy = ConvertTypeForMem(TempLV.getType());
5995
5997
5998 Address TmpAddr(Addr, ElTy, TempLV.getAlignment());
5999 Args.addWriteback(BaseLV, TmpAddr, nullptr, E->getWritebackCast());
6000 Args.add(RValue::get(TmpAddr, *this), Ty);
6001 return TempLV;
6002}
6003
6004LValue
6007
6008 llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
6009 it = OpaqueLValues.find(e);
6010
6011 if (it != OpaqueLValues.end())
6012 return it->second;
6013
6014 assert(e->isUnique() && "LValue for a nonunique OVE hasn't been emitted");
6015 return EmitLValue(e->getSourceExpr());
6016}
6017
6018RValue
6021
6022 llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
6023 it = OpaqueRValues.find(e);
6024
6025 if (it != OpaqueRValues.end())
6026 return it->second;
6027
6028 assert(e->isUnique() && "RValue for a nonunique OVE hasn't been emitted");
6029 return EmitAnyExpr(e->getSourceExpr());
6030}
6031
6034 return OpaqueLValues.contains(E);
6035 return OpaqueRValues.contains(E);
6036}
6037
6039 const FieldDecl *FD,
6040 SourceLocation Loc) {
6041 QualType FT = FD->getType();
6042 LValue FieldLV = EmitLValueForField(LV, FD);
6043 switch (getEvaluationKind(FT)) {
6044 case TEK_Complex:
6045 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
6046 case TEK_Aggregate:
6047 return FieldLV.asAggregateRValue();
6048 case TEK_Scalar:
6049 / This routine is used to load fields one-by-one to perform a copy, so
6050 / don't load reference fields.
6051 if (FD->getType()->isReferenceType())
6052 return RValue::get(FieldLV.getPointer(*this));
6053 / Call EmitLoadOfScalar except when the lvalue is a bitfield to emit a
6054 / primitive load.
6055 if (FieldLV.isBitField())
6056 return EmitLoadOfLValue(FieldLV, Loc);
6057 return RValue::get(EmitLoadOfScalar(FieldLV, Loc));
6058 }
6059 llvm_unreachable("bad evaluation kind");
6060}
6061
6062/===--------------------------------------------------------------------===/
6063/ Expression Emission
6064/===--------------------------------------------------------------------===/
6065
6068 llvm::CallBase **CallOrInvoke) {
6069 llvm::CallBase *CallOrInvokeStorage;
6070 if (!CallOrInvoke) {
6071 CallOrInvoke = &CallOrInvokeStorage;
6072 }
6073
6074 auto AddCoroElideSafeOnExit = llvm::make_scope_exit([&] {
6075 if (E->isCoroElideSafe()) {
6076 auto *I = *CallOrInvoke;
6077 if (I)
6078 I->addFnAttr(llvm::Attribute::CoroElideSafe);
6079 }
6080 });
6081
6082 / Builtins never have block type.
6083 if (E->getCallee()->getType()->isBlockPointerType())
6084 return EmitBlockCallExpr(E, ReturnValue, CallOrInvoke);
6085
6086 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
6087 return EmitCXXMemberCallExpr(CE, ReturnValue, CallOrInvoke);
6088
6089 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
6090 return EmitCUDAKernelCallExpr(CE, ReturnValue, CallOrInvoke);
6091
6092 / A CXXOperatorCallExpr is created even for explicit object methods, but
6093 / these should be treated like static function call.
6094 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
6095 if (const auto *MD =
6096 dyn_cast_if_present<CXXMethodDecl>(CE->getCalleeDecl());
6097 MD && MD->isImplicitObjectMemberFunction())
6098 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue, CallOrInvoke);
6099
6100 CGCallee callee = EmitCallee(E->getCallee());
6101
6102 if (callee.isBuiltin()) {
6103 return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(),
6104 E, ReturnValue);
6105 }
6106
6107 if (callee.isPseudoDestructor()) {
6109 }
6110
6111 return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue,
6112 /*Chain=*/nullptr, CallOrInvoke);
6113}
6114
6115/ Emit a CallExpr without considering whether it might be a subclass.
6118 llvm::CallBase **CallOrInvoke) {
6119 CGCallee Callee = EmitCallee(E->getCallee());
6120 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue,
6121 /*Chain=*/nullptr, CallOrInvoke);
6122}
6123
6124/ Detect the unusual situation where an inline version is shadowed by a
6125/ non-inline version. In that case we should pick the external one
6126/ everywhere. That's GCC behavior too.
6128 for (const FunctionDecl *PD = FD; PD; PD = PD->getPreviousDecl())
6129 if (!PD->isInlineBuiltinDeclaration())
6130 return false;
6131 return true;
6132}
6133
6135 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
6136
6137 if (auto builtinID = FD->getBuiltinID()) {
6138 std::string NoBuiltinFD = ("no-builtin-" + FD->getName()).str();
6139 std::string NoBuiltins = "no-builtins";
6140
6141 StringRef Ident = CGF.CGM.getMangledName(GD);
6142 std::string FDInlineName = (Ident + ".inline").str();
6143
6144 bool IsPredefinedLibFunction =
6146 bool HasAttributeNoBuiltin =
6147 CGF.CurFn->getAttributes().hasFnAttr(NoBuiltinFD) ||
6148 CGF.CurFn->getAttributes().hasFnAttr(NoBuiltins);
6149
6150 / When directing calling an inline builtin, call it through it's mangled
6151 / name to make it clear it's not the actual builtin.
6152 if (CGF.CurFn->getName() != FDInlineName &&
6154 llvm::Constant *CalleePtr = CGF.CGM.getRawFunctionPointer(GD);
6155 llvm::Function *Fn = llvm::cast<llvm::Function>(CalleePtr);
6156 llvm::Module *M = Fn->getParent();
6157 llvm::Function *Clone = M->getFunction(FDInlineName);
6158 if (!Clone) {
6159 Clone = llvm::Function::Create(Fn->getFunctionType(),
6160 llvm::GlobalValue::InternalLinkage,
6161 Fn->getAddressSpace(), FDInlineName, M);
6162 Clone->addFnAttr(llvm::Attribute::AlwaysInline);
6163 }
6164 return CGCallee::forDirect(Clone, GD);
6165 }
6166
6167 / Replaceable builtins provide their own implementation of a builtin. If we
6168 / are in an inline builtin implementation, avoid trivial infinite
6169 / recursion. Honor __attribute__((no_builtin("foo"))) or
6170 / __attribute__((no_builtin)) on the current function unless foo is
6171 / not a predefined library function which means we must generate the
6172 / builtin no matter what.
6173 else if (!IsPredefinedLibFunction || !HasAttributeNoBuiltin)
6174 return CGCallee::forBuiltin(builtinID, FD);
6175 }
6176
6177 llvm::Constant *CalleePtr = CGF.CGM.getRawFunctionPointer(GD);
6178 if (CGF.CGM.getLangOpts().CUDA && !CGF.CGM.getLangOpts().CUDAIsDevice &&
6179 FD->hasAttr<CUDAGlobalAttr>())
6180 CalleePtr = CGF.CGM.getCUDARuntime().getKernelStub(
6181 cast<llvm::GlobalValue>(CalleePtr->stripPointerCasts()));
6182
6183 return CGCallee::forDirect(CalleePtr, GD);
6184}
6185
6187 if (DeviceKernelAttr::isOpenCLSpelling(FD->getAttr<DeviceKernelAttr>()))
6189 return GlobalDecl(FD);
6190}
6191
6193 E = E->IgnoreParens();
6194
6195 / Look through function-to-pointer decay.
6196 if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
6197 if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
6198 ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
6199 return EmitCallee(ICE->getSubExpr());
6200 }
6201
6202 / Try to remember the original __ptrauth qualifier for loads of
6203 / function pointers.
6204 if (ICE->getCastKind() == CK_LValueToRValue) {
6205 const Expr *SubExpr = ICE->getSubExpr();
6206 if (const auto *PtrType = SubExpr->getType()->getAs<PointerType>()) {
6207 std::pair<llvm::Value *, CGPointerAuthInfo> Result =
6209
6211 assert(FunctionType->isFunctionType());
6212
6213 GlobalDecl GD;
6214 if (const auto *VD =
6215 dyn_cast_or_null<VarDecl>(E->getReferencedDeclOfCallee())) {
6216 GD = GlobalDecl(VD);
6217 }
6219 CGCallee Callee(CalleeInfo, Result.first, Result.second);
6220 return Callee;
6221 }
6222 }
6223
6224 / Resolve direct calls.
6225 } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
6226 if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
6228 }
6229 } else if (auto ME = dyn_cast<MemberExpr>(E)) {
6230 if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
6231 EmitIgnoredExpr(ME->getBase());
6232 return EmitDirectCallee(*this, FD);
6233 }
6234
6235 / Look through template substitutions.
6236 } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
6237 return EmitCallee(NTTP->getReplacement());
6238
6239 / Treat pseudo-destructor calls differently.
6240 } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
6242 }
6243
6244 / Otherwise, we have an indirect reference.
6245 llvm::Value *calleePtr;
6247 if (auto ptrType = E->getType()->getAs<PointerType>()) {
6248 calleePtr = EmitScalarExpr(E);
6249 functionType = ptrType->getPointeeType();
6250 } else {
6251 functionType = E->getType();
6252 calleePtr = EmitLValue(E, KnownNonNull).getPointer(*this);
6253 }
6254 assert(functionType->isFunctionType());
6255
6256 GlobalDecl GD;
6257 if (const auto *VD =
6258 dyn_cast_or_null<VarDecl>(E->getReferencedDeclOfCallee()))
6259 GD = GlobalDecl(VD);
6260
6261 CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(), GD);
6262 CGPointerAuthInfo pointerAuth = CGM.getFunctionPointerAuthInfo(functionType);
6263 CGCallee callee(calleeInfo, calleePtr, pointerAuth);
6264 return callee;
6265}
6266
6268 / Comma expressions just emit their LHS then their RHS as an l-value.
6269 if (E->getOpcode() == BO_Comma) {
6270 EmitIgnoredExpr(E->getLHS());
6272 return EmitLValue(E->getRHS());
6273 }
6274
6275 if (E->getOpcode() == BO_PtrMemD ||
6276 E->getOpcode() == BO_PtrMemI)
6278
6279 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
6280
6281 / Create a Key Instructions source location atom group that covers both
6282 / LHS and RHS expressions. Nested RHS expressions may get subsequently
6283 / separately grouped (1 below):
6284 /
6285 / 1. `a = b = c` -> Two atoms.
6286 / 2. `x = new(1)` -> One atom (for both addr store and value store).
6287 / 3. Complex and agg assignment -> One atom.
6289
6290 / Note that in all of these cases, __block variables need the RHS
6291 / evaluated first just in case the variable gets moved by the RHS.
6292
6293 switch (getEvaluationKind(E->getType())) {
6294 case TEK_Scalar: {
6295 if (PointerAuthQualifier PtrAuth =
6296 E->getLHS()->getType().getPointerAuth()) {
6298 LValue CopiedLV = LV;
6299 CopiedLV.getQuals().removePointerAuth();
6300 llvm::Value *RV =
6301 EmitPointerAuthQualify(PtrAuth, E->getRHS(), CopiedLV.getAddress());
6302 EmitNullabilityCheck(CopiedLV, RV, E->getExprLoc());
6303 EmitStoreThroughLValue(RValue::get(RV), CopiedLV);
6304 return LV;
6305 }
6306
6307 switch (E->getLHS()->getType().getObjCLifetime()) {
6309 return EmitARCStoreStrong(E, /*ignored*/ false).first;
6310
6312 return EmitARCStoreAutoreleasing(E).first;
6313
6314 / No reason to do any of these differently.
6318 break;
6319 }
6320
6321 / TODO: Can we de-duplicate this code with the corresponding code in
6322 / CGExprScalar, similar to the way EmitCompoundAssignmentLValue works?
6323 RValue RV;
6324 llvm::Value *Previous = nullptr;
6325 QualType SrcType = E->getRHS()->getType();
6326 / Check if LHS is a bitfield, if RHS contains an implicit cast expression
6327 / we want to extract that value and potentially (if the bitfield sanitizer
6328 / is enabled) use it to check for an implicit conversion.
6329 if (E->getLHS()->refersToBitField()) {
6330 llvm::Value *RHS =
6332 RV = RValue::get(RHS);
6333 } else
6334 RV = EmitAnyExpr(E->getRHS());
6335
6337
6338 if (RV.isScalar())
6340
6341 if (LV.isBitField()) {
6342 llvm::Value *Result = nullptr;
6343 / If bitfield sanitizers are enabled we want to use the result
6344 / to check whether a truncation or sign change has occurred.
6345 if (SanOpts.has(SanitizerKind::ImplicitBitfieldConversion))
6347 else
6349
6350 / If the expression contained an implicit conversion, make sure
6351 / to use the value before the scalar conversion.
6352 llvm::Value *Src = Previous ? Previous : RV.getScalarVal();
6353 QualType DstType = E->getLHS()->getType();
6354 EmitBitfieldConversionCheck(Src, SrcType, Result, DstType,
6355 LV.getBitFieldInfo(), E->getExprLoc());
6356 } else
6357 EmitStoreThroughLValue(RV, LV);
6358
6359 if (getLangOpts().OpenMP)
6360 CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(*this,
6361 E->getLHS());
6362 return LV;
6363 }
6364
6365 case TEK_Complex:
6367
6368 case TEK_Aggregate:
6369 / If the lang opt is HLSL and the LHS is a constant array
6370 / then we are performing a copy assignment and call a special
6371 / function because EmitAggExprToLValue emits to a temporary LValue
6373 return EmitHLSLArrayAssignLValue(E);
6374
6375 return EmitAggExprToLValue(E);
6376 }
6377 llvm_unreachable("bad evaluation kind");
6378}
6379
6380/ This function implements trivial copy assignment for HLSL's
6381/ assignable constant arrays.
6383 / Don't emit an LValue for the RHS because it might not be an LValue
6384 LValue LHS = EmitLValue(E->getLHS());
6385
6386 / If the RHS is a global resource array, copy all individual resources
6387 / into LHS.
6389 if (CGM.getHLSLRuntime().emitResourceArrayCopy(LHS, E->getRHS(), *this))
6390 return LHS;
6391
6392 / In C the RHS of an assignment operator is an RValue.
6393 / EmitAggregateAssign takes an LValue for the RHS. Instead we can call
6394 / EmitInitializationToLValue to emit an RValue into an LValue.
6396 return LHS;
6397}
6398
6400 llvm::CallBase **CallOrInvoke) {
6401 RValue RV = EmitCallExpr(E, ReturnValueSlot(), CallOrInvoke);
6402
6403 if (!RV.isScalar())
6404 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
6406
6407 assert(E->getCallReturnType(getContext())->isReferenceType() &&
6408 "Can't have a scalar return unless the return type is a "
6409 "reference type!");
6410
6412}
6413
6415 / FIXME: This shouldn't require another copy.
6416 return EmitAggExprToLValue(E);
6417}
6418
6421 && "binding l-value to type which needs a temporary");
6422 AggValueSlot Slot = CreateAggTemp(E->getType());
6423 EmitCXXConstructExpr(E, Slot);
6425}
6426
6427LValue
6431
6433 return CGM.GetAddrOfMSGuidDecl(E->getGuidDecl())
6434 .withElementType(ConvertType(E->getType()));
6435}
6436
6441
6442LValue
6450
6453
6454 if (!RV.isScalar())
6455 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
6457
6458 assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
6459 "Can't have a scalar return unless the return type is a "
6460 "reference type!");
6461
6463}
6464
6466 Address V =
6467 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
6469}
6470
6472 const ObjCIvarDecl *Ivar) {
6473 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
6474}
6475
6476llvm::Value *
6478 const ObjCIvarDecl *Ivar) {
6479 llvm::Value *OffsetValue = EmitIvarOffset(Interface, Ivar);
6480 QualType PointerDiffType = getContext().getPointerDiffType();
6481 return Builder.CreateZExtOrTrunc(OffsetValue,
6482 getTypes().ConvertType(PointerDiffType));
6483}
6484
6486 llvm::Value *BaseValue,
6487 const ObjCIvarDecl *Ivar,
6488 unsigned CVRQualifiers) {
6489 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
6490 Ivar, CVRQualifiers);
6491}
6492
6494 / FIXME: A lot of the code below could be shared with EmitMemberExpr.
6495 llvm::Value *BaseValue = nullptr;
6496 const Expr *BaseExpr = E->getBase();
6497 Qualifiers BaseQuals;
6498 QualType ObjectTy;
6499 if (E->isArrow()) {
6500 BaseValue = EmitScalarExpr(BaseExpr);
6501 ObjectTy = BaseExpr->getType()->getPointeeType();
6502 BaseQuals = ObjectTy.getQualifiers();
6503 } else {
6504 LValue BaseLV = EmitLValue(BaseExpr);
6505 BaseValue = BaseLV.getPointer(*this);
6506 ObjectTy = BaseExpr->getType();
6507 BaseQuals = ObjectTy.getQualifiers();
6508 }
6509
6510 LValue LV =
6511 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
6512 BaseQuals.getCVRQualifiers());
6514 return LV;
6515}
6516
6518 / Can only get l-value for message expression returning aggregate type
6519 RValue RV = EmitAnyExprToTemp(E);
6520 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
6522}
6523
6525 const CGCallee &OrigCallee, const CallExpr *E,
6527 llvm::Value *Chain,
6528 llvm::CallBase **CallOrInvoke,
6529 CGFunctionInfo const **ResolvedFnInfo) {
6530 / Get the actual function type. The callee type will always be a pointer to
6531 / function type or a block pointer type.
6532 assert(CalleeType->isFunctionPointerType() &&
6533 "Call must have function pointer type!");
6534
6535 const Decl *TargetDecl =
6536 OrigCallee.getAbstractInfo().getCalleeDecl().getDecl();
6537
6538 assert((!isa_and_present<FunctionDecl>(TargetDecl) ||
6539 !cast<FunctionDecl>(TargetDecl)->isImmediateFunction()) &&
6540 "trying to emit a call to an immediate function");
6541
6542 CalleeType = getContext().getCanonicalType(CalleeType);
6543
6544 auto PointeeType = cast<PointerType>(CalleeType)->getPointeeType();
6545
6546 CGCallee Callee = OrigCallee;
6547
6548 if (SanOpts.has(SanitizerKind::Function) &&
6549 (!TargetDecl || !isa<FunctionDecl>(TargetDecl)) &&
6550 !isa<FunctionNoProtoType>(PointeeType)) {
6551 if (llvm::Constant *PrefixSig =
6552 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
6553 auto CheckOrdinal = SanitizerKind::SO_Function;
6554 auto CheckHandler = SanitizerHandler::FunctionTypeMismatch;
6555 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
6556 auto *TypeHash = getUBSanFunctionTypeHash(PointeeType);
6557
6558 llvm::Type *PrefixSigType = PrefixSig->getType();
6559 llvm::StructType *PrefixStructTy = llvm::StructType::get(
6560 CGM.getLLVMContext(), {PrefixSigType, Int32Ty}, /*isPacked=*/true);
6561
6562 llvm::Value *CalleePtr = Callee.getFunctionPointer();
6563 if (CGM.getCodeGenOpts().PointerAuth.FunctionPointers) {
6564 / Use raw pointer since we are using the callee pointer as data here.
6565 Address Addr =
6566 Address(CalleePtr, CalleePtr->getType(),
6568 CalleePtr->getPointerAlignment(CGM.getDataLayout())),
6569 Callee.getPointerAuthInfo(), nullptr);
6570 CalleePtr = Addr.emitRawPointer(*this);
6571 }
6572
6573 / On 32-bit Arm, the low bit of a function pointer indicates whether
6574 / it's using the Arm or Thumb instruction set. The actual first
6575 / instruction lives at the same address either way, so we must clear
6576 / that low bit before using the function address to find the prefix
6577 / structure.
6578 /
6579 / This applies to both Arm and Thumb target triples, because
6580 / either one could be used in an interworking context where it
6581 / might be passed function pointers of both types.
6582 llvm::Value *AlignedCalleePtr;
6583 if (CGM.getTriple().isARM() || CGM.getTriple().isThumb()) {
6584 llvm::Value *CalleeAddress =
6585 Builder.CreatePtrToInt(CalleePtr, IntPtrTy);
6586 llvm::Value *Mask = llvm::ConstantInt::get(IntPtrTy, ~1);
6587 llvm::Value *AlignedCalleeAddress =
6588 Builder.CreateAnd(CalleeAddress, Mask);
6589 AlignedCalleePtr =
6590 Builder.CreateIntToPtr(AlignedCalleeAddress, CalleePtr->getType());
6591 } else {
6592 AlignedCalleePtr = CalleePtr;
6593 }
6594
6595 llvm::Value *CalleePrefixStruct = AlignedCalleePtr;
6596 llvm::Value *CalleeSigPtr =
6597 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, -1, 0);
6598 llvm::Value *CalleeSig =
6599 Builder.CreateAlignedLoad(PrefixSigType, CalleeSigPtr, getIntAlign());
6600 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
6601
6602 llvm::BasicBlock *Cont = createBasicBlock("cont");
6603 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
6604 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
6605
6606 EmitBlock(TypeCheck);
6607 llvm::Value *CalleeTypeHash = Builder.CreateAlignedLoad(
6608 Int32Ty,
6609 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, -1, 1),
6610 getPointerAlign());
6611 llvm::Value *CalleeTypeHashMatch =
6612 Builder.CreateICmpEQ(CalleeTypeHash, TypeHash);
6613 llvm::Constant *StaticData[] = {EmitCheckSourceLocation(E->getBeginLoc()),
6614 EmitCheckTypeDescriptor(CalleeType)};
6615 EmitCheck(std::make_pair(CalleeTypeHashMatch, CheckOrdinal), CheckHandler,
6616 StaticData, {CalleePtr});
6617
6618 Builder.CreateBr(Cont);
6619 EmitBlock(Cont);
6620 }
6621 }
6622
6623 const auto *FnType = cast<FunctionType>(PointeeType);
6624
6625 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl);
6626 FD && DeviceKernelAttr::isOpenCLSpelling(FD->getAttr<DeviceKernelAttr>()))
6627 CGM.getTargetCodeGenInfo().setOCLKernelStubCallingConvention(FnType);
6628
6629 bool CFIUnchecked = CalleeType->hasPointeeToCFIUncheckedCalleeFunctionType();
6630
6631 / If we are checking indirect calls and this call is indirect, check that the
6632 / function pointer is a member of the bit set for the function type.
6633 if (SanOpts.has(SanitizerKind::CFIICall) &&
6634 (!TargetDecl || !isa<FunctionDecl>(TargetDecl)) && !CFIUnchecked) {
6635 auto CheckOrdinal = SanitizerKind::SO_CFIICall;
6636 auto CheckHandler = SanitizerHandler::CFICheckFail;
6637 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
6638 EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
6639
6640 llvm::Metadata *MD =
6641 CGM.CreateMetadataIdentifierForFnType(QualType(FnType, 0));
6642
6643 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
6644
6645 llvm::Value *CalleePtr = Callee.getFunctionPointer();
6646 llvm::Value *TypeTest = Builder.CreateCall(
6647 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CalleePtr, TypeId});
6648
6649 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
6650 llvm::Constant *StaticData[] = {
6651 llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
6654 };
6655 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
6656 EmitCfiSlowPathCheck(CheckOrdinal, TypeTest, CrossDsoTypeId, CalleePtr,
6657 StaticData);
6658 } else {
6659 EmitCheck(std::make_pair(TypeTest, CheckOrdinal), CheckHandler,
6660 StaticData, {CalleePtr, llvm::UndefValue::get(IntPtrTy)});
6661 }
6662 }
6663
6664 CallArgList Args;
6665 if (Chain)
6666 Args.add(RValue::get(Chain), CGM.getContext().VoidPtrTy);
6667
6668 / C++17 requires that we evaluate arguments to a call using assignment syntax
6669 / right-to-left, and that we evaluate arguments to certain other operators
6670 / left-to-right. Note that we allow this to override the order dictated by
6671 / the calling convention on the MS ABI, which means that parameter
6672 / destruction order is not necessarily reverse construction order.
6673 / FIXME: Revisit this based on C++ committee response to unimplementability.
6675 bool StaticOperator = false;
6676 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
6677 if (OCE->isAssignmentOp())
6679 else {
6680 switch (OCE->getOperator()) {
6681 case OO_LessLess:
6682 case OO_GreaterGreater:
6683 case OO_AmpAmp:
6684 case OO_PipePipe:
6685 case OO_Comma:
6686 case OO_ArrowStar:
6688 break;
6689 default:
6690 break;
6691 }
6692 }
6693
6694 if (const auto *MD =
6695 dyn_cast_if_present<CXXMethodDecl>(OCE->getCalleeDecl());
6696 MD && MD->isStatic())
6697 StaticOperator = true;
6698 }
6699
6700 auto Arguments = E->arguments();
6701 if (StaticOperator) {
6702 / If we're calling a static operator, we need to emit the object argument
6703 / and ignore it.
6704 EmitIgnoredExpr(E->getArg(0));
6705 Arguments = drop_begin(Arguments, 1);
6706 }
6707 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), Arguments,
6708 E->getDirectCallee(), /*ParamsToSkip=*/0, Order);
6709
6710 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
6711 Args, FnType, /*ChainCall=*/Chain);
6712
6713 if (ResolvedFnInfo)
6714 *ResolvedFnInfo = &FnInfo;
6715
6716 / HIP function pointer contains kernel handle when it is used in triple
6717 / chevron. The kernel stub needs to be loaded from kernel handle and used
6718 / as callee.
6719 if (CGM.getLangOpts().HIP && !CGM.getLangOpts().CUDAIsDevice &&
6721 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
6722 llvm::Value *Handle = Callee.getFunctionPointer();
6723 auto *Stub = Builder.CreateLoad(
6724 Address(Handle, Handle->getType(), CGM.getPointerAlign()));
6725 Callee.setFunctionPointer(Stub);
6726 }
6727 llvm::CallBase *LocalCallOrInvoke = nullptr;
6728 RValue Call = EmitCall(FnInfo, Callee, ReturnValue, Args, &LocalCallOrInvoke,
6729 E == MustTailCall, E->getExprLoc());
6730
6731 if (auto *CalleeDecl = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
6732 if (CalleeDecl->hasAttr<RestrictAttr>() ||
6733 CalleeDecl->hasAttr<MallocSpanAttr>() ||
6734 CalleeDecl->hasAttr<AllocSizeAttr>()) {
6735 / Function has 'malloc' (aka. 'restrict') or 'alloc_size' attribute.
6736 if (SanOpts.has(SanitizerKind::AllocToken)) {
6737 / Set !alloc_token metadata.
6738 EmitAllocToken(LocalCallOrInvoke, E);
6739 }
6740 }
6741 }
6742 if (CallOrInvoke)
6743 *CallOrInvoke = LocalCallOrInvoke;
6744
6745 return Call;
6746}
6747
6750 Address BaseAddr = Address::invalid();
6751 if (E->getOpcode() == BO_PtrMemI) {
6752 BaseAddr = EmitPointerWithAlignment(E->getLHS());
6753 } else {
6754 BaseAddr = EmitLValue(E->getLHS()).getAddress();
6755 }
6756
6757 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
6758 const auto *MPT = E->getRHS()->getType()->castAs<MemberPointerType>();
6759
6760 LValueBaseInfo BaseInfo;
6761 TBAAAccessInfo TBAAInfo;
6762 bool IsInBounds = !getLangOpts().PointerOverflowDefined &&
6765 E, BaseAddr, OffsetV, MPT, IsInBounds, &BaseInfo, &TBAAInfo);
6766
6767 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), BaseInfo, TBAAInfo);
6768}
6769
6770/ Given the address of a temporary variable, produce an r-value of
6771/ its type.
6773 QualType type,
6774 SourceLocation loc) {
6776 switch (getEvaluationKind(type)) {
6777 case TEK_Complex:
6778 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
6779 case TEK_Aggregate:
6780 return lvalue.asAggregateRValue();
6781 case TEK_Scalar:
6782 return RValue::get(EmitLoadOfScalar(lvalue, loc));
6783 }
6784 llvm_unreachable("bad evaluation kind");
6785}
6786
6787void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
6788 assert(Val->getType()->isFPOrFPVectorTy());
6789 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
6790 return;
6791
6792 llvm::MDBuilder MDHelper(getLLVMContext());
6793 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
6794
6795 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
6796}
6797
6799 llvm::Type *EltTy = Val->getType()->getScalarType();
6800 if (!EltTy->isFloatTy())
6801 return;
6802
6803 if ((getLangOpts().OpenCL &&
6804 !CGM.getCodeGenOpts().OpenCLCorrectlyRoundedDivSqrt) ||
6805 (getLangOpts().HIP && getLangOpts().CUDAIsDevice &&
6806 !CGM.getCodeGenOpts().HIPCorrectlyRoundedDivSqrt)) {
6807 / OpenCL v1.1 s7.4: minimum accuracy of single precision / is 3ulp
6808 /
6809 / OpenCL v1.2 s5.6.4.2: The -cl-fp32-correctly-rounded-divide-sqrt
6810 / build option allows an application to specify that single precision
6811 / floating-point divide (x/y and 1/x) and sqrt used in the program
6812 / source are correctly rounded.
6813 /
6814 / TODO: CUDA has a prec-sqrt flag
6815 SetFPAccuracy(Val, 3.0f);
6816 }
6817}
6818
6820 llvm::Type *EltTy = Val->getType()->getScalarType();
6821 if (!EltTy->isFloatTy())
6822 return;
6823
6824 if ((getLangOpts().OpenCL &&
6825 !CGM.getCodeGenOpts().OpenCLCorrectlyRoundedDivSqrt) ||
6826 (getLangOpts().HIP && getLangOpts().CUDAIsDevice &&
6827 !CGM.getCodeGenOpts().HIPCorrectlyRoundedDivSqrt)) {
6828 / OpenCL v1.1 s7.4: minimum accuracy of single precision / is 2.5ulp
6829 /
6830 / OpenCL v1.2 s5.6.4.2: The -cl-fp32-correctly-rounded-divide-sqrt
6831 / build option allows an application to specify that single precision
6832 / floating-point divide (x/y and 1/x) and sqrt used in the program
6833 / source are correctly rounded.
6834 /
6835 / TODO: CUDA has a prec-div flag
6836 SetFPAccuracy(Val, 2.5f);
6837 }
6838}
6839
6840namespace {
6841 struct LValueOrRValue {
6842 LValue LV;
6843 RValue RV;
6844 };
6845}
6846
6847static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
6848 const PseudoObjectExpr *E,
6849 bool forLValue,
6850 AggValueSlot slot) {
6852
6853 / Find the result expression, if any.
6854 const Expr *resultExpr = E->getResultExpr();
6855 LValueOrRValue result;
6856
6858 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
6859 const Expr *semantic = *i;
6860
6861 / If this semantic expression is an opaque value, bind it
6862 / to the result of its source expression.
6863 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
6864 / Skip unique OVEs.
6865 if (ov->isUnique()) {
6866 assert(ov != resultExpr &&
6867 "A unique OVE cannot be used as the result expression");
6868 continue;
6869 }
6870
6871 / If this is the result expression, we may need to evaluate
6872 / directly into the slot.
6874 OVMA opaqueData;
6875 if (ov == resultExpr && ov->isPRValue() && !forLValue &&
6877 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
6878 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
6880 opaqueData = OVMA::bind(CGF, ov, LV);
6881 result.RV = slot.asRValue();
6882
6883 / Otherwise, emit as normal.
6884 } else {
6885 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
6886
6887 / If this is the result, also evaluate the result now.
6888 if (ov == resultExpr) {
6889 if (forLValue)
6890 result.LV = CGF.EmitLValue(ov);
6891 else
6892 result.RV = CGF.EmitAnyExpr(ov, slot);
6893 }
6894 }
6895
6896 opaques.push_back(opaqueData);
6897
6898 / Otherwise, if the expression is the result, evaluate it
6899 / and remember the result.
6900 } else if (semantic == resultExpr) {
6901 if (forLValue)
6902 result.LV = CGF.EmitLValue(semantic);
6903 else
6904 result.RV = CGF.EmitAnyExpr(semantic, slot);
6905
6906 / Otherwise, evaluate the expression in an ignored context.
6907 } else {
6908 CGF.EmitIgnoredExpr(semantic);
6909 }
6910 }
6911
6912 / Unbind all the opaques now.
6913 for (CodeGenFunction::OpaqueValueMappingData &opaque : opaques)
6914 opaque.unbind(CGF);
6915
6916 return result;
6917}
6918
6920 AggValueSlot slot) {
6921 return emitPseudoObjectExpr(*this, E, false, slot).RV;
6922}
6923
6927
6929 LValue Val, SmallVectorImpl<LValue> &AccessList) {
6930
6932 std::tuple<LValue, QualType, llvm::SmallVector<llvm::Value *, 4>>, 16>
6933 WorkList;
6934 llvm::IntegerType *IdxTy = llvm::IntegerType::get(getLLVMContext(), 32);
6935 WorkList.push_back({Val, Val.getType(), {llvm::ConstantInt::get(IdxTy, 0)}});
6936
6937 while (!WorkList.empty()) {
6938 auto [LVal, T, IdxList] = WorkList.pop_back_val();
6939 T = T.getCanonicalType().getUnqualifiedType();
6940 assert(!isa<MatrixType>(T) && "Matrix types not yet supported in HLSL");
6941
6942 if (const auto *CAT = dyn_cast<ConstantArrayType>(T)) {
6943 uint64_t Size = CAT->getZExtSize();
6944 for (int64_t I = Size - 1; I > -1; I--) {
6945 llvm::SmallVector<llvm::Value *, 4> IdxListCopy = IdxList;
6946 IdxListCopy.push_back(llvm::ConstantInt::get(IdxTy, I));
6947 WorkList.emplace_back(LVal, CAT->getElementType(), IdxListCopy);
6948 }
6949 } else if (const auto *RT = dyn_cast<RecordType>(T)) {
6950 const RecordDecl *Record = RT->getDecl()->getDefinitionOrSelf();
6951 assert(!Record->isUnion() && "Union types not supported in flat cast.");
6952
6953 const CXXRecordDecl *CXXD = dyn_cast<CXXRecordDecl>(Record);
6954
6956 std::tuple<LValue, QualType, llvm::SmallVector<llvm::Value *, 4>>, 16>
6957 ReverseList;
6958 if (CXXD && CXXD->isStandardLayout())
6960
6961 / deal with potential base classes
6962 if (CXXD && !CXXD->isStandardLayout()) {
6963 if (CXXD->getNumBases() > 0) {
6964 assert(CXXD->getNumBases() == 1 &&
6965 "HLSL doesn't support multiple inheritance.");
6966 auto Base = CXXD->bases_begin();
6967 llvm::SmallVector<llvm::Value *, 4> IdxListCopy = IdxList;
6968 IdxListCopy.push_back(llvm::ConstantInt::get(
6969 IdxTy, 0)); / base struct should be at index zero
6970 ReverseList.emplace_back(LVal, Base->getType(), IdxListCopy);
6971 }
6972 }
6973
6974 const CGRecordLayout &Layout = CGM.getTypes().getCGRecordLayout(Record);
6975
6976 llvm::Type *LLVMT = ConvertTypeForMem(T);
6978 LValue RLValue;
6979 bool createdGEP = false;
6980 for (auto *FD : Record->fields()) {
6981 if (FD->isBitField()) {
6982 if (FD->isUnnamedBitField())
6983 continue;
6984 if (!createdGEP) {
6985 createdGEP = true;
6986 Address GEP = Builder.CreateInBoundsGEP(LVal.getAddress(), IdxList,
6987 LLVMT, Align, "gep");
6988 RLValue = MakeAddrLValue(GEP, T);
6989 }
6990 LValue FieldLVal = EmitLValueForField(RLValue, FD, true);
6991 ReverseList.push_back({FieldLVal, FD->getType(), {}});
6992 } else {
6993 llvm::SmallVector<llvm::Value *, 4> IdxListCopy = IdxList;
6994 IdxListCopy.push_back(
6995 llvm::ConstantInt::get(IdxTy, Layout.getLLVMFieldNo(FD)));
6996 ReverseList.emplace_back(LVal, FD->getType(), IdxListCopy);
6997 }
6998 }
6999
7000 std::reverse(ReverseList.begin(), ReverseList.end());
7001 llvm::append_range(WorkList, ReverseList);
7002 } else if (const auto *VT = dyn_cast<VectorType>(T)) {
7003 llvm::Type *LLVMT = ConvertTypeForMem(T);
7005 Address GEP = Builder.CreateInBoundsGEP(LVal.getAddress(), IdxList, LLVMT,
7006 Align, "vector.gep");
7007 LValue Base = MakeAddrLValue(GEP, T);
7008 for (unsigned I = 0, E = VT->getNumElements(); I < E; I++) {
7009 llvm::Constant *Idx = llvm::ConstantInt::get(IdxTy, I);
7010 LValue LV =
7011 LValue::MakeVectorElt(Base.getAddress(), Idx, VT->getElementType(),
7012 Base.getBaseInfo(), TBAAAccessInfo());
7013 AccessList.emplace_back(LV);
7014 }
7015 } else { / a scalar/builtin type
7016 if (!IdxList.empty()) {
7017 llvm::Type *LLVMT = ConvertTypeForMem(T);
7019 Address GEP = Builder.CreateInBoundsGEP(LVal.getAddress(), IdxList,
7020 LLVMT, Align, "gep");
7021 AccessList.emplace_back(MakeAddrLValue(GEP, T));
7022 } else / must be a bitfield we already created an lvalue for
7023 AccessList.emplace_back(LVal);
7024 }
7025 }
7026}
Defines the clang::ASTContext interface.
#define V(N, I)
This file provides some common utility functions for processing Lambda related AST Constructs.
Defines enum values for all the target-independent builtin functions.
static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E, LValue &LV, bool IsMemberAccess=false)
Definition CGExpr.cpp:2983
static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM)
Named Registers are named metadata pointing to the register name which will be read from/written to a...
Definition CGExpr.cpp:3252
static llvm::Value * emitHashMix(CGBuilderTy &Builder, llvm::Value *Acc, llvm::Value *Ptr)
Definition CGExpr.cpp:714
static const Expr * isSimpleArrayDecayOperand(const Expr *E)
isSimpleArrayDecayOperand - If the specified expr is a simple decay from an array to pointer,...
Definition CGExpr.cpp:4382
static bool getFieldOffsetInBits(CodeGenFunction &CGF, const RecordDecl *RD, const FieldDecl *Field, int64_t &Offset)
The offset of a field from the beginning of the record.
Definition CGExpr.cpp:4571
static bool hasBPFPreserveStaticOffset(const RecordDecl *D)
Definition CGExpr.cpp:4437
ConstantEmissionKind
Can we constant-emit a load of a reference to a variable of the given type?
Definition CGExpr.cpp:1898
@ CEK_AsReferenceOnly
Definition CGExpr.cpp:1900
@ CEK_AsValueOnly
Definition CGExpr.cpp:1902
@ CEK_None
Definition CGExpr.cpp:1899
@ CEK_AsValueOrReference
Definition CGExpr.cpp:1901
static bool isConstantEmittableObjectType(QualType type)
Given an object of the given canonical type, can we safely copy a value out of it based on its initia...
Definition CGExpr.cpp:1871
static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD, llvm::Value *ThisValue)
Definition CGExpr.cpp:3240
static std::optional< LValue > EmitLValueOrThrowExpression(CodeGenFunction &CGF, const Expr *Operand)
Emit the operand of a glvalue conditional operator.
Definition CGExpr.cpp:5622
static CheckRecoverableKind getRecoverableKind(SanitizerKind::SanitizerOrdinal Ordinal)
Definition CGExpr.cpp:3832
static llvm::Value * emitArraySubscriptGEP(CodeGenFunction &CGF, llvm::Type *elemType, llvm::Value *ptr, ArrayRef< llvm::Value * > indices, bool inbounds, bool signedIndices, SourceLocation loc, const llvm::Twine &name="arrayidx")
Definition CGExpr.cpp:4396
SmallVector< llvm::Value *, 8 > RecIndicesTy
Definition CGExpr.cpp:1154
static GlobalDecl getGlobalDeclForDirectCall(const FunctionDecl *FD)
Definition CGExpr.cpp:6186
static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF, const Expr *E, GlobalDecl GD)
Definition CGExpr.cpp:3227
static RawAddress MaybeConvertMatrixAddress(RawAddress Addr, CodeGenFunction &CGF, bool IsVector=true)
Definition CGExpr.cpp:2269
static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF, const PseudoObjectExpr *E, bool forLValue, AggValueSlot slot)
Definition CGExpr.cpp:6847
static Address wrapWithBPFPreserveStaticOffset(CodeGenFunction &CGF, Address &Addr)
Definition CGExpr.cpp:4453
static llvm::StringRef GetUBSanTrapForHandler(SanitizerHandler ID)
Definition CGExpr.cpp:91
static llvm::Value * getArrayIndexingBound(CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType, LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel)
If Base is known to point to the start of an array, return the length of that array.
Definition CGExpr.cpp:1006
static RValue EmitLoadOfMatrixLValue(LValue LV, SourceLocation Loc, CodeGenFunction &CGF)
Definition CGExpr.cpp:2373
static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type)
Definition CGExpr.cpp:1904
static Address emitAddrOfZeroSizeField(CodeGenFunction &CGF, Address Base, const FieldDecl *Field, bool IsInBounds)
Get the address of a zero-sized field within a record.
Definition CGExpr.cpp:5318
static QualType getConstantExprReferredType(const FullExpr *E, const ASTContext &Ctx)
Definition CGExpr.cpp:1703
static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base, const FieldDecl *field, bool IsInBounds)
Drill down to the storage of a field without walking into reference types.
Definition CGExpr.cpp:5335
static bool getRangeForType(CodeGenFunction &CGF, QualType Ty, llvm::APInt &Min, llvm::APInt &End, bool StrictEnums, bool IsBool)
Definition CGExpr.cpp:2043
static std::optional< int64_t > getOffsetDifferenceInBits(CodeGenFunction &CGF, const FieldDecl *FD1, const FieldDecl *FD2)
Returns the relative offset difference between FD1 and FD2.
Definition CGExpr.cpp:4602
static CGCallee EmitDirectCallee(CodeGenFunction &CGF, GlobalDecl GD)
Definition CGExpr.cpp:6134
static LValue EmitThreadPrivateVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr, llvm::Type *RealVarTy, SourceLocation Loc)
Definition CGExpr.cpp:3080
static bool getGEPIndicesToField(CodeGenFunction &CGF, const RecordDecl *RD, const FieldDecl *Field, RecIndicesTy &Indices)
Definition CGExpr.cpp:1156
static bool OnlyHasInlineBuiltinDeclaration(const FunctionDecl *FD)
Definition CGExpr.cpp:6127
static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF, const Expr *E, const VarDecl *VD)
Definition CGExpr.cpp:3176
static bool hasAnyVptr(const QualType Type, const ASTContext &Context)
Definition CGExpr.cpp:5364
static bool IsPreserveAIArrayBase(CodeGenFunction &CGF, const Expr *ArrayBase)
Given an array base, check whether its member access belongs to a record with preserve_access_index a...
Definition CGExpr.cpp:4466
static Address emitDeclTargetVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD, QualType T)
Definition CGExpr.cpp:3094
VariableTypeDescriptorKind
Definition CGExpr.cpp:76
@ TK_Float
A floating-point type.
Definition CGExpr.cpp:80
@ TK_Unknown
Any other type. The value representation is unspecified.
Definition CGExpr.cpp:84
@ TK_Integer
An integer type.
Definition CGExpr.cpp:78
@ TK_BitInt
An _BitInt(N) type.
Definition CGExpr.cpp:82
static void EmitStoreOfMatrixScalar(llvm::Value *value, LValue lvalue, bool isInit, CodeGenFunction &CGF)
Definition CGExpr.cpp:2294
static Address EmitPointerWithAlignment(const Expr *E, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo, KnownNonNull_t IsKnownNonNull, CodeGenFunction &CGF)
Definition CGExpr.cpp:1435
static Address emitPreserveStructAccess(CodeGenFunction &CGF, LValue base, Address addr, const FieldDecl *field)
Definition CGExpr.cpp:5351
const SanitizerHandlerInfo SanitizerHandlers[]
Definition CGExpr.cpp:3849
static void emitCheckHandlerCall(CodeGenFunction &CGF, llvm::FunctionType *FnType, ArrayRef< llvm::Value * > FnArgs, SanitizerHandler CheckHandler, CheckRecoverableKind RecoverKind, bool IsFatal, llvm::BasicBlock *ContBB, bool NoMerge)
Definition CGExpr.cpp:3855
static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base, LValueBaseInfo &BaseInfo, TBAAAccessInfo &TBAAInfo, QualType BaseTy, QualType ElTy, bool IsLowerBound)
Definition CGExpr.cpp:4922
static mlir::Value emitPointerArithmetic(CIRGenFunction &cgf, const BinOpInfo &op, bool isSubtraction)
Emit pointer + index arithmetic.
static Address createReferenceTemporary(CIRGenFunction &cgf, const MaterializeTemporaryExpr *m, const Expr *inner)
static bool isAAPCS(const TargetInfo &targetInfo)
Helper method to check if the underlying ABI is AAPCS.
static CharUnits getArrayElementAlign(CharUnits arrayAlign, mlir::Value idx, CharUnits eltSize)
static void pushTemporaryCleanup(CIRGenFunction &cgf, const MaterializeTemporaryExpr *m, const Expr *e, Address referenceTemporary)
static QualType getFixedSizeElementType(const ASTContext &astContext, const VariableArrayType *vla)
static bool canEmitSpuriousReferenceToVariable(CIRGenFunction &cgf, const DeclRefExpr *e, const VarDecl *vd)
Determine whether we can emit a reference to vd from the current context, despite not necessarily hav...
static DeclRefExpr * tryToConvertMemberExprToDeclRefExpr(CIRGenFunction &cgf, const MemberExpr *me)
FormatToken * Previous
The previous token in the unwrapped line.
static unsigned getCharWidth(tok::TokenKind kind, const TargetInfo &Target)
llvm::MachO::Record Record
Definition MachO.h:31
Defines the clang::Module class, which describes a module in the source code.
static const SanitizerMask AlwaysRecoverable
static const SanitizerMask Unrecoverable
#define LIST_SANITIZER_CHECKS
SanitizerHandler
Defines the SourceManager interface.
static QualType getPointeeType(const MemRegion *R)
a trap message and trap category.
const LValueBase getLValueBase() const
Definition APValue.cpp:983
bool isLValue() const
Definition APValue.h:472
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:220
SourceManager & getSourceManager()
Definition ASTContext.h:837
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
uint64_t getFieldOffset(const ValueDecl *FD) const
Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
Builtin::Context & BuiltinInfo
Definition ASTContext.h:778
const LangOptions & getLangOpts() const
Definition ASTContext.h:930
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
CanQualType BoolTy
llvm::DenseMap< const CXXMethodDecl *, CXXCastPath > LambdaCastPaths
For capturing lambdas with an explicit object parameter whose type is derived from the lambda type,...
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
const VariableArrayType * getAsVariableArrayType(QualType T) const
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType getCanonicalTagType(const TagDecl *TD) const
unsigned getTargetAddressSpace(LangAS AS) const
bool isSentinelNullExpr(const Expr *E)
uint64_t getCharWidth() const
Return the size of the character type, in bits.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Definition Expr.h:4287
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4465
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4471
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4477
This class represents BOTH the OpenMP Array Section and OpenACC 'subarray', with a boolean differenti...
Definition Expr.h:7105
Expr * getBase()
Get base of the array section.
Definition Expr.h:7183
Expr * getLength()
Get length of array section.
Definition Expr.h:7193
static QualType getBaseOriginalType(const Expr *Base)
Return original type of the base expression for array section.
Definition Expr.cpp:5266
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:7222
Expr * getLowerBound()
Get lower bound of array section.
Definition Expr.h:7187
bool isOpenACCArraySection() const
Definition Expr.h:7180
SourceLocation getColonLocFirst() const
Definition Expr.h:7214
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2721
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:2776
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition Expr.h:2750
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3722
QualType getElementType() const
Definition TypeBase.h:3734
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:3972
Expr * getLHS() const
Definition Expr.h:4022
SourceLocation getExprLoc() const
Definition Expr.h:4013
Expr * getRHS() const
Definition Expr.h:4024
static bool isAdditiveOp(Opcode Opc)
Definition Expr.h:4058
Opcode getOpcode() const
Definition Expr.h:4017
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8130
unsigned getNumBits() const
Definition TypeBase.h:8142
bool isPredefinedLibFunction(unsigned ID) const
Determines whether this builtin is a predefined libc/libm function, such as "malloc",...
Definition Builtins.h:320
Represents binding an expression to a temporary.
Definition ExprCXX.h:1493
CXXTemporary * getTemporary()
Definition ExprCXX.h:1511
const Expr * getSubExpr() const
Definition ExprCXX.h:1515
Represents a call to a C++ constructor.
Definition ExprCXX.h:1548
Represents a C++ destructor within a class.
Definition DeclCXX.h:2869
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition DeclCXX.h:1366
bool isStandardLayout() const
Determine whether this class is standard-layout per C++ [class]p7.
Definition DeclCXX.h:1225
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:602
base_class_iterator bases_begin()
Definition DeclCXX.h:615
bool isDynamicClass() const
Definition DeclCXX.h:574
bool hasDefinition() const
Definition DeclCXX.h:561
const CXXRecordDecl * getStandardLayoutBaseWithFields() const
If this is a standard-layout class or union, any and all data members will be declared in the same ty...
Definition DeclCXX.cpp:559
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
Definition ExprCXX.h:848
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition ExprCXX.h:1068
MSGuidDecl * getGuidDecl() const
Definition ExprCXX.h:1114
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2877
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3081
SourceLocation getBeginLoc() const
Definition Expr.h:3211
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3060
Expr * getCallee()
Definition Expr.h:3024
bool isCoroElideSafe() const
Definition Expr.h:3051
arg_range arguments()
Definition Expr.h:3129
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition Expr.cpp:1599
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3610
path_iterator path_begin()
Definition Expr.h:3680
CastKind getCastKind() const
Definition Expr.h:3654
bool changesVolatileQualification() const
Return.
Definition Expr.h:3744
path_iterator path_end()
Definition Expr.h:3681
Expr * getSubExpr()
Definition Expr.h:3660
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
CharUnits alignmentAtOffset(CharUnits offset) const
Given that this is a non-zero alignment value, what is the alignment at the given offset?
Definition CharUnits.h:207
llvm::MaybeAlign getAsMaybeAlign() const
getAsMaybeAlign - Returns Quantity as a valid llvm::Align or std::nullopt, Beware llvm::MaybeAlign as...
Definition CharUnits.h:194
llvm::Align getAsAlign() const
getAsAlign - Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit b...
Definition CharUnits.h:189
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition CharUnits.h:58
CharUnits alignmentOfArrayElement(CharUnits elementSize) const
Given that this is the alignment of the first element of an array, return the minimum alignment of an...
Definition CharUnits.h:214
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition CharUnits.h:53
@ None
Trap Messages are omitted.
@ Detailed
Trap Message includes more context (e.g.
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
Definition Address.h:128
llvm::Value * getBasePointer() const
Definition Address.h:198
static Address invalid()
Definition Address.h:176
llvm::Value * emitRawPointer(CodeGenFunction &CGF) const
Return the pointer contained in this class after authenticating it and adding offset to it if necessa...
Definition Address.h:253
CharUnits getAlignment() const
Definition Address.h:194
llvm::Type * getElementType() const
Return the type of the values stored in this address.
Definition Address.h:209
Address withPointer(llvm::Value *NewPointer, KnownNonNull_t IsKnownNonNull) const
Return address with different pointer, but same element type and alignment.
Definition Address.h:261
Address withElementType(llvm::Type *ElemTy) const
Return address with different element type, but same pointer and alignment.
Definition Address.h:276
Address withAlignment(CharUnits NewAlignment) const
Return address with different alignment, but same pointer and element type.
Definition Address.h:269
bool isValid() const
Definition Address.h:177
llvm::PointerType * getType() const
Return the type of the pointer value.
Definition Address.h:204
An aggregate value slot.
Definition CGValue.h:505
static AggValueSlot ignored()
ignored - Returns an aggregate value slot indicating that the aggregate value is being ignored.
Definition CGValue.h:573
Address getAddress() const
Definition CGValue.h:645
void setExternallyDestructed(bool destructed=true)
Definition CGValue.h:614
static AggValueSlot forLValue(const LValue &LV, IsDestructed_t isDestructed, NeedsGCBarriers_t needsGC, IsAliased_t isAliased, Overlap_t mayOverlap, IsZeroed_t isZeroed=IsNotZeroed, IsSanitizerChecked_t isChecked=IsNotSanitizerChecked)
Definition CGValue.h:603
static AggValueSlot forAddr(Address addr, Qualifiers quals, IsDestructed_t isDestructed, NeedsGCBarriers_t needsGC, IsAliased_t isAliased, Overlap_t mayOverlap, IsZeroed_t isZeroed=IsNotZeroed, IsSanitizerChecked_t isChecked=IsNotSanitizerChecked)
forAddr - Make a slot for an aggregate value.
Definition CGValue.h:588
RValue asRValue() const
Definition CGValue.h:667
A scoped helper to set the current source atom group for CGDebugInfo::addInstToCurrentSourceAtom.
A scoped helper to set the current debug location to the specified location or preferred location of ...
static ApplyDebugLocation CreateArtificial(CodeGenFunction &CGF)
Apply TemporaryLocation if it is valid.
Address CreateConstInBoundsByteGEP(Address Addr, CharUnits Offset, const llvm::Twine &Name="")
Given a pointer to i8, adjust it by a given constant offset.
Definition CGBuilder.h:309
Address CreateGEP(CodeGenFunction &CGF, Address Addr, llvm::Value *Index, const llvm::Twine &Name="")
Definition CGBuilder.h:296
Address CreateConstGEP2_32(Address Addr, unsigned Idx0, unsigned Idx1, const llvm::Twine &Name="")
Definition CGBuilder.h:335
Address CreateConstArrayGEP(Address Addr, uint64_t Index, const llvm::Twine &Name="")
Given addr = [n x T]* ... produce name = getelementptr inbounds addr, i64 0, i64 index where i64 is a...
Definition CGBuilder.h:245
Address CreateStructGEP(Address Addr, unsigned Index, const llvm::Twine &Name="")
Definition CGBuilder.h:223
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
Definition CGBuilder.h:112
Address CreateConstByteGEP(Address Addr, CharUnits Offset, const llvm::Twine &Name="")
Definition CGBuilder.h:319
Address CreatePreserveStructAccessIndex(Address Addr, unsigned Index, unsigned FieldIndex, llvm::MDNode *DbgInfo)
Definition CGBuilder.h:417
Address CreateAddrSpaceCast(Address Addr, llvm::Type *Ty, llvm::Type *ElementTy, const llvm::Twine &Name="")
Definition CGBuilder.h:193
virtual llvm::Function * getKernelStub(llvm::GlobalValue *Handle)=0
Get kernel stub by kernel handle.
virtual void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D, llvm::FunctionCallee Dtor, llvm::Constant *Addr)=0
Emit code to force the execution of a destructor during global teardown.
virtual LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD, QualType LValType)=0
Emit a reference to a non-local thread_local variable (including triggering the initialization of all...
virtual bool usesThreadWrapperFunction(const VarDecl *VD) const =0
Abstract information about a function or function prototype.
Definition CGCall.h:41
const GlobalDecl getCalleeDecl() const
Definition CGCall.h:59
All available information about a concrete callee.
Definition CGCall.h:63
CGCalleeInfo getAbstractInfo() const
Definition CGCall.h:180
const CXXPseudoDestructorExpr * getPseudoDestructorExpr() const
Definition CGCall.h:172
bool isPseudoDestructor() const
Definition CGCall.h:169
static CGCallee forBuiltin(unsigned builtinID, const FunctionDecl *builtinDecl)
Definition CGCall.h:123
unsigned getBuiltinID() const
Definition CGCall.h:164
static CGCallee forDirect(llvm::Constant *functionPtr, const CGCalleeInfo &abstractInfo=CGCalleeInfo())
Definition CGCall.h:137
bool isBuiltin() const
Definition CGCall.h:157
const FunctionDecl * getBuiltinDecl() const
Definition CGCall.h:160
static CGCallee forPseudoDestructor(const CXXPseudoDestructorExpr *E)
Definition CGCall.h:131
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
Definition CGDebugInfo.h:59
llvm::DIType * getOrCreateStandaloneType(QualType Ty, SourceLocation Loc)
Emit standalone debug info for a type.
llvm::DILocation * CreateTrapFailureMessageFor(llvm::DebugLoc TrapLocation, StringRef Category, StringRef FailureMsg)
Create a debug location from TrapLocation that adds an artificial inline frame where the frame name i...
llvm::DIType * getOrCreateRecordType(QualType Ty, SourceLocation L)
Emit record type's standalone debug info.
CGFunctionInfo - Class to encapsulate the information about a function definition.
virtual Address getAddrOfThreadPrivate(CodeGenFunction &CGF, const VarDecl *VD, Address VDAddr, SourceLocation Loc)
Returns address of the threadprivate variable for the current thread.
virtual ConstantAddress getAddrOfDeclareTargetVar(const VarDecl *VD)
Returns the address of the variable marked as declare target with link clause OR as declare target wi...
bool hasRequiresUnifiedSharedMemory() const
Return whether the unified_shared_memory has been specified.
CGRecordLayout - This class handles struct and union layout info while lowering AST types to LLVM typ...
const CGBitFieldInfo & getBitFieldInfo(const FieldDecl *FD) const
Return the BitFieldInfo that corresponds to the field FD.
unsigned getLLVMFieldNo(const FieldDecl *FD) const
Return llvm::StructType element number that corresponds to the field FD.
bool containsFieldDecl(const FieldDecl *FD) const
CallArgList - Type for representing both the value and type of arguments in a call.
Definition CGCall.h:274
void addWriteback(LValue srcLV, Address temporary, llvm::Value *toUse, const Expr *writebackExpr=nullptr)
Definition CGCall.h:320
void add(RValue rvalue, QualType type)
Definition CGCall.h:302
An object to manage conditionally-evaluated expressions.
llvm::BasicBlock * getStartingBlock() const
Returns a block which will be executed prior to each evaluation of the conditional code.
static ConstantEmission forValue(llvm::Constant *C)
static ConstantEmission forReference(llvm::Constant *C)
LValue getReferenceLValue(CodeGenFunction &CGF, const Expr *RefExpr) const
A non-RAII class containing all the information about a bound opaque value.
static OpaqueValueMappingData bind(CodeGenFunction &CGF, const OpaqueValueExpr *ov, const Expr *e)
An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
Enters a new scope for capturing cleanups, all of which will be executed once the scope is exited.
RAII object to set/unset CodeGenFunction::IsSanitizerScope.
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
LValue EmitMatrixSubscriptExpr(const MatrixSubscriptExpr *E)
Definition CGExpr.cpp:4902
LValue EmitCoawaitLValue(const CoawaitExpr *E)
llvm::Value * GetVTablePtr(Address This, llvm::Type *VTableTy, const CXXRecordDecl *VTableClass, VTableAuthMode AuthMode=VTableAuthMode::Authenticate)
GetVTablePtr - Return the Value of the vtable pointer member pointed to by This.
Definition CGClass.cpp:2752
llvm::Value * EmitObjCConsumeObject(QualType T, llvm::Value *Ptr)
Produce the code for a CK_ARCConsumeObject.
Definition CGObjC.cpp:2152
void EmitBoundsCheckImpl(const Expr *ArrayExpr, QualType ArrayBaseType, llvm::Value *IndexVal, QualType IndexType, llvm::Value *BoundsVal, QualType BoundsType, bool Accessed)
Definition CGExpr.cpp:1254
LValue EmitLoadOfReferenceLValue(LValue RefLVal)
Definition CGExpr.cpp:3149
void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock, llvm::BasicBlock *FalseBlock, uint64_t TrueCount, Stmt::Likelihood LH=Stmt::LH_None, const Expr *ConditionalOp=nullptr, const VarDecl *ConditionalDecl=nullptr)
EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g.
RValue EmitObjCMessageExpr(const ObjCMessageExpr *E, ReturnValueSlot Return=ReturnValueSlot())
Definition CGObjC.cpp:573
llvm::Value * emitBoolVecConversion(llvm::Value *SrcVec, unsigned NumElementsDst, const llvm::Twine &Name="")
void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest)
LValue EmitCXXConstructLValue(const CXXConstructExpr *E)
Definition CGExpr.cpp:6419
LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E)
Definition CGExpr.cpp:5725
std::pair< LValue, llvm::Value * > EmitARCStoreAutoreleasing(const BinaryOperator *e)
Definition CGObjC.cpp:3679
ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV, bool isInc, bool isPre)
Definition CGExpr.cpp:1335
void SetDivFPAccuracy(llvm::Value *Val)
Set the minimum required accuracy of the given sqrt operation based on CodeGenOpts.
Definition CGExpr.cpp:6819
SanitizerSet SanOpts
Sanitizers enabled for this function.
LValue EmitInitListLValue(const InitListExpr *E)
Definition CGExpr.cpp:5609
bool isUnderlyingBasePointerConstantNull(const Expr *E)
Check whether the underlying base pointer is a constant null.
Definition CGExpr.cpp:5186
void EmitARCInitWeak(Address addr, llvm::Value *value)
i8* @objc_initWeak(i8** addr, i8* value) Returns value.
Definition CGObjC.cpp:2663
RawAddress CreateIRTemp(QualType T, const Twine &Name="tmp")
CreateIRTemp - Create a temporary IR object of the given type, with appropriate alignment.
Definition CGExpr.cpp:183
LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E, bool Accessed=false)
Definition CGExpr.cpp:4682
static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts=false)
ContainsLabel - Return true if the statement contains a label in it.
LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E)
Definition CGExpr.cpp:6451
llvm::Value * GetCountedByFieldExprGEP(const Expr *Base, const FieldDecl *FD, const FieldDecl *CountDecl)
Definition CGExpr.cpp:1187
void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit)
EmitComplexExprIntoLValue - Emit the given expression of complex type and place its result into the s...
const CastExpr * CurCast
If a cast expression is being visited, this holds the current cast's expression.
llvm::Type * ConvertType(QualType T)
Address EmitCXXUuidofExpr(const CXXUuidofExpr *E)
Definition CGExpr.cpp:6432
void EmitSanitizerStatReport(llvm::SanitizerStatKind SSK)
CGCapturedStmtInfo * CapturedStmtInfo
RValue EmitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E)
ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc)
EmitLoadOfComplex - Load a complex number from the specified l-value.
llvm::Value * EmitARCRetain(QualType type, llvm::Value *value)
Produce the code to do a retain.
Definition CGObjC.cpp:2328
llvm::Value * EmitPointerAuthQualify(PointerAuthQualifier Qualifier, llvm::Value *Pointer, QualType ValueType, Address StorageAddress, bool IsKnownNonNull)
CleanupKind getARCCleanupKind()
Retrieves the default cleanup kind for an ARC cleanup.
void EmitAggFinalDestCopy(QualType Type, AggValueSlot Dest, const LValue &Src, ExprValueKind SrcKind)
EmitAggFinalDestCopy - Emit copy of the specified aggregate into destination address.
Address GetAddressOfBaseClass(Address Value, const CXXRecordDecl *Derived, CastExpr::path_const_iterator PathBegin, CastExpr::path_const_iterator PathEnd, bool NullCheckValue, SourceLocation Loc)
GetAddressOfBaseClass - This function will add the necessary delta to the load of 'this' and returns ...
Definition CGClass.cpp:286
LValue MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T)
Given a value of type T* that may not be to a complete object, construct an l-value with the natural ...
void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst)
Definition CGExpr.cpp:2848
RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue, llvm::CallBase **CallOrInvoke)
LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E)
Definition CGExpr.cpp:3615
void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint=true)
LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E)
Definition CGExpr.cpp:5582
RValue convertTempToRValue(Address addr, QualType type, SourceLocation Loc)
Given the address of a temporary variable, produce an r-value of its type.
Definition CGExpr.cpp:6772
LValue EmitObjCIsaExpr(const ObjCIsaExpr *E)
void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, llvm::Value **Result=nullptr)
EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints as EmitStoreThroughLValue.
Definition CGExpr.cpp:2769
llvm::Constant * EmitCheckSourceLocation(SourceLocation Loc)
Emit a description of a source location in a format suitable for passing to a runtime sanitizer handl...
Definition CGExpr.cpp:3767
LValue EmitCXXUuidofLValue(const CXXUuidofExpr *E)
Definition CGExpr.cpp:6437
llvm::Value * EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, bool isInc, bool isPre)
void SetSqrtFPAccuracy(llvm::Value *Val)
Set the minimum required accuracy of the given sqrt operation based on CodeGenOpts.
Definition CGExpr.cpp:6798
RValue EmitSimpleCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue, llvm::CallBase **CallOrInvoke=nullptr)
Emit a CallExpr without considering whether it might be a subclass.
Definition CGExpr.cpp:6116
static bool isNullPointerAllowed(TypeCheckKind TCK)
Determine whether the pointer type check TCK permits null pointers.
Definition CGExpr.cpp:723
RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e, AggValueSlot slot=AggValueSlot::ignored())
Definition CGExpr.cpp:6919
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
void addInstToCurrentSourceAtom(llvm::Instruction *KeyInstruction, llvm::Value *Backup)
See CGDebugInfo::addInstToCurrentSourceAtom.
unsigned getDebugInfoFIndex(const RecordDecl *Rec, unsigned FieldIndex)
Get the record field index as represented in debug info.
Definition CGExpr.cpp:5301
const LangOptions & getLangOpts() const
void EmitCfiCheckFail()
Emit a cross-DSO CFI failure handling function.
Definition CGExpr.cpp:4136
RValue EmitReferenceBindingToExpr(const Expr *E)
Emits a reference binding to the passed in expression.
Definition CGExpr.cpp:686
llvm::Value * EmitARCStoreStrong(LValue lvalue, llvm::Value *value, bool resultIgnored)
Store into a strong object.
Definition CGObjC.cpp:2545
LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E)
Definition CGExpr.cpp:6749
LValue EmitLValueForIvar(QualType ObjectTy, llvm::Value *Base, const ObjCIvarDecl *Ivar, unsigned CVRQualifiers)
Definition CGExpr.cpp:6485
Address GetAddressOfDerivedClass(Address Value, const CXXRecordDecl *Derived, CastExpr::path_const_iterator PathBegin, CastExpr::path_const_iterator PathEnd, bool NullCheckValue)
Definition CGClass.cpp:394
void EmitIgnoredConditionalOperator(const AbstractConditionalOperator *E)
Definition CGExpr.cpp:5707
void EmitCountedByBoundsChecking(const Expr *ArrayExpr, QualType ArrayType, Address ArrayInst, QualType IndexType, llvm::Value *IndexVal, bool Accessed, bool FlexibleArray)
EmitCountedByBoundsChecking - If the array being accessed has a "counted_by" attribute,...
Definition CGExpr.cpp:4632
Address EmitFieldAnnotations(const FieldDecl *D, Address V)
Emit field annotations for the given field & value.
void pushDestroy(QualType::DestructionKind dtorKind, Address addr, QualType type)
pushDestroy - Push the standard destructor for the given type as at least a normal cleanup.
Definition CGDecl.cpp:2278
void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue, bool capturedByInit)
Definition CGDecl.cpp:787
void EmitNullabilityCheck(LValue LHS, llvm::Value *RHS, SourceLocation Loc)
Given an assignment *LHS = RHS, emit a test that checks if RHS is nonnull, if LHS is marked _Nonnull.
Definition CGDecl.cpp:765
llvm::Value * EmitPointerAuthUnqualify(PointerAuthQualifier Qualifier, llvm::Value *Pointer, QualType PointerType, Address StorageAddress, bool IsKnownNonNull)
void EmitDeclRefExprDbgValue(const DeclRefExpr *E, const APValue &Init)
Address makeNaturalAddressForPointer(llvm::Value *Ptr, QualType T, CharUnits Alignment=CharUnits::Zero(), bool ForPointeeType=false, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
Construct an address with the natural alignment of T.
Address EmitLoadOfPointer(Address Ptr, const PointerType *PtrTy, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
Load a pointer with type PtrTy stored at address Ptr.
Definition CGExpr.cpp:3158
RValue EmitLoadOfGlobalRegLValue(LValue LV)
Load of global named registers are always calls to intrinsics.
Definition CGExpr.cpp:2572
void EmitVTablePtrCheckForCast(QualType T, Address Derived, bool MayBeNull, CFITypeCheckKind TCK, SourceLocation Loc)
Derived is the presumed address of an object of type T after a cast.
Definition CGClass.cpp:2895
TypeCheckKind
Situations in which we might emit a check for the suitability of a pointer or glvalue.
@ TCK_DowncastPointer
Checking the operand of a static_cast to a derived pointer type.
@ TCK_DowncastReference
Checking the operand of a static_cast to a derived reference type.
@ TCK_MemberAccess
Checking the object expression in a non-static data member access.
@ TCK_Store
Checking the destination of a store. Must be suitably sized and aligned.
@ TCK_UpcastToVirtualBase
Checking the operand of a cast to a virtual base object.
@ TCK_MemberCall
Checking the 'this' pointer for a call to a non-static member function.
@ TCK_DynamicOperation
Checking the operand of a dynamic_cast or a typeid expression.
@ TCK_ReferenceBinding
Checking the bound value in a reference binding.
@ TCK_Upcast
Checking the operand of a cast to a base object.
LValue EmitBinaryOperatorLValue(const BinaryOperator *E)
Definition CGExpr.cpp:6267
bool InNoMergeAttributedStmt
True if the current statement has nomerge attribute.
LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E)
const Decl * CurCodeDecl
CurCodeDecl - This is the inner-most code context, which includes blocks.
Destroyer * getDestroyer(QualType::DestructionKind destructionKind)
Definition CGDecl.cpp:2251
llvm::AssertingVH< llvm::Instruction > AllocaInsertPt
AllocaInsertPoint - This is an instruction in the entry block before which we prefer to insert alloca...
void maybeAttachRangeForLoad(llvm::LoadInst *Load, QualType Ty, SourceLocation Loc)
Definition CGExpr.cpp:2071
void EmitBitfieldConversionCheck(llvm::Value *Src, QualType SrcType, llvm::Value *Dst, QualType DstType, const CGBitFieldInfo &Info, SourceLocation Loc)
Emit a check that an [implicit] conversion of a bitfield.
LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e)
Definition CGExpr.cpp:6924
llvm::Constant * EmitCheckTypeDescriptor(QualType T)
Emit a description of a type in a format suitable for passing to a runtime sanitizer handler.
Definition CGExpr.cpp:3657
LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e)
Definition CGExpr.cpp:5965
llvm::Value * LoadPassedObjectSize(const Expr *E, QualType EltTy)
If E references a parameter with pass_object_size info or a constant array size modifier,...
Definition CGExpr.cpp:965
@ ForceLeftToRight
! Language semantics require left-to-right evaluation.
@ Default
! No language constraints on evaluation order.
@ ForceRightToLeft
! Language semantics require right-to-left evaluation.
llvm::Value * EmitIvarOffsetAsPointerDiff(const ObjCInterfaceDecl *Interface, const ObjCIvarDecl *Ivar)
Definition CGExpr.cpp:6477
RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E, ReturnValueSlot ReturnValue, llvm::CallBase **CallOrInvoke)
RValue EmitLoadOfAnyValue(LValue V, AggValueSlot Slot=AggValueSlot::ignored(), SourceLocation Loc={})
Like EmitLoadOfLValue but also handles complex and aggregate types.
Definition CGExpr.cpp:2381
LValue EmitLValueForField(LValue Base, const FieldDecl *Field, bool IsInBounds=true)
Definition CGExpr.cpp:5383
RawAddress CreateDefaultAlignTempAlloca(llvm::Type *Ty, const Twine &Name="tmp")
CreateDefaultAlignedTempAlloca - This creates an alloca with the default ABI alignment of the given L...
Definition CGExpr.cpp:176
const TargetInfo & getTarget() const
LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E)
bool isInConditionalBranch() const
isInConditionalBranch - Return true if we're currently emitting one branch or the other of a conditio...
Address EmitCXXMemberDataPointerAddress(const Expr *E, Address base, llvm::Value *memberPtr, const MemberPointerType *memberPtrType, bool IsInBounds, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
Emit the address of a field using a member data pointer.
Definition CGClass.cpp:150
LValue EmitHLSLOutArgExpr(const HLSLOutArgExpr *E, CallArgList &Args, QualType Ty)
Definition CGExpr.cpp:5988
static bool isVptrCheckRequired(TypeCheckKind TCK, QualType Ty)
Determine whether the pointer type check TCK requires a vptr check.
Definition CGExpr.cpp:728
CGCallee EmitCallee(const Expr *E)
Definition CGExpr.cpp:6192
void EmitIgnoredExpr(const Expr *E)
EmitIgnoredExpr - Emit an expression in a context which ignores the result.
Definition CGExpr.cpp:244
RValue EmitCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue=ReturnValueSlot(), llvm::CallBase **CallOrInvoke=nullptr)
Definition CGExpr.cpp:6066
RValue EmitLoadOfLValue(LValue V, SourceLocation Loc)
EmitLoadOfLValue - Given an expression that represents a value lvalue, this method emits the address ...
Definition CGExpr.cpp:2399
LValue EmitArraySectionExpr(const ArraySectionExpr *E, bool IsLowerBound=true)
Definition CGExpr.cpp:4961
Address GetAddrOfBlockDecl(const VarDecl *var)
llvm::Value * EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy, QualType DstTy, SourceLocation Loc)
Emit a conversion from the specified complex type to the specified destination type,...
void pushCleanupAfterFullExpr(CleanupKind Kind, As... A)
Queue a cleanup to be pushed after finishing the current full-expression, potentially with an active ...
void EmitCfiCheckStub()
Emit a stub for the cross-DSO CFI check function.
Definition CGExpr.cpp:4097
void pushFullExprCleanup(CleanupKind kind, As... A)
pushFullExprCleanup - Push a cleanup to be run at the end of the current full-expression.
void StartFunction(GlobalDecl GD, QualType RetTy, llvm::Function *Fn, const CGFunctionInfo &FnInfo, const FunctionArgList &Args, SourceLocation Loc=SourceLocation(), SourceLocation StartLoc=SourceLocation())
Emit code for the start of a function.
LValue EmitAggExprToLValue(const Expr *E)
EmitAggExprToLValue - Emit the computation of the specified expression of aggregate type into a tempo...
void SetFPAccuracy(llvm::Value *Val, float Accuracy)
SetFPAccuracy - Set the minimum required accuracy of the given floating point operation,...
Definition CGExpr.cpp:6787
Address mergeAddressesInConditionalExpr(Address LHS, Address RHS, llvm::BasicBlock *LHSBlock, llvm::BasicBlock *RHSBlock, llvm::BasicBlock *MergeBlock, QualType MergedType)
Address emitAddrOfImagComponent(Address complex, QualType complexType)
void EmitBoundsCheck(const Expr *ArrayExpr, const Expr *ArrayExprBase, llvm::Value *Index, QualType IndexType, bool Accessed)
Emit a check that Base points into an array object, which we can access at index Index.
Definition CGExpr.cpp:1238
llvm::Value * EvaluateExprAsBool(const Expr *E)
EvaluateExprAsBool - Perform the usual unary conversions on the specified expression and compare the ...
Definition CGExpr.cpp:225
LValue EmitPredefinedLValue(const PredefinedExpr *E)
Definition CGExpr.cpp:3620
void EmitCheck(ArrayRef< std::pair< llvm::Value *, SanitizerKind::SanitizerOrdinal > > Checked, SanitizerHandler Check, ArrayRef< llvm::Constant * > StaticArgs, ArrayRef< llvm::Value * > DynamicArgs, const TrapReason *TR=nullptr)
Create a basic block that will either trap or call a handler function in the UBSan runtime with the p...
Definition CGExpr.cpp:3915
LValue EmitDeclRefLValue(const DeclRefExpr *E)
Definition CGExpr.cpp:3324
LValue EmitStringLiteralLValue(const StringLiteral *E)
Definition CGExpr.cpp:3610
AggValueSlot CreateAggTemp(QualType T, const Twine &Name="tmp", RawAddress *Alloca=nullptr)
CreateAggTemp - Create a temporary memory object for the given aggregate type.
RValue getOrCreateOpaqueRValueMapping(const OpaqueValueExpr *e)
Given an opaque value expression, return its RValue mapping if it exists, otherwise create one.
Definition CGExpr.cpp:6019
RValue EmitAtomicLoad(LValue LV, SourceLocation SL, AggValueSlot Slot=AggValueSlot::ignored())
llvm::Value * emitScalarConstant(const ConstantEmission &Constant, Expr *E)
Definition CGExpr.cpp:2026
llvm::Value * getTypeSize(QualType Ty)
Returns calculated size of the specified type.
bool EmitLifetimeStart(llvm::Value *Addr)
Emit a lifetime.begin marker if some criteria are satisfied.
Definition CGDecl.cpp:1356
LValue EmitUnsupportedLValue(const Expr *E, const char *Name)
EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue an ErrorUnsupported style ...
Definition CGExpr.cpp:1623
LValue MakeRawAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment, AlignmentSource Source=AlignmentSource::Type)
Same as MakeAddrLValue above except that the pointer is known to be unsigned.
llvm::MDNode * buildAllocToken(QualType AllocType)
Build metadata used by the AllocToken instrumentation.
Definition CGExpr.cpp:1299
RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E, ReturnValueSlot ReturnValue, llvm::CallBase **CallOrInvoke=nullptr)
LValue EmitLValueForFieldInitialization(LValue Base, const FieldDecl *Field)
EmitLValueForFieldInitialization - Like EmitLValueForField, except that if the Field is a reference,...
Definition CGExpr.cpp:5557
llvm::Value * EmitToMemory(llvm::Value *Value, QualType Ty)
EmitToMemory - Change a scalar value from its value representation to its in-memory representation.
Definition CGExpr.cpp:2212
Address emitBlockByrefAddress(Address baseAddr, const VarDecl *V, bool followForward=true)
BuildBlockByrefAddress - Computes the location of the data in a variable which is declared as __block...
llvm::AllocaInst * CreateTempAlloca(llvm::Type *Ty, const Twine &Name="tmp", llvm::Value *ArraySize=nullptr)
CreateTempAlloca - This creates an alloca and inserts it into the entry block if ArraySize is nullptr...
Definition CGExpr.cpp:153
LValue getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e)
Given an opaque value expression, return its LValue mapping if it exists, otherwise create one.
Definition CGExpr.cpp:6005
bool EmitScalarRangeCheck(llvm::Value *Value, QualType Ty, SourceLocation Loc)
Check if the scalar Value is within the valid range for the given type Ty.
Definition CGExpr.cpp:2085
ComplexPairTy EmitComplexExpr(const Expr *E, bool IgnoreReal=false, bool IgnoreImag=false)
EmitComplexExpr - Emit the computation of the specified expression of complex type,...
RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, ReturnValueSlot ReturnValue, const CallArgList &Args, llvm::CallBase **CallOrInvoke, bool IsMustTail, SourceLocation Loc, bool IsVirtualFunctionPointerThunk=false)
EmitCall - Generate a call of the given function, expecting the given result type,...
Definition CGCall.cpp:5248
const TargetCodeGenInfo & getTargetHooks() const
llvm::ConstantInt * getUBSanFunctionTypeHash(QualType T) const
Return a type hash constant for a function instrumented by -fsanitize=function.
LValue EmitHLSLArrayAssignLValue(const BinaryOperator *E)
Definition CGExpr.cpp:6382
RawAddress CreateMemTempWithoutCast(QualType T, const Twine &Name="tmp")
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignmen without...
Definition CGExpr.cpp:217
void incrementProfileCounter(const Stmt *S, llvm::Value *StepV=nullptr)
Increment the profiler's counter for the given statement by StepV.
LValue EmitVAArgExprLValue(const VAArgExpr *E)
Definition CGExpr.cpp:6414
bool IsInPreservedAIRegion
True if CodeGen currently emits code inside presereved access index region.
RValue EmitAnyExprToTemp(const Expr *E)
EmitAnyExprToTemp - Similarly to EmitAnyExpr(), however, the result will always be accessible even if...
Definition CGExpr.cpp:285
VlaSizePair getVLASize(const VariableArrayType *vla)
Returns an LLVM value that corresponds to the size, in non-variably-sized elements,...
LValue EmitStmtExprLValue(const StmtExpr *E)
Definition CGExpr.cpp:6517
llvm::Value * EmitARCLoadWeakRetained(Address addr)
i8* @objc_loadWeakRetained(i8** addr)
Definition CGObjC.cpp:2643
llvm::CallInst * EmitNounwindRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
RawAddress CreateTempAllocaWithoutCast(llvm::Type *Ty, CharUnits align, const Twine &Name="tmp", llvm::Value *ArraySize=nullptr)
CreateTempAlloca - This creates a alloca and inserts it into the entry block.
Definition CGExpr.cpp:105
llvm::Value * EmitWithOriginalRHSBitfieldAssignment(const BinaryOperator *E, llvm::Value **Previous, QualType *SrcType)
Retrieve the implicit cast expression of the rhs in a binary operator expression by passing pointers ...
llvm::Value * EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty, SourceLocation Loc, AlignmentSource Source=AlignmentSource::Type, bool isNontemporal=false)
EmitLoadOfScalar - Load a scalar value from an address, taking care to appropriately convert from the...
void Destroyer(CodeGenFunction &CGF, Address addr, QualType ty)
void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit)
EmitStoreOfComplex - Store a complex number into the specified l-value.
LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E)
Definition CGExpr.cpp:6493
void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit=false)
EmitStoreThroughLValue - Store the specified rvalue into the specified lvalue, where both are guarant...
Definition CGExpr.cpp:2596
Address EmitArrayToPointerDecay(const Expr *Array, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
Definition CGExpr.cpp:4345
void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr, QualType type, Destroyer *destroyer, bool useEHCleanupForArray)
Definition CGDecl.cpp:2331
RValue EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID, const CallExpr *E, ReturnValueSlot ReturnValue)
RValue GetUndefRValue(QualType Ty)
GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
Definition CGExpr.cpp:1591
llvm::Instruction * getPostAllocaInsertPoint()
Return PostAllocaInsertPt.
void EmitAllocToken(llvm::CallBase *CB, QualType AllocType)
Emit and set additional metadata used by the AllocToken instrumentation.
Definition CGExpr.cpp:1313
LValue EmitComplexAssignmentLValue(const BinaryOperator *E)
Emit an l-value for an assignment (simple or compound) of complex type.
LValue EmitCastLValue(const CastExpr *E)
EmitCastLValue - Casts are never lvalues unless that cast is to a reference type.
Definition CGExpr.cpp:5775
llvm::Value * EmitPointerArithmetic(const BinaryOperator *BO, Expr *pointerOperand, llvm::Value *pointer, Expr *indexOperand, llvm::Value *index, bool isSubtraction)
Emit pointer + index arithmetic.
LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E)
Definition CGExpr.cpp:510
LValue EmitLoadOfPointerLValue(Address Ptr, const PointerType *PtrTy)
Definition CGExpr.cpp:3168
llvm::Value * EmitCheckValue(llvm::Value *V)
Convert a value into a format suitable for passing to a runtime sanitizer handler.
Definition CGExpr.cpp:3729
void EmitAnyExprToMem(const Expr *E, Address Location, Qualifiers Quals, bool IsInitializer)
EmitAnyExprToMem - Emits the code necessary to evaluate an arbitrary expression into the given memory...
Definition CGExpr.cpp:295
RValue EmitAnyExpr(const Expr *E, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
EmitAnyExpr - Emit code to compute the specified expression which can have any type.
Definition CGExpr.cpp:266
LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E)
Definition CGExpr.cpp:5125
llvm::DenseMap< const ValueDecl *, FieldDecl * > LambdaCaptureFields
RValue EmitUnsupportedRValue(const Expr *E, const char *Name)
EmitUnsupportedRValue - Emit a dummy r-value using the type of E and issue an ErrorUnsupported style ...
Definition CGExpr.cpp:1617
CleanupKind getCleanupKind(QualType::DestructionKind kind)
std::pair< LValue, LValue > EmitHLSLOutArgLValues(const HLSLOutArgExpr *E, QualType Ty)
Definition CGExpr.cpp:5971
LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E)
Definition CGExpr.cpp:6465
llvm::Type * ConvertTypeForMem(QualType T)
LValue EmitCallExprLValue(const CallExpr *E, llvm::CallBase **CallOrInvoke=nullptr)
Definition CGExpr.cpp:6399
RValue EmitLoadOfBitfieldLValue(LValue LV, SourceLocation Loc)
Definition CGExpr.cpp:2470
llvm::Value * EmitARCLoadWeak(Address addr)
i8* @objc_loadWeak(i8** addr) Essentially objc_autorelease(objc_loadWeakRetained(addr)).
Definition CGObjC.cpp:2636
LValue EmitLValueForLambdaField(const FieldDecl *Field)
Definition CGExpr.cpp:5295
void markStmtMaybeUsed(const Stmt *S)
CodeGenTypes & getTypes() const
static TypeEvaluationKind getEvaluationKind(QualType T)
getEvaluationKind - Return the TypeEvaluationKind of QualType T.
llvm::Value * EmitIvarOffset(const ObjCInterfaceDecl *Interface, const ObjCIvarDecl *Ivar)
Definition CGExpr.cpp:6471
bool IsSanitizerScope
True if CodeGen currently emits code implementing sanitizer checks.
void FlattenAccessAndTypeLValue(LValue LVal, SmallVectorImpl< LValue > &AccessList)
Definition CGExpr.cpp:6928
LValue EmitCoyieldLValue(const CoyieldExpr *E)
void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, LValue LV, QualType Type, SanitizerSet SkippedChecks=SanitizerSet(), llvm::Value *ArraySize=nullptr)
void EmitCfiSlowPathCheck(SanitizerKind::SanitizerOrdinal Ordinal, llvm::Value *Cond, llvm::ConstantInt *TypeId, llvm::Value *Ptr, ArrayRef< llvm::Constant * > StaticArgs)
Emit a slow path cross-DSO CFI check which calls __cfi_slowpath if Cond if false.
Definition CGExpr.cpp:4049
llvm::SmallVector< const ParmVarDecl *, 4 > FnArgs
Save Parameter Decl for coroutine.
void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType, Address Ptr)
Emits all the code to cause the given temporary to be cleaned up.
llvm::Value * authPointerToPointerCast(llvm::Value *ResultPtr, QualType SourceType, QualType DestType)
LValue EmitUnaryOpLValue(const UnaryOperator *E)
Definition CGExpr.cpp:3543
Address EmitPointerWithAlignment(const Expr *Addr, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
EmitPointerWithAlignment - Given an expression with a pointer type, emit the value and compute our be...
Definition CGExpr.cpp:1574
bool LValueIsSuitableForInlineAtomic(LValue Src)
An LValue is a candidate for having its loads and stores be made atomic if we are operating under /vo...
LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK)
Same as EmitLValue but additionally we generate checking code to guard against undefined behavior.
Definition CGExpr.cpp:1655
RawAddress CreateMemTemp(QualType T, const Twine &Name="tmp", RawAddress *Alloca=nullptr)
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignmen and cas...
Definition CGExpr.cpp:188
Address EmitLoadOfReference(LValue RefLVal, LValueBaseInfo *PointeeBaseInfo=nullptr, TBAAAccessInfo *PointeeTBAAInfo=nullptr)
Definition CGExpr.cpp:3116
RValue EmitRValueForField(LValue LV, const FieldDecl *FD, SourceLocation Loc)
Definition CGExpr.cpp:6038
llvm::Value * EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr)
Definition CGObjC.cpp:2160
LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E)
Definition CGExpr.cpp:6443
llvm::Type * convertTypeForLoadStore(QualType ASTTy, llvm::Type *LLVMTy=nullptr)
bool sanitizePerformTypeCheck() const
Whether any type-checking sanitizers are enabled.
Definition CGExpr.cpp:736
Address EmitExtVectorElementLValue(LValue V)
Generates lvalue for partial ext_vector access.
Definition CGExpr.cpp:2554
llvm::Value * EmitCheckedInBoundsGEP(llvm::Type *ElemTy, llvm::Value *Ptr, ArrayRef< llvm::Value * > IdxList, bool SignedIndices, bool IsSubtraction, SourceLocation Loc, const Twine &Name="")
Same as IRBuilder::CreateInBoundsGEP, but additionally emits a check to detect undefined behavior whe...
void EmitInitializationToLValue(const Expr *E, LValue LV, AggValueSlot::IsZeroed_t IsZeroed=AggValueSlot::IsNotZeroed)
EmitInitializationToLValue - Emit an initializer to an LValue.
Definition CGExpr.cpp:325
void EmitAggExpr(const Expr *E, AggValueSlot AS)
EmitAggExpr - Emit the computation of the specified expression of aggregate type.
Address emitAddrOfRealComponent(Address complex, QualType complexType)
llvm::Value * EmitScalarExpr(const Expr *E, bool IgnoreResultAssign=false)
EmitScalarExpr - Emit the computation of the specified expression of LLVM scalar type,...
RValue EmitLoadOfExtVectorElementLValue(LValue V)
Definition CGExpr.cpp:2507
static bool hasAggregateEvaluationKind(QualType T)
static bool IsWrappedCXXThis(const Expr *E)
Check if E is a C++ "this" pointer wrapped in value-preserving casts.
Definition CGExpr.cpp:1632
void EmitCallArgs(CallArgList &Args, PrototypeWrapper Prototype, llvm::iterator_range< CallExpr::const_arg_iterator > ArgRange, AbstractCallee AC=AbstractCallee(), unsigned ParamsToSkip=0, EvaluationOrder Order=EvaluationOrder::Default)
EmitCallArgs - Emit call arguments for a function.
Definition CGCall.cpp:4688
llvm::Value * EmitMatrixIndexExpr(const Expr *E)
Definition CGExpr.cpp:4894
llvm::CallInst * EmitTrapCall(llvm::Intrinsic::ID IntrID)
Emit a call to trap or debugtrap and attach function attribute "trap-func-name" if specified.
Definition CGExpr.cpp:4330
LValue MakeAddrLValue(Address Addr, QualType T, AlignmentSource Source=AlignmentSource::Type)
void EmitTrapCheck(llvm::Value *Checked, SanitizerHandler CheckHandlerID, bool NoMerge=false, const TrapReason *TR=nullptr)
Create a basic block that will call the trap intrinsic, and emit a conditional branch to it,...
Definition CGExpr.cpp:4257
void FinishFunction(SourceLocation EndLoc=SourceLocation())
FinishFunction - Complete IR generation of the current function.
void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit)
llvm::Value * EmitFromMemory(llvm::Value *Value, QualType Ty)
EmitFromMemory - Change a scalar value from its memory representation to its value representation.
Definition CGExpr.cpp:2242
uint64_t getProfileCount(const Stmt *S)
Get the profiler's count for the given statement.
llvm::Value * EmitLoadOfCountedByField(const Expr *Base, const FieldDecl *FD, const FieldDecl *CountDecl)
Build an expression accessing the "counted_by" field.
Definition CGExpr.cpp:1230
Address GetAddrOfLocalVar(const VarDecl *VD)
GetAddrOfLocalVar - Return the address of a local variable.
void EmitUnreachable(SourceLocation Loc)
Emit a reached-unreachable diagnostic if Loc is valid and runtime checking is enabled.
Definition CGExpr.cpp:4245
bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result, bool AllowLabels=false)
ConstantFoldsToSimpleInteger - If the specified expression does not fold to a constant,...
void ErrorUnsupported(const Stmt *S, const char *Type)
ErrorUnsupported - Print out an error that codegen doesn't support the specified stmt yet.
LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E)
Definition CGExpr.cpp:6428
llvm::Function * generateDestroyHelper(Address addr, QualType type, Destroyer *destroyer, bool useEHCleanupForArray, const VarDecl *VD)
generateDestroyHelper - Generates a helper function which, when invoked, destroys the given object.
LValue EmitMemberExpr(const MemberExpr *E)
Definition CGExpr.cpp:5193
std::pair< llvm::Value *, llvm::Value * > ComplexPairTy
Address ReturnValue
ReturnValue - The temporary alloca to hold the return value.
ConstantEmission tryEmitAsConstant(const DeclRefExpr *RefExpr)
Try to emit a reference to the given value without producing it as an l-value.
Definition CGExpr.cpp:1923
LValue EmitLValue(const Expr *E, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
EmitLValue - Emit code to compute a designator that specifies the location of the expression.
Definition CGExpr.cpp:1690
void EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst)
Store of global named registers are always calls to intrinsics.
Definition CGExpr.cpp:2958
bool isOpaqueValueEmitted(const OpaqueValueExpr *E)
isOpaqueValueEmitted - Return true if the opaque value expression has already been emitted.
Definition CGExpr.cpp:6032
std::pair< llvm::Value *, CGPointerAuthInfo > EmitOrigPointerRValue(const Expr *E)
Retrieve a pointer rvalue and its ptrauth info.
llvm::Value * EmitARCStoreWeak(Address addr, llvm::Value *value, bool ignored)
i8* @objc_storeWeak(i8** addr, i8* value) Returns value.
Definition CGObjC.cpp:2651
void EnsureInsertPoint()
EnsureInsertPoint - Ensure that an insertion point is defined so that emitted IR has a place to go.
llvm::LLVMContext & getLLVMContext()
RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue, llvm::CallBase **CallOrInvoke)
static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts)
getAccessedFieldNo - Given an encoded value and a result number, return the input field number being ...
Definition CGExpr.cpp:708
llvm::Value * EmitScalarConversion(llvm::Value *Src, QualType SrcTy, QualType DstTy, SourceLocation Loc)
Emit a conversion from the specified type to the specified destination type, both of which are LLVM s...
void EmitVariablyModifiedType(QualType Ty)
EmitVLASize - Capture all the sizes for the VLA expressions in the given variably-modified type and s...
static bool ShouldNullCheckClassCastValue(const CastExpr *Cast)
llvm::Value * EmitNonNullRValueCheck(RValue RV, QualType T)
Create a check that a scalar RValue is non-null.
Definition CGExpr.cpp:1584
void EmitStoreOfScalar(llvm::Value *Value, Address Addr, bool Volatile, QualType Ty, AlignmentSource Source=AlignmentSource::Type, bool isInit=false, bool isNontemporal=false)
EmitStoreOfScalar - Store a scalar value to an address, taking care to appropriately convert from the...
llvm::Value * EmitDynamicCast(Address V, const CXXDynamicCastExpr *DCE)
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition CGStmt.cpp:656
LValue MakeNaturalAlignRawAddrLValue(llvm::Value *V, QualType T)
llvm::Value * EmitCXXTypeidExpr(const CXXTypeidExpr *E)
This class organizes the cross-function state that is used while generating LLVM code.
void EmitExplicitCastExprType(const ExplicitCastExpr *E, CodeGenFunction *CGF=nullptr)
Emit type info if type of an expression is a variably modified type.
Definition CGExpr.cpp:1370
llvm::Module & getModule() const
llvm::FunctionCallee CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList(), bool Local=false, bool AssumeConvergent=false)
Create or return a runtime function declaration with the specified type and name.
llvm::Constant * getRawFunctionPointer(GlobalDecl GD, llvm::Type *Ty=nullptr)
Return a function pointer for a reference to the given function.
Definition CGExpr.cpp:3215
llvm::FunctionCallee getAddrAndTypeOfCXXStructor(GlobalDecl GD, const CGFunctionInfo *FnInfo=nullptr, llvm::FunctionType *FnType=nullptr, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Definition CGCXX.cpp:217
llvm::Constant * GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty=nullptr, bool ForVTable=false, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the given function.
llvm::Constant * getFunctionPointer(GlobalDecl GD, llvm::Type *Ty=nullptr)
Return the ABI-correct function pointer value for a reference to the given function.
const LangOptions & getLangOpts() const
CGCUDARuntime & getCUDARuntime()
Return a reference to the configured CUDA runtime.
CharUnits getNaturalTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, bool forPointeeType=false)
CGPointerAuthInfo getPointerAuthInfoForPointeeType(QualType type)
llvm::GlobalValue::LinkageTypes getLLVMLinkageVarDefinition(const VarDecl *VD)
Returns LLVM linkage for a declarator.
ConstantAddress GetWeakRefReference(const ValueDecl *VD)
Get a reference to the target of VD.
CGOpenMPRuntime & getOpenMPRuntime()
Return a reference to the configured OpenMP runtime.
TBAAAccessInfo getTBAAAccessInfo(QualType AccessType)
getTBAAAccessInfo - Get TBAA information that describes an access to an object of the given type.
ASTContext & getContext() const
TBAAAccessInfo mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo, TBAAAccessInfo TargetInfo)
mergeTBAAInfoForCast - Get merged TBAA information for the purposes of type casts.
llvm::Constant * GetAddrOfGlobalVar(const VarDecl *D, llvm::Type *Ty=nullptr, ForDefinition_t IsForDefinition=NotForDefinition)
Return the llvm::Constant for the address of the given global variable.
const CodeGenOptions & getCodeGenOpts() const
StringRef getMangledName(GlobalDecl GD)
CharUnits getNaturalPointeeTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
llvm::LLVMContext & getLLVMContext()
llvm::Function * getIntrinsic(unsigned IID, ArrayRef< llvm::Type * > Tys={})
ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E, const Expr *Inner)
Returns a pointer to a global variable representing a temporary with static or thread storage duratio...
LangAS GetGlobalConstantAddressSpace() const
Return the AST address space of constant literal, which is used to emit the constant literal as globa...
const CGRecordLayout & getCGRecordLayout(const RecordDecl *)
getCGRecordLayout - Return record layout info for the given record decl.
llvm::Type * ConvertTypeForMem(QualType T)
ConvertTypeForMem - Convert type T into a llvm::Type.
A specialization of Address that requires the address to be an LLVM Constant.
Definition Address.h:296
llvm::Constant * getPointer() const
Definition Address.h:308
llvm::Constant * emitAbstract(const Expr *E, QualType T)
Emit the result of the given expression as an abstract constant, asserting that it succeeded.
FunctionArgList - Type for representing both the decl and type of parameters to a function.
Definition CGCall.h:375
AlignmentSource getAlignmentSource() const
Definition CGValue.h:172
LValue - This represents an lvalue references.
Definition CGValue.h:183
bool isBitField() const
Definition CGValue.h:281
bool isMatrixElt() const
Definition CGValue.h:284
Expr * getBaseIvarExp() const
Definition CGValue.h:333
llvm::Constant * getExtVectorElts() const
Definition CGValue.h:410
static LValue MakeGlobalReg(llvm::Value *V, CharUnits alignment, QualType type)
Definition CGValue.h:479
bool isObjCStrong() const
Definition CGValue.h:325
bool isGlobalObjCRef() const
Definition CGValue.h:307
bool isVectorElt() const
Definition CGValue.h:280
bool isSimple() const
Definition CGValue.h:279
bool isVolatileQualified() const
Definition CGValue.h:286
RValue asAggregateRValue() const
Definition CGValue.h:499
llvm::Value * getPointer(CodeGenFunction &CGF) const
llvm::Value * getMatrixIdx() const
Definition CGValue.h:396
llvm::Value * getGlobalReg() const
Definition CGValue.h:431
static LValue MakeAddr(Address Addr, QualType type, ASTContext &Context, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
Definition CGValue.h:433
bool isVolatile() const
Definition CGValue.h:329
const Qualifiers & getQuals() const
Definition CGValue.h:339
bool isGlobalReg() const
Definition CGValue.h:283
static LValue MakeExtVectorElt(Address Addr, llvm::Constant *Elts, QualType type, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
Definition CGValue.h:453
bool isObjCWeak() const
Definition CGValue.h:322
Address getAddress() const
Definition CGValue.h:362
unsigned getVRQualifiers() const
Definition CGValue.h:288
LValue setKnownNonNull()
Definition CGValue.h:351
bool isNonGC() const
Definition CGValue.h:304
bool isExtVectorElt() const
Definition CGValue.h:282
llvm::Value * getVectorIdx() const
Definition CGValue.h:383
void setNontemporal(bool Value)
Definition CGValue.h:320
LValueBaseInfo getBaseInfo() const
Definition CGValue.h:347
void setARCPreciseLifetime(ARCPreciseLifetime_t value)
Definition CGValue.h:316
QualType getType() const
Definition CGValue.h:292
const CGBitFieldInfo & getBitFieldInfo() const
Definition CGValue.h:425
bool isThreadLocalRef() const
Definition CGValue.h:310
KnownNonNull_t isKnownNonNull() const
Definition CGValue.h:350
TBAAAccessInfo getTBAAInfo() const
Definition CGValue.h:336
void setNonGC(bool Value)
Definition CGValue.h:305
Address getVectorAddress() const
Definition CGValue.h:371
bool isNontemporal() const
Definition CGValue.h:319
static LValue MakeBitfield(Address Addr, const CGBitFieldInfo &Info, QualType type, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
Create a new object to represent a bit-field access.
Definition CGValue.h:469
bool isObjCIvar() const
Definition CGValue.h:298
static LValue MakeVectorElt(Address vecAddress, llvm::Value *Idx, QualType type, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
Definition CGValue.h:443
void setAddress(Address address)
Definition CGValue.h:364
Address getExtVectorAddress() const
Definition CGValue.h:402
static LValue MakeMatrixElt(Address matAddress, llvm::Value *Idx, QualType type, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
Definition CGValue.h:489
Address getMatrixAddress() const
Definition CGValue.h:388
Address getBitFieldAddress() const
Definition CGValue.h:416
RValue - This trivial value class is used to represent the result of an expression that is evaluated.
Definition CGValue.h:42
bool isScalar() const
Definition CGValue.h:64
static RValue get(llvm::Value *V)
Definition CGValue.h:99
static RValue getAggregate(Address addr, bool isVolatile=false)
Convert an Address to an RValue.
Definition CGValue.h:126
static RValue getComplex(llvm::Value *V1, llvm::Value *V2)
Definition CGValue.h:109
Address getAggregateAddress() const
getAggregateAddr() - Return the Value* of the address of the aggregate.
Definition CGValue.h:84
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
Definition CGValue.h:72
An abstract representation of an aligned address.
Definition Address.h:42
CharUnits getAlignment() const
Return the alignment of this pointer.
Definition Address.h:93
llvm::Type * getElementType() const
Return the type of the values stored in this address.
Definition Address.h:77
llvm::Value * getPointer() const
Definition Address.h:66
unsigned getAddressSpace() const
Return the address space that this address resides in.
Definition Address.h:83
ReturnValueSlot - Contains the address where the return value of a function can be stored,...
Definition CGCall.h:379
Address performAddrSpaceCast(CodeGen::CodeGenFunction &CGF, Address Addr, LangAS SrcAddr, llvm::Type *DestTy, bool IsNonNull=false) const
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3275
QualType getElementType() const
Definition TypeBase.h:3285
CompoundLiteralExpr - [C99 6.5.2.5].
Definition Expr.h:3539
bool isFileScope() const
Definition Expr.h:3571
const Expr * getInitializer() const
Definition Expr.h:3567
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4373
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4389
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1270
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition Expr.h:1474
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition Expr.cpp:484
ValueDecl * getDecl()
Definition Expr.h:1338
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition Expr.h:1468
SourceLocation getLocation() const
Definition Expr.h:1346
T * getAttr() const
Definition DeclBase.h:573
SourceLocation getLocation() const
Definition DeclBase.h:439
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition DeclBase.cpp:575
DeclContext * getDeclContext()
Definition DeclBase.h:448
bool hasAttr() const
Definition DeclBase.h:577
ExplicitCastExpr - An explicit cast written in the source code.
Definition Expr.h:3862
This represents one expression.
Definition Expr.h:112
const Expr * skipRValueSubobjectAdjustments(SmallVectorImpl< const Expr * > &CommaLHS, SmallVectorImpl< SubobjectAdjustment > &Adjustments) const
Walk outwards from an expression we want to bind a reference to and find the expression whose lifetim...
Definition Expr.cpp:80
bool isGLValue() const
Definition Expr.h:287
Expr * IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY
Skip past any parentheses and casts which do not change the value (including ptr->int casts of the sa...
Definition Expr.cpp:3113
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:444
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3086
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3074
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3082
bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsLValue - Evaluate an expression to see if we can fold it to an lvalue with link time known ...
bool isPRValue() const
Definition Expr.h:285
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:284
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
Decl * getReferencedDeclOfCallee()
Definition Expr.cpp:1542
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition Expr.cpp:3666
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3066
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:273
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h:476
QualType getType() const
Definition Expr.h:144
bool isOBJCGCCandidate(ASTContext &Ctx) const
isOBJCGCCandidate - Return true if this expression may be used in a read/ write barrier.
Definition Expr.cpp:2997
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
Definition Expr.h:6498
bool isArrow() const
isArrow - Return true if the base expression is a pointer to vector, return false if the base express...
Definition Expr.cpp:4411
void getEncodedElementAccess(SmallVectorImpl< uint32_t > &Elts) const
getEncodedElementAccess - Encode the elements accessed into an llvm aggregate Constant of ConstantInt...
Definition Expr.cpp:4443
const Expr * getBase() const
Definition Expr.h:6515
Represents a member of a struct/union/class.
Definition Decl.h:3160
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3263
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3245
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3396
const FieldDecl * findCountedByField() const
Find the FieldDecl specified in a FAM's "counted_by" attribute.
Definition Decl.cpp:4851
FullExpr - Represents a "full-expression" node.
Definition Expr.h:1049
const Expr * getSubExpr() const
Definition Expr.h:1062
Represents a function declaration or definition.
Definition Decl.h:2000
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3758
FunctionDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5254
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4450
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:57
const Decl * getDecl() const
Definition GlobalDecl.h:106
This class represents temporary values used to represent inout and out arguments in HLSL.
Definition Expr.h:7283
const OpaqueValueExpr * getCastedTemporary() const
Definition Expr.h:7334
const OpaqueValueExpr * getOpaqueArgLValue() const
Definition Expr.h:7315
bool isInOut() const
returns true if the parameter is inout and false if the parameter is out.
Definition Expr.h:7342
const Expr * getWritebackCast() const
Definition Expr.h:7329
const Expr * getArgLValue() const
Return the l-value expression that was written as the argument in source.
Definition Expr.h:7324
Describes an C or C++ initializer list.
Definition Expr.h:5233
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic,...
Definition Expr.cpp:2458
const Expr * getInit(unsigned Init) const
Definition Expr.h:5287
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition ExprCXX.h:4920
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition ExprCXX.h:4945
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
Definition ExprCXX.h:4937
ValueDecl * getExtendingDecl()
Get the declaration which triggered the lifetime-extension of this temporary, if any.
Definition ExprCXX.h:4970
MatrixSubscriptExpr - Matrix subscript expression for the MatrixType extension.
Definition Expr.h:2799
bool isIncomplete() const
Definition Expr.h:2819
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3298
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3381
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition Expr.h:3522
Expr * getBase() const
Definition Expr.h:3375
bool isArrow() const
Definition Expr.h:3482
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:3493
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3653
bool isObjCBOOLType(QualType T) const
Returns true if.
Definition NSAPI.cpp:481
This represents a decl that may have a name.
Definition Decl.h:274
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
A C++ nested-name-specifier augmented with source location information.
ObjCEncodeExpr, used for @encode in Objective-C.
Definition ExprObjC.h:407
Represents an ObjC class declaration.
Definition DeclObjC.h:1154
ObjCIvarDecl - Represents an ObjC instance variable.
Definition DeclObjC.h:1952
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition ExprObjC.h:546
ObjCIvarDecl * getDecl()
Definition ExprObjC.h:576
bool isArrow() const
Definition ExprObjC.h:584
const Expr * getBase() const
Definition ExprObjC.h:580
An expression that sends a message to the given Objective-C object or class.
Definition ExprObjC.h:937
const ObjCMethodDecl * getMethodDecl() const
Definition ExprObjC.h:1361
QualType getReturnType() const
Definition DeclObjC.h:329
ObjCSelectorExpr used for @selector in Objective-C.
Definition ExprObjC.h:452
Selector getSelector() const
Definition ExprObjC.h:466
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1178
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition Expr.h:1228
bool isUnique() const
Definition Expr.h:1236
const Expr * getSubExpr() const
Definition Expr.h:2199
Pointer-authentication qualifiers.
Definition TypeBase.h:152
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3328
QualType getPointeeType() const
Definition TypeBase.h:3338
[C99 6.4.2.2] - A predefined identifier such as func.
Definition Expr.h:2005
StringRef getIdentKindName() const
Definition Expr.h:2062
PredefinedIdentKind getIdentKind() const
Definition Expr.h:2040
StringLiteral * getFunctionName()
Definition Expr.h:2049
Represents an unpacked "presumed" location which can be presented to the user.
unsigned getColumn() const
Return the presumed column number of this location.
const char * getFilename() const
Return the presumed filename of this location.
unsigned getLine() const
Return the presumed line number of this location.
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition Expr.h:6690
semantics_iterator semantics_end()
Definition Expr.h:6755
semantics_iterator semantics_begin()
Definition Expr.h:6751
const Expr *const * const_semantics_iterator
Definition Expr.h:6750
Expr * getResultExpr()
Return the result-bearing expression, or null if there is none.
Definition Expr.h:6738
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8362
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:1453
QualType withoutLocalFastQualifiers() const
Definition TypeBase.h:1214
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8404
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8318
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1438
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition TypeBase.h:8463
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8372
QualType withCVRQualifiers(unsigned CVR) const
Definition TypeBase.h:1179
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1545
bool isConstantStorage(const ASTContext &Ctx, bool ExcludeCtor, bool ExcludeDtor)
Definition TypeBase.h:1036
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
unsigned getCVRQualifiers() const
Definition TypeBase.h:488
GC getObjCGCAttr() const
Definition TypeBase.h:519
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:361
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:354
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:350
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:364
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:367
bool hasConst() const
Definition TypeBase.h:457
void addCVRQualifiers(unsigned mask)
Definition TypeBase.h:502
void removeObjCGCAttr()
Definition TypeBase.h:523
void addQualifiers(Qualifiers Q)
Add the qualifiers from the given set to this set.
Definition TypeBase.h:650
void removePointerAuth()
Definition TypeBase.h:610
void setAddressSpace(LangAS space)
Definition TypeBase.h:591
bool hasVolatile() const
Definition TypeBase.h:467
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:603
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:545
Represents a struct/union/class.
Definition Decl.h:4321
field_range fields() const
Definition Decl.h:4524
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4505
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
PresumedLoc getPresumedLoc(SourceLocation Loc, bool UseLineDirectives=true) const
Returns the "presumed" location of a SourceLocation specifies.
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition Expr.h:4529
StmtClass getStmtClass() const
Definition Stmt.h:1483
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:350
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1799
bool isUnion() const
Definition Decl.h:3922
Exposes information about the current target.
Definition TargetInfo.h:226
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
virtual StringRef getABI() const
Get the ABI currently in use.
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isBlockPointerType() const
Definition TypeBase.h:8535
bool isVoidType() const
Definition TypeBase.h:8871
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2225
bool isPackedVectorBoolType(const ASTContext &ctx) const
Definition Type.cpp:418
bool hasAttr(attr::Kind AK) const
Determine whether this type had the specified attribute applied to it (looking through top-level type...
Definition Type.cpp:1951
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9167
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isConstantArrayType() const
Definition TypeBase.h:8618
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isArrayType() const
Definition TypeBase.h:8614
bool isFunctionPointerType() const
Definition TypeBase.h:8582
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isArithmeticType() const
Definition Type.cpp:2337
bool isConstantMatrixType() const
Definition TypeBase.h:8676
bool isPointerType() const
Definition TypeBase.h:8515
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:8915
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9158
bool isReferenceType() const
Definition TypeBase.h:8539
bool isEnumeralType() const
Definition TypeBase.h:8646
bool isVariableArrayType() const
Definition TypeBase.h:8626
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:752
bool isExtVectorBoolType() const
Definition TypeBase.h:8662
bool isBitIntType() const
Definition TypeBase.h:8780
bool isAnyComplexType() const
Definition TypeBase.h:8650
bool hasPointeeToCFIUncheckedCalleeFunctionType() const
Definition TypeBase.h:8567
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9044
bool isAtomicType() const
Definition TypeBase.h:8697
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2800
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2510
bool isHLSLResourceRecord() const
Definition Type.cpp:5362
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2435
bool isFunctionType() const
Definition TypeBase.h:8511
bool isObjCObjectPointerType() const
Definition TypeBase.h:8684
bool isVectorType() const
Definition TypeBase.h:8654
bool isAnyPointerType() const
Definition TypeBase.h:8523
bool isSubscriptableVectorType() const
Definition TypeBase.h:8668
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9091
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:653
bool isRecordType() const
Definition TypeBase.h:8642
bool isHLSLResourceRecordArray() const
Definition Type.cpp:5366
bool hasBooleanRepresentation() const
Determine whether this type has a boolean representation – i.e., it is a boolean type,...
Definition Type.cpp:2354
bool isCFIUncheckedCalleeFunctionType() const
Definition TypeBase.h:8561
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2244
SourceLocation getExprLoc() const
Definition Expr.h:2368
Expr * getSubExpr() const
Definition Expr.h:2285
Opcode getOpcode() const
Definition Expr.h:2280
Represents a call to the builtin function __builtin_va_arg.
Definition Expr.h:4891
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
QualType getType() const
Definition Decl.h:723
QualType getType() const
Definition Value.cpp:237
Represents a variable declaration or definition.
Definition Decl.h:926
TLSKind getTLSKind() const
Definition Decl.cpp:2175
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition Decl.cpp:2373
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1184
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition Decl.h:952
@ TLS_None
Not a TLS variable.
Definition Decl.h:946
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:3966
Represents a GCC generic vector type.
Definition TypeBase.h:4175
unsigned getNumElements() const
Definition TypeBase.h:4190
#define INT_MIN
Definition limits.h:55
Definition SPIR.cpp:35
AlignmentSource
The source of the alignment of an l-value; an expression of confidence in the alignment actually matc...
Definition CGValue.h:142
@ Type
The l-value was considered opaque, so the alignment was determined from a type.
Definition CGValue.h:155
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
Definition CGValue.h:146
bool isEmptyFieldForLayout(const ASTContext &Context, const FieldDecl *FD)
isEmptyFieldForLayout - Return true iff the field is "empty", that is, either a zero-width bit-field ...
@ EHCleanup
Denotes a cleanup that should run when a scope is exited using exceptional control flow (a throw stat...
@ ARCImpreciseLifetime
Definition CGValue.h:137
static AlignmentSource getFieldAlignmentSource(AlignmentSource Source)
Given that the base address has the given alignment source, what's our confidence in the alignment of...
Definition CGValue.h:160
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< ArrayType > arrayType
const AstTypeMatcher< FunctionType > functionType
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
std::optional< llvm::AllocTokenMetadata > getAllocTokenMetadata(QualType T, const ASTContext &Ctx)
Get the information required for construction of an allocation token ID.
QualType inferPossibleType(const CallExpr *E, const ASTContext &Ctx, const CastExpr *CastE)
Infer the possible allocated type from an allocation call expression.
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus
@ OK_BitField
A bitfield object is a bitfield on a C or C++ record.
Definition Specifiers.h:154
@ SC_Register
Definition Specifiers.h:257
Expr * Cond
};
@ Asm
Assembly: we accept this only so that we can preprocess it.
StorageDuration
The storage duration for an object (per C++ [basic.stc]).
Definition Specifiers.h:339
@ SD_Thread
Thread storage duration.
Definition Specifiers.h:342
@ SD_Static
Static storage duration.
Definition Specifiers.h:343
@ SD_FullExpression
Full-expression storage duration (for temporaries).
Definition Specifiers.h:340
@ SD_Automatic
Automatic storage duration (most local variables).
Definition Specifiers.h:341
@ SD_Dynamic
Dynamic storage duration.
Definition Specifiers.h:344
@ Result
The result type of a method or function.
Definition TypeBase.h:905
const FunctionProtoType * T
@ Dtor_Complete
Complete object dtor.
Definition ABI.h:36
LangAS
Defines the address space values used by the address space qualifier of QualType.
llvm::cl::opt< bool > ClSanitizeGuardChecks
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
Definition ASTContext.h:149
U cast(CodeGen::Address addr)
Definition Address.h:327
LangAS getLangASFromTargetAS(unsigned TargetAS)
@ Interface
The "__interface" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5858
bool isLambdaMethod(const DeclContext *DC)
Definition ASTLambda.h:39
@ Other
Other implicit parameter.
Definition Decl.h:1746
@ NOUR_Unevaluated
This name appears in an unevaluated operand.
Definition Specifiers.h:177
@ NOUR_Constant
This name appears as a potential result of an lvalue-to-rvalue conversion that is a constant expressi...
Definition Specifiers.h:180
__INTPTR_TYPE__ intptr_t
A signed integer type with the property that any valid pointer to void can be converted to this type,...
Structure with information about how a bitfield should be accessed.
CharUnits VolatileStorageOffset
The offset of the bitfield storage from the start of the struct.
unsigned VolatileOffset
The offset within a contiguous run of bitfields that are represented as a single "field" within the L...
unsigned Offset
The offset within a contiguous run of bitfields that are represented as a single "field" within the L...
unsigned VolatileStorageSize
The storage size in bits which should be used when accessing this bitfield.
unsigned Size
The total size of the bit-field, in bits.
unsigned StorageSize
The storage size in bits which should be used when accessing this bitfield.
unsigned IsSigned
Whether the bit-field is signed.
static Address getAddrOfThreadPrivate(CodeGenFunction &CGF, const VarDecl *VD, Address VDAddr, SourceLocation Loc)
Returns address of the threadprivate variable for the current thread.
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
unsigned char PointerWidthInBits
The width of a pointer into the generic address space.
llvm::MDNode * AccessType
AccessType - The final access type.
uint64_t Offset
Offset - The byte offset of the final access within the base one.
static TBAAAccessInfo getMayAliasInfo()
Definition CodeGenTBAA.h:63
uint64_t Size
Size - The size of access, in bytes.
llvm::MDNode * BaseType
BaseType - The base/leading access type.
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:645
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:647
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition Expr.h:612
void set(SanitizerMask K, bool Value)
Enable or disable a certain (single) sanitizer.
Definition Sanitizers.h:187
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.
Definition Sanitizers.h:174
An adjustment to be made to the temporary created when emitting a reference binding,...
Definition Expr.h:68

Follow Lee on X/Twitter - Father, Husband, Serial builder creating AI, crypto, games & web tools. We are friends :) AI Will Come To Life!

Check out: eBank.nz (Art Generator) | Netwrck.com (AI Tools) | Text-Generator.io (AI API) | BitBank.nz (Crypto AI) | ReadingTime (Kids Reading) | RewordGame | BigMultiplayerChess | WebFiddle | How.nz | Helix AI Assistant