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