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