clang  15.0.0git
CGObjC.cpp
Go to the documentation of this file.
1 //===---- CGObjC.cpp - Emit LLVM Code for Objective-C ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This contains code to emit Objective-C code as LLVM code.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "CGDebugInfo.h"
14 #include "CGObjCRuntime.h"
15 #include "CodeGenFunction.h"
16 #include "CodeGenModule.h"
17 #include "ConstantEmitter.h"
18 #include "TargetInfo.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/Attr.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/StmtObjC.h"
23 #include "clang/Basic/Diagnostic.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/Analysis/ObjCARCUtil.h"
27 #include "llvm/BinaryFormat/MachO.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/InlineAsm.h"
30 using namespace clang;
31 using namespace CodeGen;
32 
33 typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
34 static TryEmitResult
37  QualType ET,
38  RValue Result);
39 
40 /// Given the address of a variable of pointer type, find the correct
41 /// null to store into it.
42 static llvm::Constant *getNullForVariable(Address addr) {
43  llvm::Type *type = addr.getElementType();
44  return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
45 }
46 
47 /// Emits an instance of NSConstantString representing the object.
49 {
50  llvm::Constant *C =
52  // FIXME: This bitcast should just be made an invariant on the Runtime.
53  return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
54 }
55 
56 /// EmitObjCBoxedExpr - This routine generates code to call
57 /// the appropriate expression boxing method. This will either be
58 /// one of +[NSNumber numberWith<Type>:], or +[NSString stringWithUTF8String:],
59 /// or [NSValue valueWithBytes:objCType:].
60 ///
61 llvm::Value *
63  // Generate the correct selector for this literal's concrete type.
64  // Get the method.
65  const ObjCMethodDecl *BoxingMethod = E->getBoxingMethod();
66  const Expr *SubExpr = E->getSubExpr();
67 
69  ConstantEmitter ConstEmitter(CGM);
70  return ConstEmitter.tryEmitAbstract(E, E->getType());
71  }
72 
73  assert(BoxingMethod->isClassMethod() && "BoxingMethod must be a class method");
74  Selector Sel = BoxingMethod->getSelector();
75 
76  // Generate a reference to the class pointer, which will be the receiver.
77  // Assumes that the method was introduced in the class that should be
78  // messaged (avoids pulling it out of the result type).
79  CGObjCRuntime &Runtime = CGM.getObjCRuntime();
80  const ObjCInterfaceDecl *ClassDecl = BoxingMethod->getClassInterface();
81  llvm::Value *Receiver = Runtime.GetClass(*this, ClassDecl);
82 
83  CallArgList Args;
84  const ParmVarDecl *ArgDecl = *BoxingMethod->param_begin();
85  QualType ArgQT = ArgDecl->getType().getUnqualifiedType();
86 
87  // ObjCBoxedExpr supports boxing of structs and unions
88  // via [NSValue valueWithBytes:objCType:]
89  const QualType ValueType(SubExpr->getType().getCanonicalType());
90  if (ValueType->isObjCBoxableRecordType()) {
91  // Emit CodeGen for first parameter
92  // and cast value to correct type
93  Address Temporary = CreateMemTemp(SubExpr->getType());
94  EmitAnyExprToMem(SubExpr, Temporary, Qualifiers(), /*isInit*/ true);
95  llvm::Value *BitCast =
96  Builder.CreateBitCast(Temporary.getPointer(), ConvertType(ArgQT));
97  Args.add(RValue::get(BitCast), ArgQT);
98 
99  // Create char array to store type encoding
100  std::string Str;
101  getContext().getObjCEncodingForType(ValueType, Str);
102  llvm::Constant *GV = CGM.GetAddrOfConstantCString(Str).getPointer();
103 
104  // Cast type encoding to correct type
105  const ParmVarDecl *EncodingDecl = BoxingMethod->parameters()[1];
106  QualType EncodingQT = EncodingDecl->getType().getUnqualifiedType();
107  llvm::Value *Cast = Builder.CreateBitCast(GV, ConvertType(EncodingQT));
108 
109  Args.add(RValue::get(Cast), EncodingQT);
110  } else {
111  Args.add(EmitAnyExpr(SubExpr), ArgQT);
112  }
113 
114  RValue result = Runtime.GenerateMessageSend(
115  *this, ReturnValueSlot(), BoxingMethod->getReturnType(), Sel, Receiver,
116  Args, ClassDecl, BoxingMethod);
117  return Builder.CreateBitCast(result.getScalarVal(),
118  ConvertType(E->getType()));
119 }
120 
122  const ObjCMethodDecl *MethodWithObjects) {
123  ASTContext &Context = CGM.getContext();
124  const ObjCDictionaryLiteral *DLE = nullptr;
125  const ObjCArrayLiteral *ALE = dyn_cast<ObjCArrayLiteral>(E);
126  if (!ALE)
127  DLE = cast<ObjCDictionaryLiteral>(E);
128 
129  // Optimize empty collections by referencing constants, when available.
130  uint64_t NumElements =
131  ALE ? ALE->getNumElements() : DLE->getNumElements();
132  if (NumElements == 0 && CGM.getLangOpts().ObjCRuntime.hasEmptyCollections()) {
133  StringRef ConstantName = ALE ? "__NSArray0__" : "__NSDictionary0__";
135  llvm::Constant *Constant =
136  CGM.CreateRuntimeVariable(ConvertType(IdTy), ConstantName);
137  LValue LV = MakeNaturalAlignAddrLValue(Constant, IdTy);
138  llvm::Value *Ptr = EmitLoadOfScalar(LV, E->getBeginLoc());
139  cast<llvm::LoadInst>(Ptr)->setMetadata(
140  CGM.getModule().getMDKindID("invariant.load"),
141  llvm::MDNode::get(getLLVMContext(), None));
142  return Builder.CreateBitCast(Ptr, ConvertType(E->getType()));
143  }
144 
145  // Compute the type of the array we're initializing.
146  llvm::APInt APNumElements(Context.getTypeSize(Context.getSizeType()),
147  NumElements);
148  QualType ElementType = Context.getObjCIdType().withConst();
149  QualType ElementArrayType
150  = Context.getConstantArrayType(ElementType, APNumElements, nullptr,
151  ArrayType::Normal, /*IndexTypeQuals=*/0);
152 
153  // Allocate the temporary array(s).
154  Address Objects = CreateMemTemp(ElementArrayType, "objects");
155  Address Keys = Address::invalid();
156  if (DLE)
157  Keys = CreateMemTemp(ElementArrayType, "keys");
158 
159  // In ARC, we may need to do extra work to keep all the keys and
160  // values alive until after the call.
161  SmallVector<llvm::Value *, 16> NeededObjects;
162  bool TrackNeededObjects =
163  (getLangOpts().ObjCAutoRefCount &&
164  CGM.getCodeGenOpts().OptimizationLevel != 0);
165 
166  // Perform the actual initialialization of the array(s).
167  for (uint64_t i = 0; i < NumElements; i++) {
168  if (ALE) {
169  // Emit the element and store it to the appropriate array slot.
170  const Expr *Rhs = ALE->getElement(i);
172  ElementType, AlignmentSource::Decl);
173 
174  llvm::Value *value = EmitScalarExpr(Rhs);
175  EmitStoreThroughLValue(RValue::get(value), LV, true);
176  if (TrackNeededObjects) {
177  NeededObjects.push_back(value);
178  }
179  } else {
180  // Emit the key and store it to the appropriate array slot.
181  const Expr *Key = DLE->getKeyValueElement(i).Key;
183  ElementType, AlignmentSource::Decl);
184  llvm::Value *keyValue = EmitScalarExpr(Key);
185  EmitStoreThroughLValue(RValue::get(keyValue), KeyLV, /*isInit=*/true);
186 
187  // Emit the value and store it to the appropriate array slot.
188  const Expr *Value = DLE->getKeyValueElement(i).Value;
189  LValue ValueLV = MakeAddrLValue(Builder.CreateConstArrayGEP(Objects, i),
190  ElementType, AlignmentSource::Decl);
191  llvm::Value *valueValue = EmitScalarExpr(Value);
192  EmitStoreThroughLValue(RValue::get(valueValue), ValueLV, /*isInit=*/true);
193  if (TrackNeededObjects) {
194  NeededObjects.push_back(keyValue);
195  NeededObjects.push_back(valueValue);
196  }
197  }
198  }
199 
200  // Generate the argument list.
201  CallArgList Args;
202  ObjCMethodDecl::param_const_iterator PI = MethodWithObjects->param_begin();
203  const ParmVarDecl *argDecl = *PI++;
204  QualType ArgQT = argDecl->getType().getUnqualifiedType();
205  Args.add(RValue::get(Objects.getPointer()), ArgQT);
206  if (DLE) {
207  argDecl = *PI++;
208  ArgQT = argDecl->getType().getUnqualifiedType();
209  Args.add(RValue::get(Keys.getPointer()), ArgQT);
210  }
211  argDecl = *PI;
212  ArgQT = argDecl->getType().getUnqualifiedType();
213  llvm::Value *Count =
214  llvm::ConstantInt::get(CGM.getTypes().ConvertType(ArgQT), NumElements);
215  Args.add(RValue::get(Count), ArgQT);
216 
217  // Generate a reference to the class pointer, which will be the receiver.
218  Selector Sel = MethodWithObjects->getSelector();
219  QualType ResultType = E->getType();
220  const ObjCObjectPointerType *InterfacePointerType
221  = ResultType->getAsObjCInterfacePointerType();
222  ObjCInterfaceDecl *Class
223  = InterfacePointerType->getObjectType()->getInterface();
224  CGObjCRuntime &Runtime = CGM.getObjCRuntime();
225  llvm::Value *Receiver = Runtime.GetClass(*this, Class);
226 
227  // Generate the message send.
228  RValue result = Runtime.GenerateMessageSend(
229  *this, ReturnValueSlot(), MethodWithObjects->getReturnType(), Sel,
230  Receiver, Args, Class, MethodWithObjects);
231 
232  // The above message send needs these objects, but in ARC they are
233  // passed in a buffer that is essentially __unsafe_unretained.
234  // Therefore we must prevent the optimizer from releasing them until
235  // after the call.
236  if (TrackNeededObjects) {
237  EmitARCIntrinsicUse(NeededObjects);
238  }
239 
240  return Builder.CreateBitCast(result.getScalarVal(),
241  ConvertType(E->getType()));
242 }
243 
246 }
247 
249  const ObjCDictionaryLiteral *E) {
251 }
252 
253 /// Emit a selector.
255  // Untyped selector.
256  // Note that this implementation allows for non-constant strings to be passed
257  // as arguments to @selector(). Currently, the only thing preventing this
258  // behaviour is the type checking in the front end.
259  return CGM.getObjCRuntime().GetSelector(*this, E->getSelector());
260 }
261 
263  // FIXME: This should pass the Decl not the name.
264  return CGM.getObjCRuntime().GenerateProtocolRef(*this, E->getProtocol());
265 }
266 
267 /// Adjust the type of an Objective-C object that doesn't match up due
268 /// to type erasure at various points, e.g., related result types or the use
269 /// of parameterized classes.
271  RValue Result) {
272  if (!ExpT->isObjCRetainableType())
273  return Result;
274 
275  // If the converted types are the same, we're done.
276  llvm::Type *ExpLLVMTy = CGF.ConvertType(ExpT);
277  if (ExpLLVMTy == Result.getScalarVal()->getType())
278  return Result;
279 
280  // We have applied a substitution. Cast the rvalue appropriately.
281  return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
282  ExpLLVMTy));
283 }
284 
285 /// Decide whether to extend the lifetime of the receiver of a
286 /// returns-inner-pointer message.
287 static bool
289  switch (message->getReceiverKind()) {
290 
291  // For a normal instance message, we should extend unless the
292  // receiver is loaded from a variable with precise lifetime.
294  const Expr *receiver = message->getInstanceReceiver();
295 
296  // Look through OVEs.
297  if (auto opaque = dyn_cast<OpaqueValueExpr>(receiver)) {
298  if (opaque->getSourceExpr())
299  receiver = opaque->getSourceExpr()->IgnoreParens();
300  }
301 
302  const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver);
303  if (!ice || ice->getCastKind() != CK_LValueToRValue) return true;
304  receiver = ice->getSubExpr()->IgnoreParens();
305 
306  // Look through OVEs.
307  if (auto opaque = dyn_cast<OpaqueValueExpr>(receiver)) {
308  if (opaque->getSourceExpr())
309  receiver = opaque->getSourceExpr()->IgnoreParens();
310  }
311 
312  // Only __strong variables.
313  if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
314  return true;
315 
316  // All ivars and fields have precise lifetime.
317  if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver))
318  return false;
319 
320  // Otherwise, check for variables.
321  const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr());
322  if (!declRef) return true;
323  const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl());
324  if (!var) return true;
325 
326  // All variables have precise lifetime except local variables with
327  // automatic storage duration that aren't specially marked.
328  return (var->hasLocalStorage() &&
329  !var->hasAttr<ObjCPreciseLifetimeAttr>());
330  }
331 
334  // It's never necessary for class objects.
335  return false;
336 
338  // We generally assume that 'self' lives throughout a method call.
339  return false;
340  }
341 
342  llvm_unreachable("invalid receiver kind");
343 }
344 
345 /// Given an expression of ObjC pointer type, check whether it was
346 /// immediately loaded from an ARC __weak l-value.
347 static const Expr *findWeakLValue(const Expr *E) {
348  assert(E->getType()->isObjCRetainableType());
349  E = E->IgnoreParens();
350  if (auto CE = dyn_cast<CastExpr>(E)) {
351  if (CE->getCastKind() == CK_LValueToRValue) {
352  if (CE->getSubExpr()->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
353  return CE->getSubExpr();
354  }
355  }
356 
357  return nullptr;
358 }
359 
360 /// The ObjC runtime may provide entrypoints that are likely to be faster
361 /// than an ordinary message send of the appropriate selector.
362 ///
363 /// The entrypoints are guaranteed to be equivalent to just sending the
364 /// corresponding message. If the entrypoint is implemented naively as just a
365 /// message send, using it is a trade-off: it sacrifices a few cycles of
366 /// overhead to save a small amount of code. However, it's possible for
367 /// runtimes to detect and special-case classes that use "standard"
368 /// behavior; if that's dynamically a large proportion of all objects, using
369 /// the entrypoint will also be faster than using a message send.
370 ///
371 /// If the runtime does support a required entrypoint, then this method will
372 /// generate a call and return the resulting value. Otherwise it will return
373 /// None and the caller can generate a msgSend instead.
376  llvm::Value *Receiver,
377  const CallArgList& Args, Selector Sel,
378  const ObjCMethodDecl *method,
379  bool isClassMessage) {
380  auto &CGM = CGF.CGM;
381  if (!CGM.getCodeGenOpts().ObjCConvertMessagesToRuntimeCalls)
382  return None;
383 
384  auto &Runtime = CGM.getLangOpts().ObjCRuntime;
385  switch (Sel.getMethodFamily()) {
386  case OMF_alloc:
387  if (isClassMessage &&
388  Runtime.shouldUseRuntimeFunctionsForAlloc() &&
389  ResultType->isObjCObjectPointerType()) {
390  // [Foo alloc] -> objc_alloc(Foo) or
391  // [self alloc] -> objc_alloc(self)
392  if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "alloc")
393  return CGF.EmitObjCAlloc(Receiver, CGF.ConvertType(ResultType));
394  // [Foo allocWithZone:nil] -> objc_allocWithZone(Foo) or
395  // [self allocWithZone:nil] -> objc_allocWithZone(self)
396  if (Sel.isKeywordSelector() && Sel.getNumArgs() == 1 &&
397  Args.size() == 1 && Args.front().getType()->isPointerType() &&
398  Sel.getNameForSlot(0) == "allocWithZone") {
399  const llvm::Value* arg = Args.front().getKnownRValue().getScalarVal();
400  if (isa<llvm::ConstantPointerNull>(arg))
401  return CGF.EmitObjCAllocWithZone(Receiver,
402  CGF.ConvertType(ResultType));
403  return None;
404  }
405  }
406  break;
407 
408  case OMF_autorelease:
409  if (ResultType->isObjCObjectPointerType() &&
410  CGM.getLangOpts().getGC() == LangOptions::NonGC &&
411  Runtime.shouldUseARCFunctionsForRetainRelease())
412  return CGF.EmitObjCAutorelease(Receiver, CGF.ConvertType(ResultType));
413  break;
414 
415  case OMF_retain:
416  if (ResultType->isObjCObjectPointerType() &&
417  CGM.getLangOpts().getGC() == LangOptions::NonGC &&
418  Runtime.shouldUseARCFunctionsForRetainRelease())
419  return CGF.EmitObjCRetainNonBlock(Receiver, CGF.ConvertType(ResultType));
420  break;
421 
422  case OMF_release:
423  if (ResultType->isVoidType() &&
424  CGM.getLangOpts().getGC() == LangOptions::NonGC &&
425  Runtime.shouldUseARCFunctionsForRetainRelease()) {
426  CGF.EmitObjCRelease(Receiver, ARCPreciseLifetime);
427  return nullptr;
428  }
429  break;
430 
431  default:
432  break;
433  }
434  return None;
435 }
436 
438  CodeGenFunction &CGF, ReturnValueSlot Return, QualType ResultType,
439  Selector Sel, llvm::Value *Receiver, const CallArgList &Args,
440  const ObjCInterfaceDecl *OID, const ObjCMethodDecl *Method,
441  bool isClassMessage) {
442  if (Optional<llvm::Value *> SpecializedResult =
443  tryGenerateSpecializedMessageSend(CGF, ResultType, Receiver, Args,
444  Sel, Method, isClassMessage)) {
445  return RValue::get(SpecializedResult.getValue());
446  }
447  return GenerateMessageSend(CGF, Return, ResultType, Sel, Receiver, Args, OID,
448  Method);
449 }
450 
452  const ObjCProtocolDecl *PD,
453  llvm::UniqueVector<const ObjCProtocolDecl *> &PDs) {
454  if (!PD->isNonRuntimeProtocol()) {
455  const auto *Can = PD->getCanonicalDecl();
456  PDs.insert(Can);
457  return;
458  }
459 
460  for (const auto *ParentPD : PD->protocols())
461  AppendFirstImpliedRuntimeProtocols(ParentPD, PDs);
462 }
463 
464 std::vector<const ObjCProtocolDecl *>
467  std::vector<const ObjCProtocolDecl *> RuntimePds;
469 
470  for (; begin != end; ++begin) {
471  const auto *It = *begin;
472  const auto *Can = It->getCanonicalDecl();
473  if (Can->isNonRuntimeProtocol())
474  NonRuntimePDs.insert(Can);
475  else
476  RuntimePds.push_back(Can);
477  }
478 
479  // If there are no non-runtime protocols then we can just stop now.
480  if (NonRuntimePDs.empty())
481  return RuntimePds;
482 
483  // Else we have to search through the non-runtime protocol's inheritancy
484  // hierarchy DAG stopping whenever a branch either finds a runtime protocol or
485  // a non-runtime protocol without any parents. These are the "first-implied"
486  // protocols from a non-runtime protocol.
487  llvm::UniqueVector<const ObjCProtocolDecl *> FirstImpliedProtos;
488  for (const auto *PD : NonRuntimePDs)
489  AppendFirstImpliedRuntimeProtocols(PD, FirstImpliedProtos);
490 
491  // Walk the Runtime list to get all protocols implied via the inclusion of
492  // this protocol, e.g. all protocols it inherits from including itself.
493  llvm::DenseSet<const ObjCProtocolDecl *> AllImpliedProtocols;
494  for (const auto *PD : RuntimePds) {
495  const auto *Can = PD->getCanonicalDecl();
496  AllImpliedProtocols.insert(Can);
497  Can->getImpliedProtocols(AllImpliedProtocols);
498  }
499 
500  // Similar to above, walk the list of first-implied protocols to find the set
501  // all the protocols implied excluding the listed protocols themselves since
502  // they are not yet a part of the `RuntimePds` list.
503  for (const auto *PD : FirstImpliedProtos) {
504  PD->getImpliedProtocols(AllImpliedProtocols);
505  }
506 
507  // From the first-implied list we have to finish building the final protocol
508  // list. If a protocol in the first-implied list was already implied via some
509  // inheritance path through some other protocols then it would be redundant to
510  // add it here and so we skip over it.
511  for (const auto *PD : FirstImpliedProtos) {
512  if (!AllImpliedProtocols.contains(PD)) {
513  RuntimePds.push_back(PD);
514  }
515  }
516 
517  return RuntimePds;
518 }
519 
520 /// Instead of '[[MyClass alloc] init]', try to generate
521 /// 'objc_alloc_init(MyClass)'. This provides a code size improvement on the
522 /// caller side, as well as the optimized objc_alloc.
525  auto &Runtime = CGF.getLangOpts().ObjCRuntime;
526  if (!Runtime.shouldUseRuntimeFunctionForCombinedAllocInit())
527  return None;
528 
529  // Match the exact pattern '[[MyClass alloc] init]'.
530  Selector Sel = OME->getSelector();
532  !OME->getType()->isObjCObjectPointerType() || !Sel.isUnarySelector() ||
533  Sel.getNameForSlot(0) != "init")
534  return None;
535 
536  // Okay, this is '[receiver init]', check if 'receiver' is '[cls alloc]'
537  // with 'cls' a Class.
538  auto *SubOME =
539  dyn_cast<ObjCMessageExpr>(OME->getInstanceReceiver()->IgnoreParenCasts());
540  if (!SubOME)
541  return None;
542  Selector SubSel = SubOME->getSelector();
543 
544  if (!SubOME->getType()->isObjCObjectPointerType() ||
545  !SubSel.isUnarySelector() || SubSel.getNameForSlot(0) != "alloc")
546  return None;
547 
548  llvm::Value *Receiver = nullptr;
549  switch (SubOME->getReceiverKind()) {
551  if (!SubOME->getInstanceReceiver()->getType()->isObjCClassType())
552  return None;
553  Receiver = CGF.EmitScalarExpr(SubOME->getInstanceReceiver());
554  break;
555 
556  case ObjCMessageExpr::Class: {
557  QualType ReceiverType = SubOME->getClassReceiver();
558  const ObjCObjectType *ObjTy = ReceiverType->castAs<ObjCObjectType>();
559  const ObjCInterfaceDecl *ID = ObjTy->getInterface();
560  assert(ID && "null interface should be impossible here");
561  Receiver = CGF.CGM.getObjCRuntime().GetClass(CGF, ID);
562  break;
563  }
566  return None;
567  }
568 
569  return CGF.EmitObjCAllocInit(Receiver, CGF.ConvertType(OME->getType()));
570 }
571 
573  ReturnValueSlot Return) {
574  // Only the lookup mechanism and first two arguments of the method
575  // implementation vary between runtimes. We can get the receiver and
576  // arguments in generic code.
577 
578  bool isDelegateInit = E->isDelegateInitCall();
579 
580  const ObjCMethodDecl *method = E->getMethodDecl();
581 
582  // If the method is -retain, and the receiver's being loaded from
583  // a __weak variable, peephole the entire operation to objc_loadWeakRetained.
584  if (method && E->getReceiverKind() == ObjCMessageExpr::Instance &&
585  method->getMethodFamily() == OMF_retain) {
586  if (auto lvalueExpr = findWeakLValue(E->getInstanceReceiver())) {
587  LValue lvalue = EmitLValue(lvalueExpr);
588  llvm::Value *result = EmitARCLoadWeakRetained(lvalue.getAddress(*this));
589  return AdjustObjCObjectType(*this, E->getType(), RValue::get(result));
590  }
591  }
592 
594  return AdjustObjCObjectType(*this, E->getType(), RValue::get(*Val));
595 
596  // We don't retain the receiver in delegate init calls, and this is
597  // safe because the receiver value is always loaded from 'self',
598  // which we zero out. We don't want to Block_copy block receivers,
599  // though.
600  bool retainSelf =
601  (!isDelegateInit &&
602  CGM.getLangOpts().ObjCAutoRefCount &&
603  method &&
604  method->hasAttr<NSConsumesSelfAttr>());
605 
606  CGObjCRuntime &Runtime = CGM.getObjCRuntime();
607  bool isSuperMessage = false;
608  bool isClassMessage = false;
609  ObjCInterfaceDecl *OID = nullptr;
610  // Find the receiver
611  QualType ReceiverType;
612  llvm::Value *Receiver = nullptr;
613  switch (E->getReceiverKind()) {
615  ReceiverType = E->getInstanceReceiver()->getType();
616  isClassMessage = ReceiverType->isObjCClassType();
617  if (retainSelf) {
619  E->getInstanceReceiver());
620  Receiver = ter.getPointer();
621  if (ter.getInt()) retainSelf = false;
622  } else
623  Receiver = EmitScalarExpr(E->getInstanceReceiver());
624  break;
625 
626  case ObjCMessageExpr::Class: {
627  ReceiverType = E->getClassReceiver();
628  OID = ReceiverType->castAs<ObjCObjectType>()->getInterface();
629  assert(OID && "Invalid Objective-C class message send");
630  Receiver = Runtime.GetClass(*this, OID);
631  isClassMessage = true;
632  break;
633  }
634 
636  ReceiverType = E->getSuperType();
637  Receiver = LoadObjCSelf();
638  isSuperMessage = true;
639  break;
640 
642  ReceiverType = E->getSuperType();
643  Receiver = LoadObjCSelf();
644  isSuperMessage = true;
645  isClassMessage = true;
646  break;
647  }
648 
649  if (retainSelf)
650  Receiver = EmitARCRetainNonBlock(Receiver);
651 
652  // In ARC, we sometimes want to "extend the lifetime"
653  // (i.e. retain+autorelease) of receivers of returns-inner-pointer
654  // messages.
655  if (getLangOpts().ObjCAutoRefCount && method &&
656  method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
658  Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
659 
660  QualType ResultType = method ? method->getReturnType() : E->getType();
661 
662  CallArgList Args;
663  EmitCallArgs(Args, method, E->arguments(), /*AC*/AbstractCallee(method));
664 
665  // For delegate init calls in ARC, do an unsafe store of null into
666  // self. This represents the call taking direct ownership of that
667  // value. We have to do this after emitting the other call
668  // arguments because they might also reference self, but we don't
669  // have to worry about any of them modifying self because that would
670  // be an undefined read and write of an object in unordered
671  // expressions.
672  if (isDelegateInit) {
673  assert(getLangOpts().ObjCAutoRefCount &&
674  "delegate init calls should only be marked in ARC");
675 
676  // Do an unsafe store of null into self.
677  Address selfAddr =
678  GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
679  Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
680  }
681 
682  RValue result;
683  if (isSuperMessage) {
684  // super is only valid in an Objective-C method
685  const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
686  bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
687  result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
688  E->getSelector(),
689  OMD->getClassInterface(),
690  isCategoryImpl,
691  Receiver,
692  isClassMessage,
693  Args,
694  method);
695  } else {
696  // Call runtime methods directly if we can.
698  *this, Return, ResultType, E->getSelector(), Receiver, Args, OID,
699  method, isClassMessage);
700  }
701 
702  // For delegate init calls in ARC, implicitly store the result of
703  // the call back into self. This takes ownership of the value.
704  if (isDelegateInit) {
705  Address selfAddr =
706  GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
707  llvm::Value *newSelf = result.getScalarVal();
708 
709  // The delegate return type isn't necessarily a matching type; in
710  // fact, it's quite likely to be 'id'.
711  llvm::Type *selfTy = selfAddr.getElementType();
712  newSelf = Builder.CreateBitCast(newSelf, selfTy);
713 
714  Builder.CreateStore(newSelf, selfAddr);
715  }
716 
717  return AdjustObjCObjectType(*this, E->getType(), result);
718 }
719 
720 namespace {
721 struct FinishARCDealloc final : EHScopeStack::Cleanup {
722  void Emit(CodeGenFunction &CGF, Flags flags) override {
723  const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
724 
725  const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
726  const ObjCInterfaceDecl *iface = impl->getClassInterface();
727  if (!iface->getSuperClass()) return;
728 
729  bool isCategory = isa<ObjCCategoryImplDecl>(impl);
730 
731  // Call [super dealloc] if we have a superclass.
732  llvm::Value *self = CGF.LoadObjCSelf();
733 
734  CallArgList args;
736  CGF.getContext().VoidTy,
737  method->getSelector(),
738  iface,
739  isCategory,
740  self,
741  /*is class msg*/ false,
742  args,
743  method);
744  }
745 };
746 }
747 
748 /// StartObjCMethod - Begin emission of an ObjCMethod. This generates
749 /// the LLVM function and sets the other context used by
750 /// CodeGenFunction.
752  const ObjCContainerDecl *CD) {
753  SourceLocation StartLoc = OMD->getBeginLoc();
754  FunctionArgList args;
755  // Check if we should generate debug info for this method.
756  if (OMD->hasAttr<NoDebugAttr>())
757  DebugInfo = nullptr; // disable debug info indefinitely for this function
758 
759  llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
760 
762  if (OMD->isDirectMethod()) {
763  Fn->setVisibility(llvm::Function::HiddenVisibility);
764  CGM.SetLLVMFunctionAttributes(OMD, FI, Fn, /*IsThunk=*/false);
766  } else {
767  CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
768  }
769 
770  args.push_back(OMD->getSelfDecl());
771  args.push_back(OMD->getCmdDecl());
772 
773  args.append(OMD->param_begin(), OMD->param_end());
774 
775  CurGD = OMD;
776  CurEHLocation = OMD->getEndLoc();
777 
778  StartFunction(OMD, OMD->getReturnType(), Fn, FI, args,
779  OMD->getLocation(), StartLoc);
780 
781  if (OMD->isDirectMethod()) {
782  // This function is a direct call, it has to implement a nil check
783  // on entry.
784  //
785  // TODO: possibly have several entry points to elide the check
786  CGM.getObjCRuntime().GenerateDirectMethodPrologue(*this, Fn, OMD, CD);
787  }
788 
789  // In ARC, certain methods get an extra cleanup.
790  if (CGM.getLangOpts().ObjCAutoRefCount &&
791  OMD->isInstanceMethod() &&
792  OMD->getSelector().isUnarySelector()) {
793  const IdentifierInfo *ident =
795  if (ident->isStr("dealloc"))
796  EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
797  }
798 }
799 
800 static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
801  LValue lvalue, QualType type);
802 
803 /// Generate an Objective-C method. An Objective-C method is a C function with
804 /// its pointer, name, and types registered in the class structure.
806  StartObjCMethod(OMD, OMD->getClassInterface());
808  assert(isa<CompoundStmt>(OMD->getBody()));
810  EmitCompoundStmtWithoutScope(*cast<CompoundStmt>(OMD->getBody()));
812 }
813 
814 /// emitStructGetterCall - Call the runtime function to load a property
815 /// into the return value slot.
817  bool isAtomic, bool hasStrong) {
818  ASTContext &Context = CGF.getContext();
819 
820  llvm::Value *src =
821  CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
822  .getPointer(CGF);
823 
824  // objc_copyStruct (ReturnValue, &structIvar,
825  // sizeof (Type of Ivar), isAtomic, false);
826  CallArgList args;
827 
828  llvm::Value *dest =
829  CGF.Builder.CreateBitCast(CGF.ReturnValue.getPointer(), CGF.VoidPtrTy);
830  args.add(RValue::get(dest), Context.VoidPtrTy);
831 
832  src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
833  args.add(RValue::get(src), Context.VoidPtrTy);
834 
835  CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
836  args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
837  args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
838  args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
839 
840  llvm::FunctionCallee fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
841  CGCallee callee = CGCallee::forDirect(fn);
842  CGF.EmitCall(CGF.getTypes().arrangeBuiltinFunctionCall(Context.VoidTy, args),
843  callee, ReturnValueSlot(), args);
844 }
845 
846 /// Determine whether the given architecture supports unaligned atomic
847 /// accesses. They don't have to be fast, just faster than a function
848 /// call and a mutex.
849 static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
850  // FIXME: Allow unaligned atomic load/store on x86. (It is not
851  // currently supported by the backend.)
852  return false;
853 }
854 
855 /// Return the maximum size that permits atomic accesses for the given
856 /// architecture.
858  llvm::Triple::ArchType arch) {
859  // ARM has 8-byte atomic accesses, but it's not clear whether we
860  // want to rely on them here.
861 
862  // In the default case, just assume that any size up to a pointer is
863  // fine given adequate alignment.
865 }
866 
867 namespace {
868  class PropertyImplStrategy {
869  public:
870  enum StrategyKind {
871  /// The 'native' strategy is to use the architecture's provided
872  /// reads and writes.
873  Native,
874 
875  /// Use objc_setProperty and objc_getProperty.
876  GetSetProperty,
877 
878  /// Use objc_setProperty for the setter, but use expression
879  /// evaluation for the getter.
880  SetPropertyAndExpressionGet,
881 
882  /// Use objc_copyStruct.
883  CopyStruct,
884 
885  /// The 'expression' strategy is to emit normal assignment or
886  /// lvalue-to-rvalue expressions.
887  Expression
888  };
889 
890  StrategyKind getKind() const { return StrategyKind(Kind); }
891 
892  bool hasStrongMember() const { return HasStrong; }
893  bool isAtomic() const { return IsAtomic; }
894  bool isCopy() const { return IsCopy; }
895 
896  CharUnits getIvarSize() const { return IvarSize; }
897  CharUnits getIvarAlignment() const { return IvarAlignment; }
898 
899  PropertyImplStrategy(CodeGenModule &CGM,
900  const ObjCPropertyImplDecl *propImpl);
901 
902  private:
903  unsigned Kind : 8;
904  unsigned IsAtomic : 1;
905  unsigned IsCopy : 1;
906  unsigned HasStrong : 1;
907 
908  CharUnits IvarSize;
909  CharUnits IvarAlignment;
910  };
911 }
912 
913 /// Pick an implementation strategy for the given property synthesis.
914 PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
915  const ObjCPropertyImplDecl *propImpl) {
916  const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
917  ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
918 
919  IsCopy = (setterKind == ObjCPropertyDecl::Copy);
920  IsAtomic = prop->isAtomic();
921  HasStrong = false; // doesn't matter here.
922 
923  // Evaluate the ivar's size and alignment.
924  ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
925  QualType ivarType = ivar->getType();
926  auto TInfo = CGM.getContext().getTypeInfoInChars(ivarType);
927  IvarSize = TInfo.Width;
928  IvarAlignment = TInfo.Align;
929 
930  // If we have a copy property, we always have to use setProperty.
931  // If the property is atomic we need to use getProperty, but in
932  // the nonatomic case we can just use expression.
933  if (IsCopy) {
934  Kind = IsAtomic ? GetSetProperty : SetPropertyAndExpressionGet;
935  return;
936  }
937 
938  // Handle retain.
939  if (setterKind == ObjCPropertyDecl::Retain) {
940  // In GC-only, there's nothing special that needs to be done.
941  if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
942  // fallthrough
943 
944  // In ARC, if the property is non-atomic, use expression emission,
945  // which translates to objc_storeStrong. This isn't required, but
946  // it's slightly nicer.
947  } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) {
948  // Using standard expression emission for the setter is only
949  // acceptable if the ivar is __strong, which won't be true if
950  // the property is annotated with __attribute__((NSObject)).
951  // TODO: falling all the way back to objc_setProperty here is
952  // just laziness, though; we could still use objc_storeStrong
953  // if we hacked it right.
954  if (ivarType.getObjCLifetime() == Qualifiers::OCL_Strong)
955  Kind = Expression;
956  else
957  Kind = SetPropertyAndExpressionGet;
958  return;
959 
960  // Otherwise, we need to at least use setProperty. However, if
961  // the property isn't atomic, we can use normal expression
962  // emission for the getter.
963  } else if (!IsAtomic) {
964  Kind = SetPropertyAndExpressionGet;
965  return;
966 
967  // Otherwise, we have to use both setProperty and getProperty.
968  } else {
969  Kind = GetSetProperty;
970  return;
971  }
972  }
973 
974  // If we're not atomic, just use expression accesses.
975  if (!IsAtomic) {
976  Kind = Expression;
977  return;
978  }
979 
980  // Properties on bitfield ivars need to be emitted using expression
981  // accesses even if they're nominally atomic.
982  if (ivar->isBitField()) {
983  Kind = Expression;
984  return;
985  }
986 
987  // GC-qualified or ARC-qualified ivars need to be emitted as
988  // expressions. This actually works out to being atomic anyway,
989  // except for ARC __strong, but that should trigger the above code.
990  if (ivarType.hasNonTrivialObjCLifetime() ||
991  (CGM.getLangOpts().getGC() &&
992  CGM.getContext().getObjCGCAttrKind(ivarType))) {
993  Kind = Expression;
994  return;
995  }
996 
997  // Compute whether the ivar has strong members.
998  if (CGM.getLangOpts().getGC())
999  if (const RecordType *recordType = ivarType->getAs<RecordType>())
1000  HasStrong = recordType->getDecl()->hasObjectMember();
1001 
1002  // We can never access structs with object members with a native
1003  // access, because we need to use write barriers. This is what
1004  // objc_copyStruct is for.
1005  if (HasStrong) {
1006  Kind = CopyStruct;
1007  return;
1008  }
1009 
1010  // Otherwise, this is target-dependent and based on the size and
1011  // alignment of the ivar.
1012 
1013  // If the size of the ivar is not a power of two, give up. We don't
1014  // want to get into the business of doing compare-and-swaps.
1015  if (!IvarSize.isPowerOfTwo()) {
1016  Kind = CopyStruct;
1017  return;
1018  }
1019 
1020  llvm::Triple::ArchType arch =
1021  CGM.getTarget().getTriple().getArch();
1022 
1023  // Most architectures require memory to fit within a single cache
1024  // line, so the alignment has to be at least the size of the access.
1025  // Otherwise we have to grab a lock.
1026  if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
1027  Kind = CopyStruct;
1028  return;
1029  }
1030 
1031  // If the ivar's size exceeds the architecture's maximum atomic
1032  // access size, we have to use CopyStruct.
1033  if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
1034  Kind = CopyStruct;
1035  return;
1036  }
1037 
1038  // Otherwise, we can use native loads and stores.
1039  Kind = Native;
1040 }
1041 
1042 /// Generate an Objective-C property getter function.
1043 ///
1044 /// The given Decl must be an ObjCImplementationDecl. \@synthesize
1045 /// is illegal within a category.
1047  const ObjCPropertyImplDecl *PID) {
1048  llvm::Constant *AtomicHelperFn =
1050  ObjCMethodDecl *OMD = PID->getGetterMethodDecl();
1051  assert(OMD && "Invalid call to generate getter (empty method)");
1052  StartObjCMethod(OMD, IMP->getClassInterface());
1053 
1054  generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn);
1055 
1056  FinishFunction(OMD->getEndLoc());
1057 }
1058 
1059 static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
1060  const Expr *getter = propImpl->getGetterCXXConstructor();
1061  if (!getter) return true;
1062 
1063  // Sema only makes only of these when the ivar has a C++ class type,
1064  // so the form is pretty constrained.
1065 
1066  // If the property has a reference type, we might just be binding a
1067  // reference, in which case the result will be a gl-value. We should
1068  // treat this as a non-trivial operation.
1069  if (getter->isGLValue())
1070  return false;
1071 
1072  // If we selected a trivial copy-constructor, we're okay.
1073  if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
1074  return (construct->getConstructor()->isTrivial());
1075 
1076  // The constructor might require cleanups (in which case it's never
1077  // trivial).
1078  assert(isa<ExprWithCleanups>(getter));
1079  return false;
1080 }
1081 
1082 /// emitCPPObjectAtomicGetterCall - Call the runtime function to
1083 /// copy the ivar into the resturn slot.
1085  llvm::Value *returnAddr,
1086  ObjCIvarDecl *ivar,
1087  llvm::Constant *AtomicHelperFn) {
1088  // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
1089  // AtomicHelperFn);
1090  CallArgList args;
1091 
1092  // The 1st argument is the return Slot.
1093  args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
1094 
1095  // The 2nd argument is the address of the ivar.
1096  llvm::Value *ivarAddr =
1097  CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
1098  .getPointer(CGF);
1099  ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1100  args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
1101 
1102  // Third argument is the helper function.
1103  args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
1104 
1105  llvm::FunctionCallee copyCppAtomicObjectFn =
1107  CGCallee callee = CGCallee::forDirect(copyCppAtomicObjectFn);
1108  CGF.EmitCall(
1110  callee, ReturnValueSlot(), args);
1111 }
1112 
1113 void
1115  const ObjCPropertyImplDecl *propImpl,
1116  const ObjCMethodDecl *GetterMethodDecl,
1117  llvm::Constant *AtomicHelperFn) {
1118  // If there's a non-trivial 'get' expression, we just have to emit that.
1119  if (!hasTrivialGetExpr(propImpl)) {
1120  if (!AtomicHelperFn) {
1121  auto *ret = ReturnStmt::Create(getContext(), SourceLocation(),
1122  propImpl->getGetterCXXConstructor(),
1123  /* NRVOCandidate=*/nullptr);
1124  EmitReturnStmt(*ret);
1125  }
1126  else {
1127  ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
1129  ivar, AtomicHelperFn);
1130  }
1131  return;
1132  }
1133 
1134  const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
1135  QualType propType = prop->getType();
1136  ObjCMethodDecl *getterMethod = propImpl->getGetterMethodDecl();
1137 
1138  ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
1139 
1140  // Pick an implementation strategy.
1141  PropertyImplStrategy strategy(CGM, propImpl);
1142  switch (strategy.getKind()) {
1143  case PropertyImplStrategy::Native: {
1144  // We don't need to do anything for a zero-size struct.
1145  if (strategy.getIvarSize().isZero())
1146  return;
1147 
1149 
1150  // Currently, all atomic accesses have to be through integer
1151  // types, so there's no point in trying to pick a prettier type.
1152  uint64_t ivarSize = getContext().toBits(strategy.getIvarSize());
1153  llvm::Type *bitcastType = llvm::Type::getIntNTy(getLLVMContext(), ivarSize);
1154 
1155  // Perform an atomic load. This does not impose ordering constraints.
1156  Address ivarAddr = LV.getAddress(*this);
1157  ivarAddr = Builder.CreateElementBitCast(ivarAddr, bitcastType);
1158  llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
1159  load->setAtomic(llvm::AtomicOrdering::Unordered);
1160 
1161  // Store that value into the return address. Doing this with a
1162  // bitcast is likely to produce some pretty ugly IR, but it's not
1163  // the *most* terrible thing in the world.
1164  llvm::Type *retTy = ConvertType(getterMethod->getReturnType());
1165  uint64_t retTySize = CGM.getDataLayout().getTypeSizeInBits(retTy);
1166  llvm::Value *ivarVal = load;
1167  if (ivarSize > retTySize) {
1168  bitcastType = llvm::Type::getIntNTy(getLLVMContext(), retTySize);
1169  ivarVal = Builder.CreateTrunc(load, bitcastType);
1170  }
1171  Builder.CreateStore(ivarVal,
1172  Builder.CreateElementBitCast(ReturnValue, bitcastType));
1173 
1174  // Make sure we don't do an autorelease.
1175  AutoreleaseResult = false;
1176  return;
1177  }
1178 
1179  case PropertyImplStrategy::GetSetProperty: {
1180  llvm::FunctionCallee getPropertyFn =
1182  if (!getPropertyFn) {
1183  CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
1184  return;
1185  }
1186  CGCallee callee = CGCallee::forDirect(getPropertyFn);
1187 
1188  // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
1189  // FIXME: Can't this be simpler? This might even be worse than the
1190  // corresponding gcc code.
1191  llvm::Value *cmd =
1192  Builder.CreateLoad(GetAddrOfLocalVar(getterMethod->getCmdDecl()), "cmd");
1193  llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1194  llvm::Value *ivarOffset =
1195  EmitIvarOffset(classImpl->getClassInterface(), ivar);
1196 
1197  CallArgList args;
1198  args.add(RValue::get(self), getContext().getObjCIdType());
1199  args.add(RValue::get(cmd), getContext().getObjCSelType());
1200  args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1201  args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1202  getContext().BoolTy);
1203 
1204  // FIXME: We shouldn't need to get the function info here, the
1205  // runtime already should have computed it to build the function.
1206  llvm::CallBase *CallInstruction;
1207  RValue RV = EmitCall(getTypes().arrangeBuiltinFunctionCall(
1208  getContext().getObjCIdType(), args),
1209  callee, ReturnValueSlot(), args, &CallInstruction);
1210  if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(CallInstruction))
1211  call->setTailCall();
1212 
1213  // We need to fix the type here. Ivars with copy & retain are
1214  // always objects so we don't need to worry about complex or
1215  // aggregates.
1216  RV = RValue::get(Builder.CreateBitCast(
1217  RV.getScalarVal(),
1218  getTypes().ConvertType(getterMethod->getReturnType())));
1219 
1220  EmitReturnOfRValue(RV, propType);
1221 
1222  // objc_getProperty does an autorelease, so we should suppress ours.
1223  AutoreleaseResult = false;
1224 
1225  return;
1226  }
1227 
1228  case PropertyImplStrategy::CopyStruct:
1229  emitStructGetterCall(*this, ivar, strategy.isAtomic(),
1230  strategy.hasStrongMember());
1231  return;
1232 
1233  case PropertyImplStrategy::Expression:
1234  case PropertyImplStrategy::SetPropertyAndExpressionGet: {
1236 
1237  QualType ivarType = ivar->getType();
1238  switch (getEvaluationKind(ivarType)) {
1239  case TEK_Complex: {
1242  /*init*/ true);
1243  return;
1244  }
1245  case TEK_Aggregate: {
1246  // The return value slot is guaranteed to not be aliased, but
1247  // that's not necessarily the same as "on the stack", so
1248  // we still potentially need objc_memmove_collectable.
1249  EmitAggregateCopy(/* Dest= */ MakeAddrLValue(ReturnValue, ivarType),
1250  /* Src= */ LV, ivarType, getOverlapForReturnValue());
1251  return;
1252  }
1253  case TEK_Scalar: {
1254  llvm::Value *value;
1255  if (propType->isReferenceType()) {
1256  value = LV.getAddress(*this).getPointer();
1257  } else {
1258  // We want to load and autoreleaseReturnValue ARC __weak ivars.
1260  if (getLangOpts().ObjCAutoRefCount) {
1261  value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
1262  } else {
1263  value = EmitARCLoadWeak(LV.getAddress(*this));
1264  }
1265 
1266  // Otherwise we want to do a simple load, suppressing the
1267  // final autorelease.
1268  } else {
1269  value = EmitLoadOfLValue(LV, SourceLocation()).getScalarVal();
1270  AutoreleaseResult = false;
1271  }
1272 
1273  value = Builder.CreateBitCast(
1274  value, ConvertType(GetterMethodDecl->getReturnType()));
1275  }
1276 
1277  EmitReturnOfRValue(RValue::get(value), propType);
1278  return;
1279  }
1280  }
1281  llvm_unreachable("bad evaluation kind");
1282  }
1283 
1284  }
1285  llvm_unreachable("bad @property implementation strategy!");
1286 }
1287 
1288 /// emitStructSetterCall - Call the runtime function to store the value
1289 /// from the first formal parameter into the given ivar.
1291  ObjCIvarDecl *ivar) {
1292  // objc_copyStruct (&structIvar, &Arg,
1293  // sizeof (struct something), true, false);
1294  CallArgList args;
1295 
1296  // The first argument is the address of the ivar.
1297  llvm::Value *ivarAddr =
1298  CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
1299  .getPointer(CGF);
1300  ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1301  args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
1302 
1303  // The second argument is the address of the parameter variable.
1304  ParmVarDecl *argVar = *OMD->param_begin();
1305  DeclRefExpr argRef(CGF.getContext(), argVar, false,
1306  argVar->getType().getNonReferenceType(), VK_LValue,
1307  SourceLocation());
1308  llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer(CGF);
1309  argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1310  args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
1311 
1312  // The third argument is the sizeof the type.
1313  llvm::Value *size =
1314  CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
1315  args.add(RValue::get(size), CGF.getContext().getSizeType());
1316 
1317  // The fourth argument is the 'isAtomic' flag.
1318  args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
1319 
1320  // The fifth argument is the 'hasStrong' flag.
1321  // FIXME: should this really always be false?
1322  args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
1323 
1324  llvm::FunctionCallee fn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
1325  CGCallee callee = CGCallee::forDirect(fn);
1326  CGF.EmitCall(
1328  callee, ReturnValueSlot(), args);
1329 }
1330 
1331 /// emitCPPObjectAtomicSetterCall - Call the runtime function to store
1332 /// the value from the first formal parameter into the given ivar, using
1333 /// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
1335  ObjCMethodDecl *OMD,
1336  ObjCIvarDecl *ivar,
1337  llvm::Constant *AtomicHelperFn) {
1338  // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
1339  // AtomicHelperFn);
1340  CallArgList args;
1341 
1342  // The first argument is the address of the ivar.
1343  llvm::Value *ivarAddr =
1344  CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
1345  .getPointer(CGF);
1346  ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1347  args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
1348 
1349  // The second argument is the address of the parameter variable.
1350  ParmVarDecl *argVar = *OMD->param_begin();
1351  DeclRefExpr argRef(CGF.getContext(), argVar, false,
1352  argVar->getType().getNonReferenceType(), VK_LValue,
1353  SourceLocation());
1354  llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer(CGF);
1355  argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1356  args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
1357 
1358  // Third argument is the helper function.
1359  args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
1360 
1361  llvm::FunctionCallee fn =
1363  CGCallee callee = CGCallee::forDirect(fn);
1364  CGF.EmitCall(
1366  callee, ReturnValueSlot(), args);
1367 }
1368 
1369 
1370 static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1371  Expr *setter = PID->getSetterCXXAssignment();
1372  if (!setter) return true;
1373 
1374  // Sema only makes only of these when the ivar has a C++ class type,
1375  // so the form is pretty constrained.
1376 
1377  // An operator call is trivial if the function it calls is trivial.
1378  // This also implies that there's nothing non-trivial going on with
1379  // the arguments, because operator= can only be trivial if it's a
1380  // synthesized assignment operator and therefore both parameters are
1381  // references.
1382  if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
1383  if (const FunctionDecl *callee
1384  = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1385  if (callee->isTrivial())
1386  return true;
1387  return false;
1388  }
1389 
1390  assert(isa<ExprWithCleanups>(setter));
1391  return false;
1392 }
1393 
1395  if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
1396  return false;
1398 }
1399 
1400 void
1402  const ObjCPropertyImplDecl *propImpl,
1403  llvm::Constant *AtomicHelperFn) {
1404  ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
1405  ObjCMethodDecl *setterMethod = propImpl->getSetterMethodDecl();
1406 
1407  // Just use the setter expression if Sema gave us one and it's
1408  // non-trivial.
1409  if (!hasTrivialSetExpr(propImpl)) {
1410  if (!AtomicHelperFn)
1411  // If non-atomic, assignment is called directly.
1412  EmitStmt(propImpl->getSetterCXXAssignment());
1413  else
1414  // If atomic, assignment is called via a locking api.
1415  emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
1416  AtomicHelperFn);
1417  return;
1418  }
1419 
1420  PropertyImplStrategy strategy(CGM, propImpl);
1421  switch (strategy.getKind()) {
1422  case PropertyImplStrategy::Native: {
1423  // We don't need to do anything for a zero-size struct.
1424  if (strategy.getIvarSize().isZero())
1425  return;
1426 
1427  Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
1428 
1429  LValue ivarLValue =
1430  EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
1431  Address ivarAddr = ivarLValue.getAddress(*this);
1432 
1433  // Currently, all atomic accesses have to be through integer
1434  // types, so there's no point in trying to pick a prettier type.
1435  llvm::Type *bitcastType =
1436  llvm::Type::getIntNTy(getLLVMContext(),
1437  getContext().toBits(strategy.getIvarSize()));
1438 
1439  // Cast both arguments to the chosen operation type.
1440  argAddr = Builder.CreateElementBitCast(argAddr, bitcastType);
1441  ivarAddr = Builder.CreateElementBitCast(ivarAddr, bitcastType);
1442 
1443  // This bitcast load is likely to cause some nasty IR.
1444  llvm::Value *load = Builder.CreateLoad(argAddr);
1445 
1446  // Perform an atomic store. There are no memory ordering requirements.
1447  llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
1448  store->setAtomic(llvm::AtomicOrdering::Unordered);
1449  return;
1450  }
1451 
1452  case PropertyImplStrategy::GetSetProperty:
1453  case PropertyImplStrategy::SetPropertyAndExpressionGet: {
1454 
1455  llvm::FunctionCallee setOptimizedPropertyFn = nullptr;
1456  llvm::FunctionCallee setPropertyFn = nullptr;
1457  if (UseOptimizedSetter(CGM)) {
1458  // 10.8 and iOS 6.0 code and GC is off
1459  setOptimizedPropertyFn =
1461  strategy.isAtomic(), strategy.isCopy());
1462  if (!setOptimizedPropertyFn) {
1463  CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1464  return;
1465  }
1466  }
1467  else {
1468  setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1469  if (!setPropertyFn) {
1470  CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1471  return;
1472  }
1473  }
1474 
1475  // Emit objc_setProperty((id) self, _cmd, offset, arg,
1476  // <is-atomic>, <is-copy>).
1477  llvm::Value *cmd =
1478  Builder.CreateLoad(GetAddrOfLocalVar(setterMethod->getCmdDecl()));
1479  llvm::Value *self =
1480  Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1481  llvm::Value *ivarOffset =
1482  EmitIvarOffset(classImpl->getClassInterface(), ivar);
1483  Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
1484  llvm::Value *arg = Builder.CreateLoad(argAddr, "arg");
1485  arg = Builder.CreateBitCast(arg, VoidPtrTy);
1486 
1487  CallArgList args;
1488  args.add(RValue::get(self), getContext().getObjCIdType());
1489  args.add(RValue::get(cmd), getContext().getObjCSelType());
1490  if (setOptimizedPropertyFn) {
1491  args.add(RValue::get(arg), getContext().getObjCIdType());
1492  args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1493  CGCallee callee = CGCallee::forDirect(setOptimizedPropertyFn);
1494  EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
1495  callee, ReturnValueSlot(), args);
1496  } else {
1497  args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1498  args.add(RValue::get(arg), getContext().getObjCIdType());
1499  args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1500  getContext().BoolTy);
1501  args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1502  getContext().BoolTy);
1503  // FIXME: We shouldn't need to get the function info here, the runtime
1504  // already should have computed it to build the function.
1505  CGCallee callee = CGCallee::forDirect(setPropertyFn);
1506  EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
1507  callee, ReturnValueSlot(), args);
1508  }
1509 
1510  return;
1511  }
1512 
1513  case PropertyImplStrategy::CopyStruct:
1514  emitStructSetterCall(*this, setterMethod, ivar);
1515  return;
1516 
1517  case PropertyImplStrategy::Expression:
1518  break;
1519  }
1520 
1521  // Otherwise, fake up some ASTs and emit a normal assignment.
1522  ValueDecl *selfDecl = setterMethod->getSelfDecl();
1523  DeclRefExpr self(getContext(), selfDecl, false, selfDecl->getType(),
1525  ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack, selfDecl->getType(),
1526  CK_LValueToRValue, &self, VK_PRValue,
1527  FPOptionsOverride());
1528  ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
1530  &selfLoad, true, true);
1531 
1532  ParmVarDecl *argDecl = *setterMethod->param_begin();
1533  QualType argType = argDecl->getType().getNonReferenceType();
1534  DeclRefExpr arg(getContext(), argDecl, false, argType, VK_LValue,
1535  SourceLocation());
1537  argType.getUnqualifiedType(), CK_LValueToRValue,
1539 
1540  // The property type can differ from the ivar type in some situations with
1541  // Objective-C pointer types, we can always bit cast the RHS in these cases.
1542  // The following absurdity is just to ensure well-formed IR.
1543  CastKind argCK = CK_NoOp;
1544  if (ivarRef.getType()->isObjCObjectPointerType()) {
1545  if (argLoad.getType()->isObjCObjectPointerType())
1546  argCK = CK_BitCast;
1547  else if (argLoad.getType()->isBlockPointerType())
1548  argCK = CK_BlockPointerToObjCPointerCast;
1549  else
1550  argCK = CK_CPointerToObjCPointerCast;
1551  } else if (ivarRef.getType()->isBlockPointerType()) {
1552  if (argLoad.getType()->isBlockPointerType())
1553  argCK = CK_BitCast;
1554  else
1555  argCK = CK_AnyPointerToBlockPointerCast;
1556  } else if (ivarRef.getType()->isPointerType()) {
1557  argCK = CK_BitCast;
1558  } else if (argLoad.getType()->isAtomicType() &&
1559  !ivarRef.getType()->isAtomicType()) {
1560  argCK = CK_AtomicToNonAtomic;
1561  } else if (!argLoad.getType()->isAtomicType() &&
1562  ivarRef.getType()->isAtomicType()) {
1563  argCK = CK_NonAtomicToAtomic;
1564  }
1565  ImplicitCastExpr argCast(ImplicitCastExpr::OnStack, ivarRef.getType(), argCK,
1566  &argLoad, VK_PRValue, FPOptionsOverride());
1567  Expr *finalArg = &argLoad;
1568  if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1569  argLoad.getType()))
1570  finalArg = &argCast;
1571 
1573  getContext(), &ivarRef, finalArg, BO_Assign, ivarRef.getType(),
1575  EmitStmt(assign);
1576 }
1577 
1578 /// Generate an Objective-C property setter function.
1579 ///
1580 /// The given Decl must be an ObjCImplementationDecl. \@synthesize
1581 /// is illegal within a category.
1583  const ObjCPropertyImplDecl *PID) {
1584  llvm::Constant *AtomicHelperFn =
1586  ObjCMethodDecl *OMD = PID->getSetterMethodDecl();
1587  assert(OMD && "Invalid call to generate setter (empty method)");
1588  StartObjCMethod(OMD, IMP->getClassInterface());
1589 
1590  generateObjCSetterBody(IMP, PID, AtomicHelperFn);
1591 
1592  FinishFunction(OMD->getEndLoc());
1593 }
1594 
1595 namespace {
1596  struct DestroyIvar final : EHScopeStack::Cleanup {
1597  private:
1598  llvm::Value *addr;
1599  const ObjCIvarDecl *ivar;
1600  CodeGenFunction::Destroyer *destroyer;
1601  bool useEHCleanupForArray;
1602  public:
1603  DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1604  CodeGenFunction::Destroyer *destroyer,
1605  bool useEHCleanupForArray)
1606  : addr(addr), ivar(ivar), destroyer(destroyer),
1607  useEHCleanupForArray(useEHCleanupForArray) {}
1608 
1609  void Emit(CodeGenFunction &CGF, Flags flags) override {
1610  LValue lvalue
1611  = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1612  CGF.emitDestroy(lvalue.getAddress(CGF), ivar->getType(), destroyer,
1613  flags.isForNormalCleanup() && useEHCleanupForArray);
1614  }
1615  };
1616 }
1617 
1618 /// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1620  Address addr,
1621  QualType type) {
1622  llvm::Value *null = getNullForVariable(addr);
1623  CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1624 }
1625 
1627  ObjCImplementationDecl *impl) {
1629 
1630  llvm::Value *self = CGF.LoadObjCSelf();
1631 
1632  const ObjCInterfaceDecl *iface = impl->getClassInterface();
1633  for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
1634  ivar; ivar = ivar->getNextIvar()) {
1635  QualType type = ivar->getType();
1636 
1637  // Check whether the ivar is a destructible type.
1638  QualType::DestructionKind dtorKind = type.isDestructedType();
1639  if (!dtorKind) continue;
1640 
1641  CodeGenFunction::Destroyer *destroyer = nullptr;
1642 
1643  // Use a call to objc_storeStrong to destroy strong ivars, for the
1644  // general benefit of the tools.
1645  if (dtorKind == QualType::DK_objc_strong_lifetime) {
1646  destroyer = destroyARCStrongWithStore;
1647 
1648  // Otherwise use the default for the destruction kind.
1649  } else {
1650  destroyer = CGF.getDestroyer(dtorKind);
1651  }
1652 
1653  CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1654 
1655  CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1656  cleanupKind & EHCleanup);
1657  }
1658 
1659  assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1660 }
1661 
1663  ObjCMethodDecl *MD,
1664  bool ctor) {
1666  StartObjCMethod(MD, IMP->getClassInterface());
1667 
1668  // Emit .cxx_construct.
1669  if (ctor) {
1670  // Suppress the final autorelease in ARC.
1671  AutoreleaseResult = false;
1672 
1673  for (const auto *IvarInit : IMP->inits()) {
1674  FieldDecl *Field = IvarInit->getAnyMember();
1675  ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
1677  LoadObjCSelf(), Ivar, 0);
1678  EmitAggExpr(IvarInit->getInit(),
1683  }
1684  // constructor returns 'self'.
1685  CodeGenTypes &Types = CGM.getTypes();
1687  llvm::Value *SelfAsId =
1688  Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1689  EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
1690 
1691  // Emit .cxx_destruct.
1692  } else {
1693  emitCXXDestructMethod(*this, IMP);
1694  }
1695  FinishFunction();
1696 }
1697 
1699  VarDecl *Self = cast<ObjCMethodDecl>(CurFuncDecl)->getSelfDecl();
1700  DeclRefExpr DRE(getContext(), Self,
1701  /*is enclosing local*/ (CurFuncDecl != CurCodeDecl),
1702  Self->getType(), VK_LValue, SourceLocation());
1704 }
1705 
1707  const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1708  ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
1709  const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1710  getContext().getCanonicalType(selfDecl->getType()));
1711  return PTy->getPointeeType();
1712 }
1713 
1715  llvm::FunctionCallee EnumerationMutationFnPtr =
1717  if (!EnumerationMutationFnPtr) {
1718  CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1719  return;
1720  }
1721  CGCallee EnumerationMutationFn =
1722  CGCallee::forDirect(EnumerationMutationFnPtr);
1723 
1724  CGDebugInfo *DI = getDebugInfo();
1725  if (DI)
1726  DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
1727 
1728  RunCleanupsScope ForScope(*this);
1729 
1730  // The local variable comes into scope immediately.
1732  if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1733  variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1734 
1735  JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
1736 
1737  // Fast enumeration state.
1739  Address StatePtr = CreateMemTemp(StateTy, "state.ptr");
1740  EmitNullInitialization(StatePtr, StateTy);
1741 
1742  // Number of elements in the items array.
1743  static const unsigned NumItems = 16;
1744 
1745  // Fetch the countByEnumeratingWithState:objects:count: selector.
1746  IdentifierInfo *II[] = {
1747  &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1748  &CGM.getContext().Idents.get("objects"),
1749  &CGM.getContext().Idents.get("count")
1750  };
1751  Selector FastEnumSel =
1752  CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
1753 
1754  QualType ItemsTy =
1755  getContext().getConstantArrayType(getContext().getObjCIdType(),
1756  llvm::APInt(32, NumItems), nullptr,
1757  ArrayType::Normal, 0);
1758  Address ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
1759 
1760  // Emit the collection pointer. In ARC, we do a retain.
1761  llvm::Value *Collection;
1762  if (getLangOpts().ObjCAutoRefCount) {
1763  Collection = EmitARCRetainScalarExpr(S.getCollection());
1764 
1765  // Enter a cleanup to do the release.
1766  EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1767  } else {
1768  Collection = EmitScalarExpr(S.getCollection());
1769  }
1770 
1771  // The 'continue' label needs to appear within the cleanup for the
1772  // collection object.
1773  JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1774 
1775  // Send it our message:
1776  CallArgList Args;
1777 
1778  // The first argument is a temporary of the enumeration-state type.
1779  Args.add(RValue::get(StatePtr.getPointer()),
1780  getContext().getPointerType(StateTy));
1781 
1782  // The second argument is a temporary array with space for NumItems
1783  // pointers. We'll actually be loading elements from the array
1784  // pointer written into the control state; this buffer is so that
1785  // collections that *aren't* backed by arrays can still queue up
1786  // batches of elements.
1787  Args.add(RValue::get(ItemsPtr.getPointer()),
1788  getContext().getPointerType(ItemsTy));
1789 
1790  // The third argument is the capacity of that temporary array.
1791  llvm::Type *NSUIntegerTy = ConvertType(getContext().getNSUIntegerType());
1792  llvm::Constant *Count = llvm::ConstantInt::get(NSUIntegerTy, NumItems);
1793  Args.add(RValue::get(Count), getContext().getNSUIntegerType());
1794 
1795  // Start the enumeration.
1796  RValue CountRV =
1798  getContext().getNSUIntegerType(),
1799  FastEnumSel, Collection, Args);
1800 
1801  // The initial number of objects that were returned in the buffer.
1802  llvm::Value *initialBufferLimit = CountRV.getScalarVal();
1803 
1804  llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1805  llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
1806 
1807  llvm::Value *zero = llvm::Constant::getNullValue(NSUIntegerTy);
1808 
1809  // If the limit pointer was zero to begin with, the collection is
1810  // empty; skip all this. Set the branch weight assuming this has the same
1811  // probability of exiting the loop as any other loop exit.
1812  uint64_t EntryCount = getCurrentProfileCount();
1813  Builder.CreateCondBr(
1814  Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"), EmptyBB,
1815  LoopInitBB,
1816  createProfileWeights(EntryCount, getProfileCount(S.getBody())));
1817 
1818  // Otherwise, initialize the loop.
1819  EmitBlock(LoopInitBB);
1820 
1821  // Save the initial mutations value. This is the value at an
1822  // address that was written into the state object by
1823  // countByEnumeratingWithState:objects:count:.
1824  Address StateMutationsPtrPtr =
1825  Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
1826  llvm::Value *StateMutationsPtr
1827  = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
1828 
1829  llvm::Type *UnsignedLongTy = ConvertType(getContext().UnsignedLongTy);
1830  llvm::Value *initialMutations =
1831  Builder.CreateAlignedLoad(UnsignedLongTy, StateMutationsPtr,
1832  getPointerAlign(), "forcoll.initial-mutations");
1833 
1834  // Start looping. This is the point we return to whenever we have a
1835  // fresh, non-empty batch of objects.
1836  llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1837  EmitBlock(LoopBodyBB);
1838 
1839  // The current index into the buffer.
1840  llvm::PHINode *index = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.index");
1841  index->addIncoming(zero, LoopInitBB);
1842 
1843  // The current buffer size.
1844  llvm::PHINode *count = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.count");
1845  count->addIncoming(initialBufferLimit, LoopInitBB);
1846 
1848 
1849  // Check whether the mutations value has changed from where it was
1850  // at start. StateMutationsPtr should actually be invariant between
1851  // refreshes.
1852  StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
1853  llvm::Value *currentMutations
1854  = Builder.CreateAlignedLoad(UnsignedLongTy, StateMutationsPtr,
1855  getPointerAlign(), "statemutations");
1856 
1857  llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
1858  llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
1859 
1860  Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1861  WasNotMutatedBB, WasMutatedBB);
1862 
1863  // If so, call the enumeration-mutation function.
1864  EmitBlock(WasMutatedBB);
1865  llvm::Type *ObjCIdType = ConvertType(getContext().getObjCIdType());
1866  llvm::Value *V =
1867  Builder.CreateBitCast(Collection, ObjCIdType);
1868  CallArgList Args2;
1869  Args2.add(RValue::get(V), getContext().getObjCIdType());
1870  // FIXME: We shouldn't need to get the function info here, the runtime already
1871  // should have computed it to build the function.
1872  EmitCall(
1874  EnumerationMutationFn, ReturnValueSlot(), Args2);
1875 
1876  // Otherwise, or if the mutation function returns, just continue.
1877  EmitBlock(WasNotMutatedBB);
1878 
1879  // Initialize the element variable.
1880  RunCleanupsScope elementVariableScope(*this);
1881  bool elementIsVariable;
1882  LValue elementLValue;
1883  QualType elementType;
1884  if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
1885  // Initialize the variable, in case it's a __block variable or something.
1886  EmitAutoVarInit(variable);
1887 
1888  const VarDecl *D = cast<VarDecl>(SD->getSingleDecl());
1889  DeclRefExpr tempDRE(getContext(), const_cast<VarDecl *>(D), false,
1890  D->getType(), VK_LValue, SourceLocation());
1891  elementLValue = EmitLValue(&tempDRE);
1892  elementType = D->getType();
1893  elementIsVariable = true;
1894 
1895  if (D->isARCPseudoStrong())
1897  } else {
1898  elementLValue = LValue(); // suppress warning
1899  elementType = cast<Expr>(S.getElement())->getType();
1900  elementIsVariable = false;
1901  }
1902  llvm::Type *convertedElementType = ConvertType(elementType);
1903 
1904  // Fetch the buffer out of the enumeration state.
1905  // TODO: this pointer should actually be invariant between
1906  // refreshes, which would help us do certain loop optimizations.
1907  Address StateItemsPtr =
1908  Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
1909  llvm::Value *EnumStateItems =
1910  Builder.CreateLoad(StateItemsPtr, "stateitems");
1911 
1912  // Fetch the value at the current index from the buffer.
1913  llvm::Value *CurrentItemPtr = Builder.CreateGEP(
1914  ObjCIdType, EnumStateItems, index, "currentitem.ptr");
1915  llvm::Value *CurrentItem =
1916  Builder.CreateAlignedLoad(ObjCIdType, CurrentItemPtr, getPointerAlign());
1917 
1918  if (SanOpts.has(SanitizerKind::ObjCCast)) {
1919  // Before using an item from the collection, check that the implicit cast
1920  // from id to the element type is valid. This is done with instrumentation
1921  // roughly corresponding to:
1922  //
1923  // if (![item isKindOfClass:expectedCls]) { /* emit diagnostic */ }
1924  const ObjCObjectPointerType *ObjPtrTy =
1925  elementType->getAsObjCInterfacePointerType();
1926  const ObjCInterfaceType *InterfaceTy =
1927  ObjPtrTy ? ObjPtrTy->getInterfaceType() : nullptr;
1928  if (InterfaceTy) {
1929  SanitizerScope SanScope(this);
1930  auto &C = CGM.getContext();
1931  assert(InterfaceTy->getDecl() && "No decl for ObjC interface type");
1932  Selector IsKindOfClassSel = GetUnarySelector("isKindOfClass", C);
1933  CallArgList IsKindOfClassArgs;
1934  llvm::Value *Cls =
1935  CGM.getObjCRuntime().GetClass(*this, InterfaceTy->getDecl());
1936  IsKindOfClassArgs.add(RValue::get(Cls), C.getObjCClassType());
1937  llvm::Value *IsClass =
1939  .GenerateMessageSend(*this, ReturnValueSlot(), C.BoolTy,
1940  IsKindOfClassSel, CurrentItem,
1941  IsKindOfClassArgs)
1942  .getScalarVal();
1943  llvm::Constant *StaticData[] = {
1944  EmitCheckSourceLocation(S.getBeginLoc()),
1945  EmitCheckTypeDescriptor(QualType(InterfaceTy, 0))};
1946  EmitCheck({{IsClass, SanitizerKind::ObjCCast}},
1947  SanitizerHandler::InvalidObjCCast,
1948  ArrayRef<llvm::Constant *>(StaticData), CurrentItem);
1949  }
1950  }
1951 
1952  // Cast that value to the right type.
1953  CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1954  "currentitem");
1955 
1956  // Make sure we have an l-value. Yes, this gets evaluated every
1957  // time through the loop.
1958  if (!elementIsVariable) {
1959  elementLValue = EmitLValue(cast<Expr>(S.getElement()));
1960  EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
1961  } else {
1962  EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue,
1963  /*isInit*/ true);
1964  }
1965 
1966  // If we do have an element variable, this assignment is the end of
1967  // its initialization.
1968  if (elementIsVariable)
1969  EmitAutoVarCleanups(variable);
1970 
1971  // Perform the loop body, setting up break and continue labels.
1972  BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
1973  {
1974  RunCleanupsScope Scope(*this);
1975  EmitStmt(S.getBody());
1976  }
1977  BreakContinueStack.pop_back();
1978 
1979  // Destroy the element variable now.
1980  elementVariableScope.ForceCleanup();
1981 
1982  // Check whether there are more elements.
1983  EmitBlock(AfterBody.getBlock());
1984 
1985  llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
1986 
1987  // First we check in the local buffer.
1988  llvm::Value *indexPlusOne =
1989  Builder.CreateAdd(index, llvm::ConstantInt::get(NSUIntegerTy, 1));
1990 
1991  // If we haven't overrun the buffer yet, we can continue.
1992  // Set the branch weights based on the simplifying assumption that this is
1993  // like a while-loop, i.e., ignoring that the false branch fetches more
1994  // elements and then returns to the loop.
1995  Builder.CreateCondBr(
1996  Builder.CreateICmpULT(indexPlusOne, count), LoopBodyBB, FetchMoreBB,
1997  createProfileWeights(getProfileCount(S.getBody()), EntryCount));
1998 
1999  index->addIncoming(indexPlusOne, AfterBody.getBlock());
2000  count->addIncoming(count, AfterBody.getBlock());
2001 
2002  // Otherwise, we have to fetch more elements.
2003  EmitBlock(FetchMoreBB);
2004 
2005  CountRV =
2007  getContext().getNSUIntegerType(),
2008  FastEnumSel, Collection, Args);
2009 
2010  // If we got a zero count, we're done.
2011  llvm::Value *refetchCount = CountRV.getScalarVal();
2012 
2013  // (note that the message send might split FetchMoreBB)
2014  index->addIncoming(zero, Builder.GetInsertBlock());
2015  count->addIncoming(refetchCount, Builder.GetInsertBlock());
2016 
2017  Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
2018  EmptyBB, LoopBodyBB);
2019 
2020  // No more elements.
2021  EmitBlock(EmptyBB);
2022 
2023  if (!elementIsVariable) {
2024  // If the element was not a declaration, set it to be null.
2025 
2026  llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
2027  elementLValue = EmitLValue(cast<Expr>(S.getElement()));
2028  EmitStoreThroughLValue(RValue::get(null), elementLValue);
2029  }
2030 
2031  if (DI)
2032  DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
2033 
2034  ForScope.ForceCleanup();
2035  EmitBlock(LoopEnd.getBlock());
2036 }
2037 
2039  CGM.getObjCRuntime().EmitTryStmt(*this, S);
2040 }
2041 
2043  CGM.getObjCRuntime().EmitThrowStmt(*this, S);
2044 }
2045 
2047  const ObjCAtSynchronizedStmt &S) {
2049 }
2050 
2051 namespace {
2052  struct CallObjCRelease final : EHScopeStack::Cleanup {
2053  CallObjCRelease(llvm::Value *object) : object(object) {}
2054  llvm::Value *object;
2055 
2056  void Emit(CodeGenFunction &CGF, Flags flags) override {
2057  // Releases at the end of the full-expression are imprecise.
2058  CGF.EmitARCRelease(object, ARCImpreciseLifetime);
2059  }
2060  };
2061 }
2062 
2063 /// Produce the code for a CK_ARCConsumeObject. Does a primitive
2064 /// release at the end of the full-expression.
2066  llvm::Value *object) {
2067  // If we're in a conditional branch, we need to make the cleanup
2068  // conditional.
2069  pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
2070  return object;
2071 }
2072 
2074  llvm::Value *value) {
2075  return EmitARCRetainAutorelease(type, value);
2076 }
2077 
2078 /// Given a number of pointers, inform the optimizer that they're
2079 /// being intrinsically used up until this point in the program.
2081  llvm::Function *&fn = CGM.getObjCEntrypoints().clang_arc_use;
2082  if (!fn)
2083  fn = CGM.getIntrinsic(llvm::Intrinsic::objc_clang_arc_use);
2084 
2085  // This isn't really a "runtime" function, but as an intrinsic it
2086  // doesn't really matter as long as we align things up.
2087  EmitNounwindRuntimeCall(fn, values);
2088 }
2089 
2090 /// Emit a call to "clang.arc.noop.use", which consumes the result of a call
2091 /// that has operand bundle "clang.arc.attachedcall".
2093  llvm::Function *&fn = CGM.getObjCEntrypoints().clang_arc_noop_use;
2094  if (!fn)
2095  fn = CGM.getIntrinsic(llvm::Intrinsic::objc_clang_arc_noop_use);
2096  EmitNounwindRuntimeCall(fn, values);
2097 }
2098 
2099 static void setARCRuntimeFunctionLinkage(CodeGenModule &CGM, llvm::Value *RTF) {
2100  if (auto *F = dyn_cast<llvm::Function>(RTF)) {
2101  // If the target runtime doesn't naturally support ARC, emit weak
2102  // references to the runtime support library. We don't really
2103  // permit this to fail, but we need a particular relocation style.
2104  if (!CGM.getLangOpts().ObjCRuntime.hasNativeARC() &&
2105  !CGM.getTriple().isOSBinFormatCOFF()) {
2106  F->setLinkage(llvm::Function::ExternalWeakLinkage);
2107  }
2108  }
2109 }
2110 
2112  llvm::FunctionCallee RTF) {
2113  setARCRuntimeFunctionLinkage(CGM, RTF.getCallee());
2114 }
2115 
2116 static llvm::Function *getARCIntrinsic(llvm::Intrinsic::ID IntID,
2117  CodeGenModule &CGM) {
2118  llvm::Function *fn = CGM.getIntrinsic(IntID);
2120  return fn;
2121 }
2122 
2123 /// Perform an operation having the signature
2124 /// i8* (i8*)
2125 /// where a null input causes a no-op and returns null.
2126 static llvm::Value *emitARCValueOperation(
2127  CodeGenFunction &CGF, llvm::Value *value, llvm::Type *returnType,
2128  llvm::Function *&fn, llvm::Intrinsic::ID IntID,
2129  llvm::CallInst::TailCallKind tailKind = llvm::CallInst::TCK_None) {
2130  if (isa<llvm::ConstantPointerNull>(value))
2131  return value;
2132 
2133  if (!fn)
2134  fn = getARCIntrinsic(IntID, CGF.CGM);
2135 
2136  // Cast the argument to 'id'.
2137  llvm::Type *origType = returnType ? returnType : value->getType();
2138  value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
2139 
2140  // Call the function.
2141  llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(fn, value);
2142  call->setTailCallKind(tailKind);
2143 
2144  // Cast the result back to the original type.
2145  return CGF.Builder.CreateBitCast(call, origType);
2146 }
2147 
2148 /// Perform an operation having the following signature:
2149 /// i8* (i8**)
2150 static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF, Address addr,
2151  llvm::Function *&fn,
2152  llvm::Intrinsic::ID IntID) {
2153  if (!fn)
2154  fn = getARCIntrinsic(IntID, CGF.CGM);
2155 
2156  // Cast the argument to 'id*'.
2157  llvm::Type *origType = addr.getElementType();
2158  addr = CGF.Builder.CreateElementBitCast(addr, CGF.Int8PtrTy);
2159 
2160  // Call the function.
2161  llvm::Value *result = CGF.EmitNounwindRuntimeCall(fn, addr.getPointer());
2162 
2163  // Cast the result back to a dereference of the original type.
2164  if (origType != CGF.Int8PtrTy)
2165  result = CGF.Builder.CreateBitCast(result, origType);
2166 
2167  return result;
2168 }
2169 
2170 /// Perform an operation having the following signature:
2171 /// i8* (i8**, i8*)
2172 static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF, Address addr,
2173  llvm::Value *value,
2174  llvm::Function *&fn,
2175  llvm::Intrinsic::ID IntID,
2176  bool ignored) {
2177  assert(addr.getElementType() == value->getType());
2178 
2179  if (!fn)
2180  fn = getARCIntrinsic(IntID, CGF.CGM);
2181 
2182  llvm::Type *origType = value->getType();
2183 
2184  llvm::Value *args[] = {
2185  CGF.Builder.CreateBitCast(addr.getPointer(), CGF.Int8PtrPtrTy),
2186  CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy)
2187  };
2188  llvm::CallInst *result = CGF.EmitNounwindRuntimeCall(fn, args);
2189 
2190  if (ignored) return nullptr;
2191 
2192  return CGF.Builder.CreateBitCast(result, origType);
2193 }
2194 
2195 /// Perform an operation having the following signature:
2196 /// void (i8**, i8**)
2198  llvm::Function *&fn,
2199  llvm::Intrinsic::ID IntID) {
2200  assert(dst.getType() == src.getType());
2201 
2202  if (!fn)
2203  fn = getARCIntrinsic(IntID, CGF.CGM);
2204 
2205  llvm::Value *args[] = {
2206  CGF.Builder.CreateBitCast(dst.getPointer(), CGF.Int8PtrPtrTy),
2207  CGF.Builder.CreateBitCast(src.getPointer(), CGF.Int8PtrPtrTy)
2208  };
2209  CGF.EmitNounwindRuntimeCall(fn, args);
2210 }
2211 
2212 /// Perform an operation having the signature
2213 /// i8* (i8*)
2214 /// where a null input causes a no-op and returns null.
2215 static llvm::Value *emitObjCValueOperation(CodeGenFunction &CGF,
2216  llvm::Value *value,
2217  llvm::Type *returnType,
2218  llvm::FunctionCallee &fn,
2219  StringRef fnName) {
2220  if (isa<llvm::ConstantPointerNull>(value))
2221  return value;
2222 
2223  if (!fn) {
2224  llvm::FunctionType *fnType =
2225  llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, false);
2226  fn = CGF.CGM.CreateRuntimeFunction(fnType, fnName);
2227 
2228  // We have Native ARC, so set nonlazybind attribute for performance
2229  if (llvm::Function *f = dyn_cast<llvm::Function>(fn.getCallee()))
2230  if (fnName == "objc_retain")
2231  f->addFnAttr(llvm::Attribute::NonLazyBind);
2232  }
2233 
2234  // Cast the argument to 'id'.
2235  llvm::Type *origType = returnType ? returnType : value->getType();
2236  value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
2237 
2238  // Call the function.
2239  llvm::CallBase *Inst = CGF.EmitCallOrInvoke(fn, value);
2240 
2241  // Mark calls to objc_autorelease as tail on the assumption that methods
2242  // overriding autorelease do not touch anything on the stack.
2243  if (fnName == "objc_autorelease")
2244  if (auto *Call = dyn_cast<llvm::CallInst>(Inst))
2245  Call->setTailCall();
2246 
2247  // Cast the result back to the original type.
2248  return CGF.Builder.CreateBitCast(Inst, origType);
2249 }
2250 
2251 /// Produce the code to do a retain. Based on the type, calls one of:
2252 /// call i8* \@objc_retain(i8* %value)
2253 /// call i8* \@objc_retainBlock(i8* %value)
2254 llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
2255  if (type->isBlockPointerType())
2256  return EmitARCRetainBlock(value, /*mandatory*/ false);
2257  else
2258  return EmitARCRetainNonBlock(value);
2259 }
2260 
2261 /// Retain the given object, with normal retain semantics.
2262 /// call i8* \@objc_retain(i8* %value)
2263 llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
2264  return emitARCValueOperation(*this, value, nullptr,
2266  llvm::Intrinsic::objc_retain);
2267 }
2268 
2269 /// Retain the given block, with _Block_copy semantics.
2270 /// call i8* \@objc_retainBlock(i8* %value)
2271 ///
2272 /// \param mandatory - If false, emit the call with metadata
2273 /// indicating that it's okay for the optimizer to eliminate this call
2274 /// if it can prove that the block never escapes except down the stack.
2275 llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
2276  bool mandatory) {
2277  llvm::Value *result
2278  = emitARCValueOperation(*this, value, nullptr,
2280  llvm::Intrinsic::objc_retainBlock);
2281 
2282  // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
2283  // tell the optimizer that it doesn't need to do this copy if the
2284  // block doesn't escape, where being passed as an argument doesn't
2285  // count as escaping.
2286  if (!mandatory && isa<llvm::Instruction>(result)) {
2287  llvm::CallInst *call
2288  = cast<llvm::CallInst>(result->stripPointerCasts());
2289  assert(call->getCalledOperand() ==
2291 
2292  call->setMetadata("clang.arc.copy_on_escape",
2293  llvm::MDNode::get(Builder.getContext(), None));
2294  }
2295 
2296  return result;
2297 }
2298 
2300  // Fetch the void(void) inline asm which marks that we're going to
2301  // do something with the autoreleased return value.
2302  llvm::InlineAsm *&marker
2304  if (!marker) {
2305  StringRef assembly
2306  = CGF.CGM.getTargetCodeGenInfo()
2308 
2309  // If we have an empty assembly string, there's nothing to do.
2310  if (assembly.empty()) {
2311 
2312  // Otherwise, at -O0, build an inline asm that we're going to call
2313  // in a moment.
2314  } else if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
2315  llvm::FunctionType *type =
2316  llvm::FunctionType::get(CGF.VoidTy, /*variadic*/false);
2317 
2318  marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
2319 
2320  // If we're at -O1 and above, we don't want to litter the code
2321  // with this marker yet, so leave a breadcrumb for the ARC
2322  // optimizer to pick up.
2323  } else {
2324  const char *retainRVMarkerKey = llvm::objcarc::getRVMarkerModuleFlagStr();
2325  if (!CGF.CGM.getModule().getModuleFlag(retainRVMarkerKey)) {
2326  auto *str = llvm::MDString::get(CGF.getLLVMContext(), assembly);
2327  CGF.CGM.getModule().addModuleFlag(llvm::Module::Error,
2328  retainRVMarkerKey, str);
2329  }
2330  }
2331  }
2332 
2333  // Call the marker asm if we made one, which we do only at -O0.
2334  if (marker)
2335  CGF.Builder.CreateCall(marker, None, CGF.getBundlesForFunclet(marker));
2336 }
2337 
2338 static llvm::Value *emitOptimizedARCReturnCall(llvm::Value *value,
2339  bool IsRetainRV,
2340  CodeGenFunction &CGF) {
2342 
2343  // Add operand bundle "clang.arc.attachedcall" to the call instead of emitting
2344  // retainRV or claimRV calls in the IR. We currently do this only when the
2345  // optimization level isn't -O0 since global-isel, which is currently run at
2346  // -O0, doesn't know about the operand bundle.
2347  ObjCEntrypoints &EPs = CGF.CGM.getObjCEntrypoints();
2348  llvm::Function *&EP = IsRetainRV
2351  llvm::Intrinsic::ID IID =
2352  IsRetainRV ? llvm::Intrinsic::objc_retainAutoreleasedReturnValue
2353  : llvm::Intrinsic::objc_unsafeClaimAutoreleasedReturnValue;
2354  EP = getARCIntrinsic(IID, CGF.CGM);
2355 
2356  llvm::Triple::ArchType Arch = CGF.CGM.getTriple().getArch();
2357 
2358  // FIXME: Do this on all targets and at -O0 too. This can be enabled only if
2359  // the target backend knows how to handle the operand bundle.
2360  if (CGF.CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2361  (Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::x86_64)) {
2362  llvm::Value *bundleArgs[] = {EP};
2363  llvm::OperandBundleDef OB("clang.arc.attachedcall", bundleArgs);
2364  auto *oldCall = cast<llvm::CallBase>(value);
2365  llvm::CallBase *newCall = llvm::CallBase::addOperandBundle(
2366  oldCall, llvm::LLVMContext::OB_clang_arc_attachedcall, OB, oldCall);
2367  newCall->copyMetadata(*oldCall);
2368  oldCall->replaceAllUsesWith(newCall);
2369  oldCall->eraseFromParent();
2370  CGF.EmitARCNoopIntrinsicUse(newCall);
2371  return newCall;
2372  }
2373 
2374  bool isNoTail =
2376  llvm::CallInst::TailCallKind tailKind =
2377  isNoTail ? llvm::CallInst::TCK_NoTail : llvm::CallInst::TCK_None;
2378  return emitARCValueOperation(CGF, value, nullptr, EP, IID, tailKind);
2379 }
2380 
2381 /// Retain the given object which is the result of a function call.
2382 /// call i8* \@objc_retainAutoreleasedReturnValue(i8* %value)
2383 ///
2384 /// Yes, this function name is one character away from a different
2385 /// call with completely different semantics.
2386 llvm::Value *
2388  return emitOptimizedARCReturnCall(value, true, *this);
2389 }
2390 
2391 /// Claim a possibly-autoreleased return value at +0. This is only
2392 /// valid to do in contexts which do not rely on the retain to keep
2393 /// the object valid for all of its uses; for example, when
2394 /// the value is ignored, or when it is being assigned to an
2395 /// __unsafe_unretained variable.
2396 ///
2397 /// call i8* \@objc_unsafeClaimAutoreleasedReturnValue(i8* %value)
2398 llvm::Value *
2400  return emitOptimizedARCReturnCall(value, false, *this);
2401 }
2402 
2403 /// Release the given object.
2404 /// call void \@objc_release(i8* %value)
2405 void CodeGenFunction::EmitARCRelease(llvm::Value *value,
2406  ARCPreciseLifetime_t precise) {
2407  if (isa<llvm::ConstantPointerNull>(value)) return;
2408 
2409  llvm::Function *&fn = CGM.getObjCEntrypoints().objc_release;
2410  if (!fn)
2411  fn = getARCIntrinsic(llvm::Intrinsic::objc_release, CGM);
2412 
2413  // Cast the argument to 'id'.
2414  value = Builder.CreateBitCast(value, Int8PtrTy);
2415 
2416  // Call objc_release.
2417  llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);
2418 
2419  if (precise == ARCImpreciseLifetime) {
2420  call->setMetadata("clang.imprecise_release",
2421  llvm::MDNode::get(Builder.getContext(), None));
2422  }
2423 }
2424 
2425 /// Destroy a __strong variable.
2426 ///
2427 /// At -O0, emit a call to store 'null' into the address;
2428 /// instrumenting tools prefer this because the address is exposed,
2429 /// but it's relatively cumbersome to optimize.
2430 ///
2431 /// At -O1 and above, just load and call objc_release.
2432 ///
2433 /// call void \@objc_storeStrong(i8** %addr, i8* null)
2435  ARCPreciseLifetime_t precise) {
2436  if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2437  llvm::Value *null = getNullForVariable(addr);
2438  EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
2439  return;
2440  }
2441 
2442  llvm::Value *value = Builder.CreateLoad(addr);
2443  EmitARCRelease(value, precise);
2444 }
2445 
2446 /// Store into a strong object. Always calls this:
2447 /// call void \@objc_storeStrong(i8** %addr, i8* %value)
2449  llvm::Value *value,
2450  bool ignored) {
2451  assert(addr.getElementType() == value->getType());
2452 
2453  llvm::Function *&fn = CGM.getObjCEntrypoints().objc_storeStrong;
2454  if (!fn)
2455  fn = getARCIntrinsic(llvm::Intrinsic::objc_storeStrong, CGM);
2456 
2457  llvm::Value *args[] = {
2458  Builder.CreateBitCast(addr.getPointer(), Int8PtrPtrTy),
2459  Builder.CreateBitCast(value, Int8PtrTy)
2460  };
2461  EmitNounwindRuntimeCall(fn, args);
2462 
2463  if (ignored) return nullptr;
2464  return value;
2465 }
2466 
2467 /// Store into a strong object. Sometimes calls this:
2468 /// call void \@objc_storeStrong(i8** %addr, i8* %value)
2469 /// Other times, breaks it down into components.
2471  llvm::Value *newValue,
2472  bool ignored) {
2473  QualType type = dst.getType();
2474  bool isBlock = type->isBlockPointerType();
2475 
2476  // Use a store barrier at -O0 unless this is a block type or the
2477  // lvalue is inadequately aligned.
2478  if (shouldUseFusedARCCalls() &&
2479  !isBlock &&
2480  (dst.getAlignment().isZero() ||
2482  return EmitARCStoreStrongCall(dst.getAddress(*this), newValue, ignored);
2483  }
2484 
2485  // Otherwise, split it out.
2486 
2487  // Retain the new value.
2488  newValue = EmitARCRetain(type, newValue);
2489 
2490  // Read the old value.
2491  llvm::Value *oldValue = EmitLoadOfScalar(dst, SourceLocation());
2492 
2493  // Store. We do this before the release so that any deallocs won't
2494  // see the old value.
2495  EmitStoreOfScalar(newValue, dst);
2496 
2497  // Finally, release the old value.
2498  EmitARCRelease(oldValue, dst.isARCPreciseLifetime());
2499 
2500  return newValue;
2501 }
2502 
2503 /// Autorelease the given object.
2504 /// call i8* \@objc_autorelease(i8* %value)
2505 llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
2506  return emitARCValueOperation(*this, value, nullptr,
2508  llvm::Intrinsic::objc_autorelease);
2509 }
2510 
2511 /// Autorelease the given object.
2512 /// call i8* \@objc_autoreleaseReturnValue(i8* %value)
2513 llvm::Value *
2515  return emitARCValueOperation(*this, value, nullptr,
2517  llvm::Intrinsic::objc_autoreleaseReturnValue,
2518  llvm::CallInst::TCK_Tail);
2519 }
2520 
2521 /// Do a fused retain/autorelease of the given object.
2522 /// call i8* \@objc_retainAutoreleaseReturnValue(i8* %value)
2523 llvm::Value *
2525  return emitARCValueOperation(*this, value, nullptr,
2527  llvm::Intrinsic::objc_retainAutoreleaseReturnValue,
2528  llvm::CallInst::TCK_Tail);
2529 }
2530 
2531 /// Do a fused retain/autorelease of the given object.
2532 /// call i8* \@objc_retainAutorelease(i8* %value)
2533 /// or
2534 /// %retain = call i8* \@objc_retainBlock(i8* %value)
2535 /// call i8* \@objc_autorelease(i8* %retain)
2537  llvm::Value *value) {
2538  if (!type->isBlockPointerType())
2539  return EmitARCRetainAutoreleaseNonBlock(value);
2540 
2541  if (isa<llvm::ConstantPointerNull>(value)) return value;
2542 
2543  llvm::Type *origType = value->getType();
2544  value = Builder.CreateBitCast(value, Int8PtrTy);
2545  value = EmitARCRetainBlock(value, /*mandatory*/ true);
2546  value = EmitARCAutorelease(value);
2547  return Builder.CreateBitCast(value, origType);
2548 }
2549 
2550 /// Do a fused retain/autorelease of the given object.
2551 /// call i8* \@objc_retainAutorelease(i8* %value)
2552 llvm::Value *
2554  return emitARCValueOperation(*this, value, nullptr,
2556  llvm::Intrinsic::objc_retainAutorelease);
2557 }
2558 
2559 /// i8* \@objc_loadWeak(i8** %addr)
2560 /// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
2562  return emitARCLoadOperation(*this, addr,
2564  llvm::Intrinsic::objc_loadWeak);
2565 }
2566 
2567 /// i8* \@objc_loadWeakRetained(i8** %addr)
2569  return emitARCLoadOperation(*this, addr,
2571  llvm::Intrinsic::objc_loadWeakRetained);
2572 }
2573 
2574 /// i8* \@objc_storeWeak(i8** %addr, i8* %value)
2575 /// Returns %value.
2577  llvm::Value *value,
2578  bool ignored) {
2579  return emitARCStoreOperation(*this, addr, value,
2581  llvm::Intrinsic::objc_storeWeak, ignored);
2582 }
2583 
2584 /// i8* \@objc_initWeak(i8** %addr, i8* %value)
2585 /// Returns %value. %addr is known to not have a current weak entry.
2586 /// Essentially equivalent to:
2587 /// *addr = nil; objc_storeWeak(addr, value);
2588 void CodeGenFunction::EmitARCInitWeak(Address addr, llvm::Value *value) {
2589  // If we're initializing to null, just write null to memory; no need
2590  // to get the runtime involved. But don't do this if optimization
2591  // is enabled, because accounting for this would make the optimizer
2592  // much more complicated.
2593  if (isa<llvm::ConstantPointerNull>(value) &&
2594  CGM.getCodeGenOpts().OptimizationLevel == 0) {
2595  Builder.CreateStore(value, addr);
2596  return;
2597  }
2598 
2599  emitARCStoreOperation(*this, addr, value,
2601  llvm::Intrinsic::objc_initWeak, /*ignored*/ true);
2602 }
2603 
2604 /// void \@objc_destroyWeak(i8** %addr)
2605 /// Essentially objc_storeWeak(addr, nil).
2607  llvm::Function *&fn = CGM.getObjCEntrypoints().objc_destroyWeak;
2608  if (!fn)
2609  fn = getARCIntrinsic(llvm::Intrinsic::objc_destroyWeak, CGM);
2610 
2611  // Cast the argument to 'id*'.
2612  addr = Builder.CreateElementBitCast(addr, Int8PtrTy);
2613 
2614  EmitNounwindRuntimeCall(fn, addr.getPointer());
2615 }
2616 
2617 /// void \@objc_moveWeak(i8** %dest, i8** %src)
2618 /// Disregards the current value in %dest. Leaves %src pointing to nothing.
2619 /// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
2621  emitARCCopyOperation(*this, dst, src,
2623  llvm::Intrinsic::objc_moveWeak);
2624 }
2625 
2626 /// void \@objc_copyWeak(i8** %dest, i8** %src)
2627 /// Disregards the current value in %dest. Essentially
2628 /// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
2630  emitARCCopyOperation(*this, dst, src,
2632  llvm::Intrinsic::objc_copyWeak);
2633 }
2634 
2636  Address SrcAddr) {
2637  llvm::Value *Object = EmitARCLoadWeakRetained(SrcAddr);
2638  Object = EmitObjCConsumeObject(Ty, Object);
2639  EmitARCStoreWeak(DstAddr, Object, false);
2640 }
2641 
2643  Address SrcAddr) {
2644  llvm::Value *Object = EmitARCLoadWeakRetained(SrcAddr);
2645  Object = EmitObjCConsumeObject(Ty, Object);
2646  EmitARCStoreWeak(DstAddr, Object, false);
2647  EmitARCDestroyWeak(SrcAddr);
2648 }
2649 
2650 /// Produce the code to do a objc_autoreleasepool_push.
2651 /// call i8* \@objc_autoreleasePoolPush(void)
2653  llvm::Function *&fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPush;
2654  if (!fn)
2655  fn = getARCIntrinsic(llvm::Intrinsic::objc_autoreleasePoolPush, CGM);
2656 
2657  return EmitNounwindRuntimeCall(fn);
2658 }
2659 
2660 /// Produce the code to do a primitive release.
2661 /// call void \@objc_autoreleasePoolPop(i8* %ptr)
2663  assert(value->getType() == Int8PtrTy);
2664 
2665  if (getInvokeDest()) {
2666  // Call the runtime method not the intrinsic if we are handling exceptions
2667  llvm::FunctionCallee &fn =
2669  if (!fn) {
2670  llvm::FunctionType *fnType =
2671  llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
2672  fn = CGM.CreateRuntimeFunction(fnType, "objc_autoreleasePoolPop");
2674  }
2675 
2676  // objc_autoreleasePoolPop can throw.
2677  EmitRuntimeCallOrInvoke(fn, value);
2678  } else {
2679  llvm::FunctionCallee &fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPop;
2680  if (!fn)
2681  fn = getARCIntrinsic(llvm::Intrinsic::objc_autoreleasePoolPop, CGM);
2682 
2683  EmitRuntimeCall(fn, value);
2684  }
2685 }
2686 
2687 /// Produce the code to do an MRR version objc_autoreleasepool_push.
2688 /// Which is: [[NSAutoreleasePool alloc] init];
2689 /// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2690 /// init is declared as: - (id) init; in its NSObject super class.
2691 ///
2693  CGObjCRuntime &Runtime = CGM.getObjCRuntime();
2694  llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(*this);
2695  // [NSAutoreleasePool alloc]
2696  IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2697  Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2698  CallArgList Args;
2699  RValue AllocRV =
2700  Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2701  getContext().getObjCIdType(),
2702  AllocSel, Receiver, Args);
2703 
2704  // [Receiver init]
2705  Receiver = AllocRV.getScalarVal();
2706  II = &CGM.getContext().Idents.get("init");
2707  Selector InitSel = getContext().Selectors.getSelector(0, &II);
2708  RValue InitRV =
2709  Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2710  getContext().getObjCIdType(),
2711  InitSel, Receiver, Args);
2712  return InitRV.getScalarVal();
2713 }
2714 
2715 /// Allocate the given objc object.
2716 /// call i8* \@objc_alloc(i8* %value)
2717 llvm::Value *CodeGenFunction::EmitObjCAlloc(llvm::Value *value,
2718  llvm::Type *resultType) {
2719  return emitObjCValueOperation(*this, value, resultType,
2721  "objc_alloc");
2722 }
2723 
2724 /// Allocate the given objc object.
2725 /// call i8* \@objc_allocWithZone(i8* %value)
2726 llvm::Value *CodeGenFunction::EmitObjCAllocWithZone(llvm::Value *value,
2727  llvm::Type *resultType) {
2728  return emitObjCValueOperation(*this, value, resultType,
2730  "objc_allocWithZone");
2731 }
2732 
2733 llvm::Value *CodeGenFunction::EmitObjCAllocInit(llvm::Value *value,
2734  llvm::Type *resultType) {
2735  return emitObjCValueOperation(*this, value, resultType,
2737  "objc_alloc_init");
2738 }
2739 
2740 /// Produce the code to do a primitive release.
2741 /// [tmp drain];
2743  IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2744  Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2745  CallArgList Args;
2747  getContext().VoidTy, DrainSel, Arg, Args);
2748 }
2749 
2751  Address addr,
2752  QualType type) {
2754 }
2755 
2757  Address addr,
2758  QualType type) {
2760 }
2761 
2763  Address addr,
2764  QualType type) {
2765  CGF.EmitARCDestroyWeak(addr);
2766 }
2767 
2769  QualType type) {
2770  llvm::Value *value = CGF.Builder.CreateLoad(addr);
2771  CGF.EmitARCIntrinsicUse(value);
2772 }
2773 
2774 /// Autorelease the given object.
2775 /// call i8* \@objc_autorelease(i8* %value)
2776 llvm::Value *CodeGenFunction::EmitObjCAutorelease(llvm::Value *value,
2777  llvm::Type *returnType) {
2778  return emitObjCValueOperation(
2779  *this, value, returnType,
2781  "objc_autorelease");
2782 }
2783 
2784 /// Retain the given object, with normal retain semantics.
2785 /// call i8* \@objc_retain(i8* %value)
2786 llvm::Value *CodeGenFunction::EmitObjCRetainNonBlock(llvm::Value *value,
2787  llvm::Type *returnType) {
2788  return emitObjCValueOperation(
2789  *this, value, returnType,
2791 }
2792 
2793 /// Release the given object.
2794 /// call void \@objc_release(i8* %value)
2795 void CodeGenFunction::EmitObjCRelease(llvm::Value *value,
2796  ARCPreciseLifetime_t precise) {
2797  if (isa<llvm::ConstantPointerNull>(value)) return;
2798 
2799  llvm::FunctionCallee &fn =
2801  if (!fn) {
2802  llvm::FunctionType *fnType =
2803  llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
2804  fn = CGM.CreateRuntimeFunction(fnType, "objc_release");
2806  // We have Native ARC, so set nonlazybind attribute for performance
2807  if (llvm::Function *f = dyn_cast<llvm::Function>(fn.getCallee()))
2808  f->addFnAttr(llvm::Attribute::NonLazyBind);
2809  }
2810 
2811  // Cast the argument to 'id'.
2812  value = Builder.CreateBitCast(value, Int8PtrTy);
2813 
2814  // Call objc_release.
2815  llvm::CallBase *call = EmitCallOrInvoke(fn, value);
2816 
2817  if (precise == ARCImpreciseLifetime) {
2818  call->setMetadata("clang.imprecise_release",
2819  llvm::MDNode::get(Builder.getContext(), None));
2820  }
2821 }
2822 
2823 namespace {
2824  struct CallObjCAutoreleasePoolObject final : EHScopeStack::Cleanup {
2825  llvm::Value *Token;
2826 
2827  CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2828 
2829  void Emit(CodeGenFunction &CGF, Flags flags) override {
2831  }
2832  };
2833  struct CallObjCMRRAutoreleasePoolObject final : EHScopeStack::Cleanup {
2834  llvm::Value *Token;
2835 
2836  CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2837 
2838  void Emit(CodeGenFunction &CGF, Flags flags) override {
2840  }
2841  };
2842 }
2843 
2845  if (CGM.getLangOpts().ObjCAutoRefCount)
2846  EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2847  else
2848  EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2849 }
2850 
2852  switch (lifetime) {
2853  case Qualifiers::OCL_None:
2857  return true;
2858 
2859  case Qualifiers::OCL_Weak:
2860  return false;
2861  }
2862 
2863  llvm_unreachable("impossible lifetime!");
2864 }
2865 
2867  LValue lvalue,
2868  QualType type) {
2869  llvm::Value *result;
2870  bool shouldRetain = shouldRetainObjCLifetime(type.getObjCLifetime());
2871  if (shouldRetain) {
2872  result = CGF.EmitLoadOfLValue(lvalue, SourceLocation()).getScalarVal();
2873  } else {
2874  assert(type.getObjCLifetime() == Qualifiers::OCL_Weak);
2875  result = CGF.EmitARCLoadWeakRetained(lvalue.getAddress(CGF));
2876  }
2877  return TryEmitResult(result, !shouldRetain);
2878 }
2879 
2881  const Expr *e) {
2882  e = e->IgnoreParens();
2883  QualType type = e->getType();
2884 
2885  // If we're loading retained from a __strong xvalue, we can avoid
2886  // an extra retain/release pair by zeroing out the source of this
2887  // "move" operation.
2888  if (e->isXValue() &&
2889  !type.isConstQualified() &&
2890  type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2891  // Emit the lvalue.
2892  LValue lv = CGF.EmitLValue(e);
2893 
2894  // Load the object pointer.
2895  llvm::Value *result = CGF.EmitLoadOfLValue(lv,
2897 
2898  // Set the source pointer to NULL.
2900 
2901  return TryEmitResult(result, true);
2902  }
2903 
2904  // As a very special optimization, in ARC++, if the l-value is the
2905  // result of a non-volatile assignment, do a simple retain of the
2906  // result of the call to objc_storeWeak instead of reloading.
2907  if (CGF.getLangOpts().CPlusPlus &&
2908  !type.isVolatileQualified() &&
2909  type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2910  isa<BinaryOperator>(e) &&
2911  cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2912  return TryEmitResult(CGF.EmitScalarExpr(e), false);
2913 
2914  // Try to emit code for scalar constant instead of emitting LValue and
2915  // loading it because we are not guaranteed to have an l-value. One of such
2916  // cases is DeclRefExpr referencing non-odr-used constant-evaluated variable.
2917  if (const auto *decl_expr = dyn_cast<DeclRefExpr>(e)) {
2918  auto *DRE = const_cast<DeclRefExpr *>(decl_expr);
2919  if (CodeGenFunction::ConstantEmission constant = CGF.tryEmitAsConstant(DRE))
2920  return TryEmitResult(CGF.emitScalarConstant(constant, DRE),
2921  !shouldRetainObjCLifetime(type.getObjCLifetime()));
2922  }
2923 
2924  return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2925 }
2926 
2927 typedef llvm::function_ref<llvm::Value *(CodeGenFunction &CGF,
2928  llvm::Value *value)>
2930 
2931 /// Insert code immediately after a call.
2932 
2933 // FIXME: We should find a way to emit the runtime call immediately
2934 // after the call is emitted to eliminate the need for this function.
2936  llvm::Value *value,
2937  ValueTransform doAfterCall,
2938  ValueTransform doFallback) {
2939  CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2940  auto *callBase = dyn_cast<llvm::CallBase>(value);
2941 
2942  if (callBase && llvm::objcarc::hasAttachedCallOpBundle(callBase)) {
2943  // Fall back if the call base has operand bundle "clang.arc.attachedcall".
2944  value = doFallback(CGF, value);
2945  } else if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2946  // Place the retain immediately following the call.
2947  CGF.Builder.SetInsertPoint(call->getParent(),
2948  ++llvm::BasicBlock::iterator(call));
2949  value = doAfterCall(CGF, value);
2950  } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2951  // Place the retain at the beginning of the normal destination block.
2952  llvm::BasicBlock *BB = invoke->getNormalDest();
2953  CGF.Builder.SetInsertPoint(BB, BB->begin());
2954  value = doAfterCall(CGF, value);
2955 
2956  // Bitcasts can arise because of related-result returns. Rewrite
2957  // the operand.
2958  } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2959  // Change the insert point to avoid emitting the fall-back call after the
2960  // bitcast.
2961  CGF.Builder.SetInsertPoint(bitcast->getParent(), bitcast->getIterator());
2962  llvm::Value *operand = bitcast->getOperand(0);
2963  operand = emitARCOperationAfterCall(CGF, operand, doAfterCall, doFallback);
2964  bitcast->setOperand(0, operand);
2965  value = bitcast;
2966  } else {
2967  auto *phi = dyn_cast<llvm::PHINode>(value);
2968  if (phi && phi->getNumIncomingValues() == 2 &&
2969  isa<llvm::ConstantPointerNull>(phi->getIncomingValue(1)) &&
2970  isa<llvm::CallBase>(phi->getIncomingValue(0))) {
2971  // Handle phi instructions that are generated when it's necessary to check
2972  // whether the receiver of a message is null.
2973  llvm::Value *inVal = phi->getIncomingValue(0);
2974  inVal = emitARCOperationAfterCall(CGF, inVal, doAfterCall, doFallback);
2975  phi->setIncomingValue(0, inVal);
2976  value = phi;
2977  } else {
2978  // Generic fall-back case.
2979  // Retain using the non-block variant: we never need to do a copy
2980  // of a block that's been returned to us.
2981  value = doFallback(CGF, value);
2982  }
2983  }
2984 
2985  CGF.Builder.restoreIP(ip);
2986  return value;
2987 }
2988 
2989 /// Given that the given expression is some sort of call (which does
2990 /// not return retained), emit a retain following it.
2991 static llvm::Value *emitARCRetainCallResult(CodeGenFunction &CGF,
2992  const Expr *e) {
2993  llvm::Value *value = CGF.EmitScalarExpr(e);
2994  return emitARCOperationAfterCall(CGF, value,
2995  [](CodeGenFunction &CGF, llvm::Value *value) {
2996  return CGF.EmitARCRetainAutoreleasedReturnValue(value);
2997  },
2998  [](CodeGenFunction &CGF, llvm::Value *value) {
2999  return CGF.EmitARCRetainNonBlock(value);
3000  });
3001 }
3002 
3003 /// Given that the given expression is some sort of call (which does
3004 /// not return retained), perform an unsafeClaim following it.
3006  const Expr *e) {
3007  llvm::Value *value = CGF.EmitScalarExpr(e);
3008  return emitARCOperationAfterCall(CGF, value,
3009  [](CodeGenFunction &CGF, llvm::Value *value) {
3011  },
3012  [](CodeGenFunction &CGF, llvm::Value *value) {
3013  return value;
3014  });
3015 }
3016 
3018  bool allowUnsafeClaim) {
3019  if (allowUnsafeClaim &&
3021  return emitARCUnsafeClaimCallResult(*this, E);
3022  } else {
3023  llvm::Value *value = emitARCRetainCallResult(*this, E);
3024  return EmitObjCConsumeObject(E->getType(), value);
3025  }
3026 }
3027 
3028 /// Determine whether it might be important to emit a separate
3029 /// objc_retain_block on the result of the given expression, or
3030 /// whether it's okay to just emit it in a +1 context.
3031 static bool shouldEmitSeparateBlockRetain(const Expr *e) {
3032  assert(e->getType()->isBlockPointerType());
3033  e = e->IgnoreParens();
3034 
3035  // For future goodness, emit block expressions directly in +1
3036  // contexts if we can.
3037  if (isa<BlockExpr>(e))
3038  return false;
3039 
3040  if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
3041  switch (cast->getCastKind()) {
3042  // Emitting these operations in +1 contexts is goodness.
3043  case CK_LValueToRValue:
3044  case CK_ARCReclaimReturnedObject:
3045  case CK_ARCConsumeObject:
3046  case CK_ARCProduceObject:
3047  return false;
3048 
3049  // These operations preserve a block type.
3050  case CK_NoOp:
3051  case CK_BitCast:
3052  return shouldEmitSeparateBlockRetain(cast->getSubExpr());
3053 
3054  // These operations are known to be bad (or haven't been considered).
3055  case CK_AnyPointerToBlockPointerCast:
3056  default:
3057  return true;
3058  }
3059  }
3060 
3061  return true;
3062 }
3063 
3064 namespace {
3065 /// A CRTP base class for emitting expressions of retainable object
3066 /// pointer type in ARC.
3067 template <typename Impl, typename Result> class ARCExprEmitter {
3068 protected:
3069  CodeGenFunction &CGF;
3070  Impl &asImpl() { return *static_cast<Impl*>(this); }
3071 
3072  ARCExprEmitter(CodeGenFunction &CGF) : CGF(CGF) {}
3073 
3074 public:
3075  Result visit(const Expr *e);
3076  Result visitCastExpr(const CastExpr *e);
3077  Result visitPseudoObjectExpr(const PseudoObjectExpr *e);
3078  Result visitBlockExpr(const BlockExpr *e);
3079  Result visitBinaryOperator(const BinaryOperator *e);
3080  Result visitBinAssign(const BinaryOperator *e);
3081  Result visitBinAssignUnsafeUnretained(const BinaryOperator *e);
3082  Result visitBinAssignAutoreleasing(const BinaryOperator *e);
3083  Result visitBinAssignWeak(const BinaryOperator *e);
3084  Result visitBinAssignStrong(const BinaryOperator *e);
3085 
3086  // Minimal implementation:
3087  // Result visitLValueToRValue(const Expr *e)
3088  // Result visitConsumeObject(const Expr *e)
3089  // Result visitExtendBlockObject(const Expr *e)
3090  // Result visitReclaimReturnedObject(const Expr *e)
3091  // Result visitCall(const Expr *e)
3092  // Result visitExpr(const Expr *e)
3093  //
3094  // Result emitBitCast(Result result, llvm::Type *resultType)
3095  // llvm::Value *getValueOfResult(Result result)
3096 };
3097 }
3098 
3099 /// Try to emit a PseudoObjectExpr under special ARC rules.
3100 ///
3101 /// This massively duplicates emitPseudoObjectRValue.
3102 template <typename Impl, typename Result>
3103 Result
3104 ARCExprEmitter<Impl,Result>::visitPseudoObjectExpr(const PseudoObjectExpr *E) {
3106 
3107  // Find the result expression.
3108  const Expr *resultExpr = E->getResultExpr();
3109  assert(resultExpr);
3110  Result result;
3111 
3113  i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
3114  const Expr *semantic = *i;
3115 
3116  // If this semantic expression is an opaque value, bind it
3117  // to the result of its source expression.
3118  if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
3120  OVMA opaqueData;
3121 
3122  // If this semantic is the result of the pseudo-object
3123  // expression, try to evaluate the source as +1.
3124  if (ov == resultExpr) {
3125  assert(!OVMA::shouldBindAsLValue(ov));
3126  result = asImpl().visit(ov->getSourceExpr());
3127  opaqueData = OVMA::bind(CGF, ov,
3128  RValue::get(asImpl().getValueOfResult(result)));
3129 
3130  // Otherwise, just bind it.
3131  } else {
3132  opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
3133  }
3134  opaques.push_back(opaqueData);
3135 
3136  // Otherwise, if the expression is the result, evaluate it
3137  // and remember the result.
3138  } else if (semantic == resultExpr) {
3139  result = asImpl().visit(semantic);
3140 
3141  // Otherwise, evaluate the expression in an ignored context.
3142  } else {
3143  CGF.EmitIgnoredExpr(semantic);
3144  }
3145  }
3146 
3147  // Unbind all the opaques now.
3148  for (unsigned i = 0, e = opaques.size(); i != e; ++i)
3149  opaques[i].unbind(CGF);
3150 
3151  return result;
3152 }
3153 
3154 template <typename Impl, typename Result>
3155 Result ARCExprEmitter<Impl, Result>::visitBlockExpr(const BlockExpr *e) {
3156  // The default implementation just forwards the expression to visitExpr.
3157  return asImpl().visitExpr(e);
3158 }
3159 
3160 template <typename Impl, typename Result>
3161 Result ARCExprEmitter<Impl,Result>::visitCastExpr(const CastExpr *e) {
3162  switch (e->getCastKind()) {
3163 
3164  // No-op casts don't change the type, so we just ignore them.
3165  case CK_NoOp:
3166  return asImpl().visit(e->getSubExpr());
3167 
3168  // These casts can change the type.
3169  case CK_CPointerToObjCPointerCast:
3170  case CK_BlockPointerToObjCPointerCast:
3171  case CK_AnyPointerToBlockPointerCast:
3172  case CK_BitCast: {
3173  llvm::Type *resultType = CGF.ConvertType(e->getType());
3174  assert(e->getSubExpr()->getType()->hasPointerRepresentation());
3175  Result result = asImpl().visit(e->getSubExpr());
3176  return asImpl().emitBitCast(result, resultType);
3177  }
3178 
3179  // Handle some casts specially.
3180  case CK_LValueToRValue:
3181  return asImpl().visitLValueToRValue(e->getSubExpr());
3182  case CK_ARCConsumeObject:
3183  return asImpl().visitConsumeObject(e->getSubExpr());
3184  case CK_ARCExtendBlockObject:
3185  return asImpl().visitExtendBlockObject(e->getSubExpr());
3186  case CK_ARCReclaimReturnedObject:
3187  return asImpl().visitReclaimReturnedObject(e->getSubExpr());
3188 
3189  // Otherwise, use the default logic.
3190  default:
3191  return asImpl().visitExpr(e);
3192  }
3193 }
3194 
3195 template <typename Impl, typename Result>
3196 Result
3197 ARCExprEmitter<Impl,Result>::visitBinaryOperator(const BinaryOperator *e) {
3198  switch (e->getOpcode()) {
3199  case BO_Comma:
3200  CGF.EmitIgnoredExpr(e->getLHS());
3201  CGF.EnsureInsertPoint();
3202  return asImpl().visit(e->getRHS());
3203 
3204  case BO_Assign:
3205  return asImpl().visitBinAssign(e);
3206 
3207  default:
3208  return asImpl().visitExpr(e);
3209  }
3210 }
3211 
3212 template <typename Impl, typename Result>
3213 Result ARCExprEmitter<Impl,Result>::visitBinAssign(const BinaryOperator *e) {
3214  switch (e->getLHS()->getType().getObjCLifetime()) {
3216  return asImpl().visitBinAssignUnsafeUnretained(e);
3217 
3218  case Qualifiers::OCL_Weak:
3219  return asImpl().visitBinAssignWeak(e);
3220 
3222  return asImpl().visitBinAssignAutoreleasing(e);
3223 
3225  return asImpl().visitBinAssignStrong(e);
3226 
3227  case Qualifiers::OCL_None:
3228  return asImpl().visitExpr(e);
3229  }
3230  llvm_unreachable("bad ObjC ownership qualifier");
3231 }
3232 
3233 /// The default rule for __unsafe_unretained emits the RHS recursively,
3234 /// stores into the unsafe variable, and propagates the result outward.
3235 template <typename Impl, typename Result>
3236 Result ARCExprEmitter<Impl,Result>::
3237  visitBinAssignUnsafeUnretained(const BinaryOperator *e) {
3238  // Recursively emit the RHS.
3239  // For __block safety, do this before emitting the LHS.
3240  Result result = asImpl().visit(e->getRHS());
3241 
3242  // Perform the store.
3243  LValue lvalue =
3244  CGF.EmitCheckedLValue(e->getLHS(), CodeGenFunction::TCK_Store);
3245  CGF.EmitStoreThroughLValue(RValue::get(asImpl().getValueOfResult(result)),
3246  lvalue);
3247 
3248  return result;
3249 }
3250 
3251 template <typename Impl, typename Result>
3252 Result
3253 ARCExprEmitter<Impl,Result>::visitBinAssignAutoreleasing(const BinaryOperator *e) {
3254  return asImpl().visitExpr(e);
3255 }
3256 
3257 template <typename Impl, typename Result>
3258 Result
3259 ARCExprEmitter<Impl,Result>::visitBinAssignWeak(const BinaryOperator *e) {
3260  return asImpl().visitExpr(e);
3261 }
3262 
3263 template <typename Impl, typename Result>
3264 Result
3265 ARCExprEmitter<Impl,Result>::visitBinAssignStrong(const BinaryOperator *e) {
3266  return asImpl().visitExpr(e);
3267 }
3268 
3269 /// The general expression-emission logic.
3270 template <typename Impl, typename Result>
3271 Result ARCExprEmitter<Impl,Result>::visit(const Expr *e) {
3272  // We should *never* see a nested full-expression here, because if
3273  // we fail to emit at +1, our caller must not retain after we close
3274  // out the full-expression. This isn't as important in the unsafe
3275  // emitter.
3276  assert(!isa<ExprWithCleanups>(e));
3277 
3278  // Look through parens, __extension__, generic selection, etc.
3279  e = e->IgnoreParens();
3280 
3281  // Handle certain kinds of casts.
3282  if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
3283  return asImpl().visitCastExpr(ce);
3284 
3285  // Handle the comma operator.
3286  } else if (auto op = dyn_cast<BinaryOperator>(e)) {
3287  return asImpl().visitBinaryOperator(op);
3288 
3289  // TODO: handle conditional operators here
3290 
3291  // For calls and message sends, use the retained-call logic.
3292  // Delegate inits are a special case in that they're the only
3293  // returns-retained expression that *isn't* surrounded by
3294  // a consume.
3295  } else if (isa<CallExpr>(e) ||
3296  (isa<ObjCMessageExpr>(e) &&
3297  !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
3298  return asImpl().visitCall(e);
3299 
3300  // Look through pseudo-object expressions.
3301  } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
3302  return asImpl().visitPseudoObjectExpr(pseudo);
3303  } else if (auto *be = dyn_cast<BlockExpr>(e))
3304  return asImpl().visitBlockExpr(be);
3305 
3306  return asImpl().visitExpr(e);
3307 }
3308 
3309 namespace {
3310 
3311 /// An emitter for +1 results.
3312 struct ARCRetainExprEmitter :
3313  public ARCExprEmitter<ARCRetainExprEmitter, TryEmitResult> {
3314 
3315  ARCRetainExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
3316 
3317  llvm::Value *getValueOfResult(TryEmitResult result) {
3318  return result.getPointer();
3319  }
3320 
3321  TryEmitResult emitBitCast(TryEmitResult result, llvm::Type *resultType) {
3322  llvm::Value *value = result.getPointer();
3323  value = CGF.Builder.CreateBitCast(value, resultType);
3324  result.setPointer(value);
3325  return result;
3326  }
3327 
3328  TryEmitResult visitLValueToRValue(const Expr *e) {
3329  return tryEmitARCRetainLoadOfScalar(CGF, e);
3330  }
3331 
3332  /// For consumptions, just emit the subexpression and thus elide
3333  /// the retain/release pair.
3334  TryEmitResult visitConsumeObject(const Expr *e) {
3335  llvm::Value *result = CGF.EmitScalarExpr(e);
3336  return TryEmitResult(result, true);
3337  }
3338 
3339  TryEmitResult visitBlockExpr(const BlockExpr *e) {
3340  TryEmitResult result = visitExpr(e);
3341  // Avoid the block-retain if this is a block literal that doesn't need to be
3342  // copied to the heap.
3343  if (CGF.CGM.getCodeGenOpts().ObjCAvoidHeapifyLocalBlocks &&
3345  result.setInt(true);
3346  return result;
3347  }
3348 
3349  /// Block extends are net +0. Naively, we could just recurse on
3350  /// the subexpression, but actually we need to ensure that the
3351  /// value is copied as a block, so there's a little filter here.
3352  TryEmitResult visitExtendBlockObject(const Expr *e) {
3353  llvm::Value *result; // will be a +0 value
3354 
3355  // If we can't safely assume the sub-expression will produce a
3356  // block-copied value, emit the sub-expression at +0.
3358  result = CGF.EmitScalarExpr(e);
3359 
3360  // Otherwise, try to emit the sub-expression at +1 recursively.
3361  } else {
3362  TryEmitResult subresult = asImpl().visit(e);
3363 
3364  // If that produced a retained value, just use that.
3365  if (subresult.getInt()) {
3366  return subresult;
3367  }
3368 
3369  // Otherwise it's +0.
3370  result = subresult.getPointer();
3371  }
3372 
3373  // Retain the object as a block.
3374  result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
3375  return TryEmitResult(result, true);
3376  }
3377 
3378  /// For reclaims, emit the subexpression as a retained call and
3379  /// skip the consumption.
3380  TryEmitResult visitReclaimReturnedObject(const Expr *e) {
3381  llvm::Value *result = emitARCRetainCallResult(CGF, e);
3382  return TryEmitResult(result, true);
3383  }
3384 
3385  /// When we have an undecorated call, retroactively do a claim.
3386  TryEmitResult visitCall(const Expr *e) {
3387  llvm::Value *result = emitARCRetainCallResult(CGF, e);
3388  return TryEmitResult(result, true);
3389  }
3390 
3391  // TODO: maybe special-case visitBinAssignWeak?
3392 
3393  TryEmitResult visitExpr(const Expr *e) {
3394  // We didn't find an obvious production, so emit what we've got and
3395  // tell the caller that we didn't manage to retain.
3396  llvm::Value *result = CGF.EmitScalarExpr(e);
3397  return TryEmitResult(result, false);
3398  }
3399 };
3400 }
3401 
3402 static TryEmitResult
3404  return ARCRetainExprEmitter(CGF).visit(e);
3405 }
3406 
3408  LValue lvalue,
3409  QualType type) {
3410  TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
3411  llvm::Value *value = result.getPointer();
3412  if (!result.getInt())
3413  value = CGF.EmitARCRetain(type, value);
3414  return value;
3415 }
3416 
3417 /// EmitARCRetainScalarExpr - Semantically equivalent to
3418 /// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
3419 /// best-effort attempt to peephole expressions that naturally produce
3420 /// retained objects.
3422  // The retain needs to happen within the full-expression.
3423  if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3424  RunCleanupsScope scope(*this);
3425  return EmitARCRetainScalarExpr(cleanups->getSubExpr());
3426  }
3427 
3428  TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
3429  llvm::Value *value = result.getPointer();
3430  if (!result.getInt())
3431  value = EmitARCRetain(e->getType(), value);
3432  return value;
3433 }
3434 
3435 llvm::Value *
3437  // The retain needs to happen within the full-expression.
3438  if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3439  RunCleanupsScope scope(*this);
3440  return EmitARCRetainAutoreleaseScalarExpr(cleanups->getSubExpr());
3441  }
3442 
3443  TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
3444  llvm::Value *value = result.getPointer();
3445  if (result.getInt())
3446  value = EmitARCAutorelease(value);
3447  else
3448  value = EmitARCRetainAutorelease(e->getType(), value);
3449  return value;
3450 }
3451 
3453  llvm::Value *result;
3454  bool doRetain;
3455 
3457  result = EmitScalarExpr(e);
3458  doRetain = true;
3459  } else {
3460  TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
3461  result = subresult.getPointer();
3462  doRetain = !subresult.getInt();
3463  }
3464 
3465  if (doRetain)
3466  result = EmitARCRetainBlock(result, /*mandatory*/ true);
3467  return EmitObjCConsumeObject(e->getType(), result);
3468 }
3469 
3471  // In ARC, retain and autorelease the expression.
3472  if (getLangOpts().ObjCAutoRefCount) {
3473  // Do so before running any cleanups for the full-expression.
3474  // EmitARCRetainAutoreleaseScalarExpr does this for us.
3476  }
3477 
3478  // Otherwise, use the normal scalar-expression emission. The
3479  // exception machinery doesn't do anything special with the
3480  // exception like retaining it, so there's no safety associated with
3481  // only running cleanups after the throw has started, and when it
3482  // matters it tends to be substantially inferior code.
3483  return EmitScalarExpr(expr);
3484 }
3485 
3486 namespace {
3487 
3488 /// An emitter for assigning into an __unsafe_unretained context.
3489 struct ARCUnsafeUnretainedExprEmitter :
3490  public ARCExprEmitter<ARCUnsafeUnretainedExprEmitter, llvm::Value*> {
3491 
3492  ARCUnsafeUnretainedExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
3493 
3494  llvm::Value *getValueOfResult(llvm::Value *value) {
3495  return value;
3496  }
3497 
3498  llvm::Value *emitBitCast(llvm::Value *value, llvm::Type *resultType) {
3499  return CGF.Builder.CreateBitCast(value, resultType);
3500  }
3501 
3502  llvm::Value *visitLValueToRValue(const Expr *e) {
3503  return CGF.EmitScalarExpr(e);
3504  }
3505 
3506  /// For consumptions, just emit the subexpression and perform the
3507  /// consumption like normal.
3508  llvm::Value *visitConsumeObject(const Expr *e) {
3509  llvm::Value *value = CGF.EmitScalarExpr(e);
3510  return CGF.EmitObjCConsumeObject(e->getType(), value);
3511  }
3512 
3513  /// No special logic for block extensions. (This probably can't
3514  /// actually happen in this emitter, though.)
3515  llvm::Value *visitExtendBlockObject(const Expr *e) {
3516  return CGF.EmitARCExtendBlockObject(e);
3517  }
3518 
3519  /// For reclaims, perform an unsafeClaim if that's enabled.
3520  llvm::Value *visitReclaimReturnedObject(const Expr *e) {
3521  return CGF.EmitARCReclaimReturnedObject(e, /*unsafe*/ true);
3522  }
3523 
3524  /// When we have an undecorated call, just emit it without adding
3525  /// the unsafeClaim.
3526  llvm::Value *visitCall(const Expr *e) {
3527  return CGF.EmitScalarExpr(e);
3528  }
3529 
3530  /// Just do normal scalar emission in the default case.
3531  llvm::Value *visitExpr(const Expr *e) {
3532  return CGF.EmitScalarExpr(e);
3533  }
3534 };
3535 }
3536 
3538  const Expr *e) {
3539  return ARCUnsafeUnretainedExprEmitter(CGF).visit(e);
3540 }
3541 
3542 /// EmitARCUnsafeUnretainedScalarExpr - Semantically equivalent to
3543 /// immediately releasing the resut of EmitARCRetainScalarExpr, but
3544 /// avoiding any spurious retains, including by performing reclaims
3545 /// with objc_unsafeClaimAutoreleasedReturnValue.
3547  // Look through full-expressions.
3548  if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3549  RunCleanupsScope scope(*this);
3550  return emitARCUnsafeUnretainedScalarExpr(*this, cleanups->getSubExpr());
3551  }
3552 
3553  return emitARCUnsafeUnretainedScalarExpr(*this, e);
3554 }
3555 
3556 std::pair<LValue,llvm::Value*>
3558  bool ignored) {
3559  // Evaluate the RHS first. If we're ignoring the result, assume
3560  // that we can emit at an unsafe +0.
3561  llvm::Value *value;
3562  if (ignored) {
3564  } else {
3565  value = EmitScalarExpr(e->getRHS());
3566  }
3567 
3568  // Emit the LHS and perform the store.
3569  LValue lvalue = EmitLValue(e->getLHS());
3570  EmitStoreOfScalar(value, lvalue);
3571 
3572  return std::pair<LValue,llvm::Value*>(std::move(lvalue), value);
3573 }
3574 
3575 std::pair<LValue,llvm::Value*>
3577  bool ignored) {
3578  // Evaluate the RHS first.
3579  TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
3580  llvm::Value *value = result.getPointer();
3581 
3582  bool hasImmediateRetain = result.getInt();
3583 
3584  // If we didn't emit a retained object, and the l-value is of block
3585  // type, then we need to emit the block-retain immediately in case
3586  // it invalidates the l-value.
3587  if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
3588  value = EmitARCRetainBlock(value, /*mandatory*/ false);
3589  hasImmediateRetain = true;
3590  }
3591 
3592  LValue lvalue = EmitLValue(e->getLHS());
3593 
3594  // If the RHS was emitted retained, expand this.
3595  if (hasImmediateRetain) {
3596  llvm::Value *oldValue = EmitLoadOfScalar(lvalue, SourceLocation());
3597  EmitStoreOfScalar(value, lvalue);
3598  EmitARCRelease(oldValue, lvalue.isARCPreciseLifetime());
3599  } else {
3600  value = EmitARCStoreStrong(lvalue, value, ignored);
3601  }
3602 
3603  return std::pair<LValue,llvm::Value*>(lvalue, value);
3604 }
3605 
3606 std::pair<LValue,llvm::Value*>
3608  llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
3609  LValue lvalue = EmitLValue(e->getLHS());
3610 
3611  EmitStoreOfScalar(value, lvalue);
3612 
3613  return std::pair<LValue,llvm::Value*>(lvalue, value);
3614 }
3615 
3617  const ObjCAutoreleasePoolStmt &ARPS) {
3618  const Stmt *subStmt = ARPS.getSubStmt();
3619  const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
3620 
3621  CGDebugInfo *DI = getDebugInfo();
3622  if (DI)
3623  DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
3624 
3625  // Keep track of the current cleanup stack depth.
3626  RunCleanupsScope Scope(*this);
3628  llvm::Value *token = EmitObjCAutoreleasePoolPush();
3629  EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
3630  } else {
3631  llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
3632  EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
3633  }
3634 
3635  for (const auto *I : S.body())
3636  EmitStmt(I);
3637 
3638  if (DI)
3639  DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
3640 }
3641 
3642 /// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
3643 /// make sure it survives garbage collection until this point.
3644 void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
3645  // We just use an inline assembly.
3646  llvm::FunctionType *extenderType
3647  = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
3648  llvm::InlineAsm *extender = llvm::InlineAsm::get(extenderType,
3649  /* assembly */ "",
3650  /* constraints */ "r",
3651  /* side effects */ true);
3652 
3653  object = Builder.CreateBitCast(object, VoidPtrTy);
3654  EmitNounwindRuntimeCall(extender, object);
3655 }
3656 
3657 /// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
3658 /// non-trivial copy assignment function, produce following helper function.
3659 /// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
3660 ///
3661 llvm::Constant *
3663  const ObjCPropertyImplDecl *PID) {
3664  if (!getLangOpts().CPlusPlus ||
3666  return nullptr;
3667  QualType Ty = PID->getPropertyIvarDecl()->getType();
3668  if (!Ty->isRecordType())
3669  return nullptr;
3670  const ObjCPropertyDecl *PD = PID->getPropertyDecl();
3672  return nullptr;
3673  llvm::Constant *HelperFn = nullptr;
3674  if (hasTrivialSetExpr(PID))
3675  return nullptr;
3676  assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
3677  if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
3678  return HelperFn;
3679 
3680  ASTContext &C = getContext();
3681  IdentifierInfo *II
3682  = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
3683 
3684  QualType ReturnTy = C.VoidTy;
3685  QualType DestTy = C.getPointerType(Ty);
3686  QualType SrcTy = Ty;
3687  SrcTy.addConst();
3688  SrcTy = C.getPointerType(SrcTy);
3689 
3690  SmallVector<QualType, 2> ArgTys;
3691  ArgTys.push_back(DestTy);
3692  ArgTys.push_back(SrcTy);
3693  QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
3694 
3696  C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
3697  FunctionTy, nullptr, SC_Static, false, false, false);
3698 
3699  FunctionArgList args;
3700  ParmVarDecl *Params[2];
3701  ParmVarDecl *DstDecl = ParmVarDecl::Create(
3702  C, FD, SourceLocation(), SourceLocation(), nullptr, DestTy,
3703  C.getTrivialTypeSourceInfo(DestTy, SourceLocation()), SC_None,
3704  /*DefArg=*/nullptr);
3705  args.push_back(Params[0] = DstDecl);
3706  ParmVarDecl *SrcDecl = ParmVarDecl::Create(
3707  C, FD, SourceLocation(), SourceLocation(), nullptr, SrcTy,
3708  C.getTrivialTypeSourceInfo(SrcTy, SourceLocation()), SC_None,
3709  /*DefArg=*/nullptr);
3710  args.push_back(Params[1] = SrcDecl);
3711  FD->setParams(Params);
3712 
3713  const CGFunctionInfo &FI =
3715 
3716  llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
3717 
3718  llvm::Function *Fn =
3719  llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
3720  "__assign_helper_atomic_property_",
3721  &CGM.getModule());
3722 
3724 
3725  StartFunction(FD, ReturnTy, Fn, FI, args);
3726 
3727  DeclRefExpr DstExpr(C, DstDecl, false, DestTy, VK_PRValue, SourceLocation());
3729  C, &DstExpr, UO_Deref, DestTy->getPointeeType(), VK_LValue, OK_Ordinary,
3730  SourceLocation(), false, FPOptionsOverride());
3731 
3732  DeclRefExpr SrcExpr(C, SrcDecl, false, SrcTy, VK_PRValue, SourceLocation());
3734  C, &SrcExpr, UO_Deref, SrcTy->getPointeeType(), VK_LValue, OK_Ordinary,
3735  SourceLocation(), false, FPOptionsOverride());
3736 
3737  Expr *Args[2] = {DST, SRC};
3738  CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
3740  C, OO_Equal, CalleeExp->getCallee(), Args, DestTy->getPointeeType(),
3742 
3743  EmitStmt(TheCall);
3744 
3745  FinishFunction();
3746  HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
3747  CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
3748  return HelperFn;
3749 }
3750 
3751 llvm::Constant *
3753  const ObjCPropertyImplDecl *PID) {
3754  if (!getLangOpts().CPlusPlus ||
3756  return nullptr;
3757  const ObjCPropertyDecl *PD = PID->getPropertyDecl();
3758  QualType Ty = PD->getType();
3759  if (!Ty->isRecordType())
3760  return nullptr;
3762  return nullptr;
3763  llvm::Constant *HelperFn = nullptr;
3764  if (hasTrivialGetExpr(PID))
3765  return nullptr;
3766  assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
3767  if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
3768  return HelperFn;
3769 
3770  ASTContext &C = getContext();
3771  IdentifierInfo *II =
3772  &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
3773 
3774  QualType ReturnTy = C.VoidTy;
3775  QualType DestTy = C.getPointerType(Ty);
3776  QualType SrcTy = Ty;
3777  SrcTy.addConst();
3778  SrcTy = C.getPointerType(SrcTy);
3779 
3780  SmallVector<QualType, 2> ArgTys;
3781  ArgTys.push_back(DestTy);
3782  ArgTys.push_back(SrcTy);
3783  QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
3784 
3786  C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
3787  FunctionTy, nullptr, SC_Static, false, false, false);
3788 
3789  FunctionArgList args;
3790  ParmVarDecl *Params[2];
3791  ParmVarDecl *DstDecl = ParmVarDecl::Create(
3792  C, FD, SourceLocation(), SourceLocation(), nullptr, DestTy,
3793  C.getTrivialTypeSourceInfo(DestTy, SourceLocation()), SC_None,
3794  /*DefArg=*/nullptr);
3795  args.push_back(Params[0] = DstDecl);
3796  ParmVarDecl *SrcDecl = ParmVarDecl::Create(
3797  C, FD, SourceLocation(), SourceLocation(), nullptr, SrcTy,
3798  C.getTrivialTypeSourceInfo(SrcTy, SourceLocation()), SC_None,
3799  /*DefArg=*/nullptr);
3800  args.push_back(Params[1] = SrcDecl);
3801  FD->setParams(Params);
3802 
3803  const CGFunctionInfo &FI =
3805 
3806  llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
3807 
3808  llvm::Function *Fn = llvm::Function::Create(
3809  LTy, llvm::GlobalValue::InternalLinkage, "__copy_helper_atomic_property_",
3810  &CGM.getModule());
3811 
3813 
3814  StartFunction(FD, ReturnTy, Fn, FI, args);
3815 
3816  DeclRefExpr SrcExpr(getContext(), SrcDecl, false, SrcTy, VK_PRValue,
3817  SourceLocation());
3818 
3820  C, &SrcExpr, UO_Deref, SrcTy->getPointeeType(), VK_LValue, OK_Ordinary,
3821  SourceLocation(), false, FPOptionsOverride());
3822 
3823  CXXConstructExpr *CXXConstExpr =
3824  cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
3825 
3826  SmallVector<Expr*, 4> ConstructorArgs;
3827  ConstructorArgs.push_back(SRC);
3828  ConstructorArgs.append(std::next(CXXConstExpr->arg_begin()),
3829  CXXConstExpr->arg_end());
3830 
3831  CXXConstructExpr *TheCXXConstructExpr =
3833  CXXConstExpr->getConstructor(),
3834  CXXConstExpr->isElidable(),
3835  ConstructorArgs,
3836  CXXConstExpr->hadMultipleCandidates(),
3837  CXXConstExpr->isListInitialization(),
3838  CXXConstExpr->isStdInitListInitialization(),
3839  CXXConstExpr->requiresZeroInitialization(),
3840  CXXConstExpr->getConstructionKind(),
3841  SourceRange());
3842 
3843  DeclRefExpr DstExpr(getContext(), DstDecl, false, DestTy, VK_PRValue,
3844  SourceLocation());
3845 
3846  RValue DV = EmitAnyExpr(&DstExpr);
3847  CharUnits Alignment =
3848  getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
3849  EmitAggExpr(TheCXXConstructExpr,
3851  Address(DV.getScalarVal(), ConvertTypeForMem(Ty), Alignment),
3855 
3856  FinishFunction();
3857  HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
3858  CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
3859  return HelperFn;
3860 }
3861 
3862 llvm::Value *
3864  // Get selectors for retain/autorelease.
3865  IdentifierInfo *CopyID = &getContext().Idents.get("copy");
3866  Selector CopySelector =
3868  IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
3869  Selector AutoreleaseSelector =
3870  getContext().Selectors.getNullarySelector(AutoreleaseID);
3871 
3872  // Emit calls to retain/autorelease.
3873  CGObjCRuntime &Runtime = CGM.getObjCRuntime();
3874  llvm::Value *Val = Block;
3875  RValue Result;
3876  Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3877  Ty, CopySelector,
3878  Val, CallArgList(), nullptr, nullptr);
3879  Val = Result.getScalarVal();
3880  Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3881  Ty, AutoreleaseSelector,
3882  Val, CallArgList(), nullptr, nullptr);
3883  Val = Result.getScalarVal();
3884  return Val;
3885 }
3886 
3887 static unsigned getBaseMachOPlatformID(const llvm::Triple &TT) {
3888  switch (TT.getOS()) {
3889  case llvm::Triple::Darwin:
3890  case llvm::Triple::MacOSX:
3891  return llvm::MachO::PLATFORM_MACOS;
3892  case llvm::Triple::IOS:
3893  return llvm::MachO::PLATFORM_IOS;
3894  case llvm::Triple::TvOS:
3895  return llvm::MachO::PLATFORM_TVOS;
3896  case llvm::Triple::WatchOS:
3897  return llvm::MachO::PLATFORM_WATCHOS;
3898  case llvm::Triple::DriverKit:
3899  return llvm::MachO::PLATFORM_DRIVERKIT;
3900  default:
3901  return /*Unknown platform*/ 0;
3902  }
3903 }
3904 
3906  const VersionTuple &Version) {
3907  CodeGenModule &CGM = CGF.CGM;
3908  // Note: we intend to support multi-platform version checks, so reserve
3909  // the room for a dual platform checking invocation that will be
3910  // implemented in the future.
3912 
3913  auto EmitArgs = [&](const VersionTuple &Version, const llvm::Triple &TT) {
3914  Optional<unsigned> Min = Version.getMinor(), SMin = Version.getSubminor();
3915  Args.push_back(
3916  llvm::ConstantInt::get(CGM.Int32Ty, getBaseMachOPlatformID(TT)));
3917  Args.push_back(llvm::ConstantInt::get(CGM.Int32Ty, Version.getMajor()));
3918  Args.push_back(llvm::ConstantInt::get(CGM.Int32Ty, Min.getValueOr(0)));
3919  Args.push_back(llvm::ConstantInt::get(CGM.Int32Ty, SMin.getValueOr(0)));
3920  };
3921 
3922  assert(!Version.empty() && "unexpected empty version");
3923  EmitArgs(Version, CGM.getTarget().getTriple());
3924 
3925  if (!CGM.IsPlatformVersionAtLeastFn) {
3926  llvm::FunctionType *FTy = llvm::FunctionType::get(
3927  CGM.Int32Ty, {CGM.Int32Ty, CGM.Int32Ty, CGM.Int32Ty, CGM.Int32Ty},
3928  false);
3930  CGM.CreateRuntimeFunction(FTy, "__isPlatformVersionAtLeast");
3931  }
3932 
3933  llvm::Value *Check =
3935  return CGF.Builder.CreateICmpNE(Check,
3936  llvm::Constant::getNullValue(CGM.Int32Ty));
3937 }
3938 
3939 llvm::Value *
3940 CodeGenFunction::EmitBuiltinAvailable(const VersionTuple &Version) {
3941  // Darwin uses the new __isPlatformVersionAtLeast family of routines.
3942  if (CGM.getTarget().getTriple().isOSDarwin())
3943  return emitIsPlatformVersionAtLeast(*this, Version);
3944 
3945  if (!CGM.IsOSVersionAtLeastFn) {
3946  llvm::FunctionType *FTy =
3947  llvm::FunctionType::get(Int32Ty, {Int32Ty, Int32Ty, Int32Ty}, false);
3949  CGM.CreateRuntimeFunction(FTy, "__isOSVersionAtLeast");
3950  }
3951 
3952  Optional<unsigned> Min = Version.getMinor(), SMin = Version.getSubminor();
3953  llvm::Value *Args[] = {
3954  llvm::ConstantInt::get(CGM.Int32Ty, Version.getMajor()),
3955  llvm::ConstantInt::get(CGM.Int32Ty, Min.getValueOr(0)),
3956  llvm::ConstantInt::get(CGM.Int32Ty, SMin.getValueOr(0))
3957  };
3958 
3959  llvm::Value *CallRes =
3961 
3962  return Builder.CreateICmpNE(CallRes, llvm::Constant::getNullValue(Int32Ty));
3963 }
3964 
3966  const llvm::Triple &TT, const VersionTuple &TargetVersion) {
3967  VersionTuple FoundationDroppedInVersion;
3968  switch (TT.getOS()) {
3969  case llvm::Triple::IOS:
3970  case llvm::Triple::TvOS:
3971  FoundationDroppedInVersion = VersionTuple(/*Major=*/13);
3972  break;
3973  case llvm::Triple::WatchOS:
3974  FoundationDroppedInVersion = VersionTuple(/*Major=*/6);
3975  break;
3976  case llvm::Triple::Darwin:
3977  case llvm::Triple::MacOSX:
3978  FoundationDroppedInVersion = VersionTuple(/*Major=*/10, /*Minor=*/15);
3979  break;
3980  case llvm::Triple::DriverKit:
3981  // DriverKit doesn't need Foundation.
3982  return false;
3983  default:
3984  llvm_unreachable("Unexpected OS");
3985  }
3986  return TargetVersion < FoundationDroppedInVersion;
3987 }
3988 
3989 void CodeGenModule::emitAtAvailableLinkGuard() {
3991  return;
3992  // @available requires CoreFoundation only on Darwin.
3993  if (!Target.getTriple().isOSDarwin())
3994  return;
3995  // @available doesn't need Foundation on macOS 10.15+, iOS/tvOS 13+, or
3996  // watchOS 6+.
3998  Target.getTriple(), Target.getPlatformMinVersion()))
3999  return;
4000  // Add -framework CoreFoundation to the linker commands. We still want to
4001  // emit the core foundation reference down below because otherwise if
4002  // CoreFoundation is not used in the code, the linker won't link the
4003  // framework.
4004  auto &Context = getLLVMContext();
4005  llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"),
4006  llvm::MDString::get(Context, "CoreFoundation")};
4007  LinkerOptionsMetadata.push_back(llvm::MDNode::get(Context, Args));
4008  // Emit a reference to a symbol from CoreFoundation to ensure that
4009  // CoreFoundation is linked into the final binary.
4010  llvm::FunctionType *FTy =
4011  llvm::FunctionType::get(Int32Ty, {VoidPtrTy}, false);
4012  llvm::FunctionCallee CFFunc =
4013  CreateRuntimeFunction(FTy, "CFBundleGetVersionNumber");
4014 
4015  llvm::FunctionType *CheckFTy = llvm::FunctionType::get(VoidTy, {}, false);
4016  llvm::FunctionCallee CFLinkCheckFuncRef = CreateRuntimeFunction(
4017  CheckFTy, "__clang_at_available_requires_core_foundation_framework",
4018  llvm::AttributeList(), /*Local=*/true);
4019  llvm::Function *CFLinkCheckFunc =
4020  cast<llvm::Function>(CFLinkCheckFuncRef.getCallee()->stripPointerCasts());
4021  if (CFLinkCheckFunc->empty()) {
4022  CFLinkCheckFunc->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
4023  CFLinkCheckFunc->setVisibility(llvm::GlobalValue::HiddenVisibility);
4024  CodeGenFunction CGF(*this);
4025  CGF.Builder.SetInsertPoint(CGF.createBasicBlock("", CFLinkCheckFunc));
4026  CGF.EmitNounwindRuntimeCall(CFFunc,
4027  llvm::Constant::getNullValue(VoidPtrTy));
4028  CGF.Builder.CreateUnreachable();
4029  addCompilerUsedGlobal(CFLinkCheckFunc);
4030  }
4031 }
4032 
clang::InternalLinkage
@ InternalLinkage
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition: Linkage.h:31
clang::CodeGen::ObjCEntrypoints::objc_autoreleasePoolPop
llvm::FunctionCallee objc_autoreleasePoolPop
void objc_autoreleasePoolPop(void*);
Definition: CodeGenModule.h:126
clang::ObjCMessageExpr::SuperInstance
@ SuperInstance
The receiver is the instance of the superclass object.
Definition: ExprObjC.h:1097
clang::CodeGen::CodeGenFunction::EmitBuiltinAvailable
llvm::Value * EmitBuiltinAvailable(const VersionTuple &Version)
Definition: CGObjC.cpp:3940
clang::CodeGen::CodeGenFunction::SanitizerScope
RAII object to set/unset CodeGenFunction::IsSanitizerScope.
Definition: CodeGenFunction.h:524
clang::ObjCInterfaceDecl
Represents an ObjC class declaration.
Definition: DeclObjC.h:1150
clang::CodeGen::CodeGenFunction::ConvertTypeForMem
llvm::Type * ConvertTypeForMem(QualType T)
Definition: CodeGenFunction.cpp:208
clang::CodeGen::CodeGenFunction::EmitObjCAutoreleasePoolStmt
void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S)
Definition: CGObjC.cpp:3616
clang::ASTContext::getTypeSizeInChars
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
Definition: ASTContext.cpp:2462
clang::CodeGen::CGObjCRuntime::GetClass
virtual llvm::Value * GetClass(CodeGenFunction &CGF, const ObjCInterfaceDecl *OID)=0
GetClass - Return a reference to the class for the given interface decl.
clang::CodeGen::CodeGenFunction::EmitARCRetainNonBlock
llvm::Value * EmitARCRetainNonBlock(llvm::Value *value)
Retain the given object, with normal retain semantics.
Definition: CGObjC.cpp:2263
emitStructGetterCall
static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar, bool isAtomic, bool hasStrong)
emitStructGetterCall - Call the runtime function to load a property into the return value slot.
Definition: CGObjC.cpp:816
clang::CodeGen::CGDebugInfo::EmitLexicalBlockStart
void EmitLexicalBlockStart(CGBuilderTy &Builder, SourceLocation Loc)
Emit metadata to indicate the beginning of a new lexical block and push the block onto the stack.
Definition: CGDebugInfo.cpp:4294
emitARCStoreOperation
static llvm::Value * emitARCStoreOperation(CodeGenFunction &CGF, Address addr, llvm::Value *value, llvm::Function *&fn, llvm::Intrinsic::ID IntID, bool ignored)
Perform an operation having the following signature: i8* (i8**, i8*)
Definition: CGObjC.cpp:2172
clang::ObjCPropertyImplDecl::getPropertyIvarDecl
ObjCIvarDecl * getPropertyIvarDecl() const
Definition: DeclObjC.h:2826
clang::Type::isRecordType
bool isRecordType() const
Definition: Type.h:6838
clang::CodeGen::CodeGenFunction::EmitObjCAutoreleasePoolCleanup
void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr)
Definition: CGObjC.cpp:2844
clang::CodeGen::ObjCEntrypoints::objc_allocWithZone
llvm::FunctionCallee objc_allocWithZone
void objc_allocWithZone(id);
Definition: CodeGenModule.h:120
clang::QualType::getObjCLifetime
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1128
clang::CodeGen::CodeGenFunction::getProfileCount
uint64_t getProfileCount(const Stmt *S)
Get the profiler's count for the given statement.
Definition: CodeGenFunction.h:1531
hasTrivialSetExpr
static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID)
Definition: CGObjC.cpp:1370
clang::HiddenVisibility
@ HiddenVisibility
Objects with "hidden" visibility are not seen by the dynamic linker.
Definition: Visibility.h:36
findWeakLValue
static const Expr * findWeakLValue(const Expr *E)
Given an expression of ObjC pointer type, check whether it was immediately loaded from an ARC __weak ...
Definition: CGObjC.cpp:347
clang::CodeGen::CodeGenFunction::RunCleanupsScope::requiresCleanups
bool requiresCleanups() const
Determine whether this scope requires any cleanups.
Definition: CodeGenFunction.h:907
getNullForVariable
static llvm::Constant * getNullForVariable(Address addr)
Given the address of a variable of pointer type, find the correct null to store into it.
Definition: CGObjC.cpp:42
clang::CodeGen::CodeGenTypeCache::Int8PtrTy
llvm::PointerType * Int8PtrTy
Definition: CodeGenTypeCache.h:57
clang::CodeGen::CodeGenFunction::EmitNullInitialization
void EmitNullInitialization(Address DestPtr, QualType Ty)
EmitNullInitialization - Generate code to set a value of the given type to null, If the type contains...
Definition: CodeGenFunction.cpp:1956
clang::ObjCProtocolExpr::getProtocol
ObjCProtocolDecl * getProtocol() const
Definition: ExprObjC.h:521
clang::ObjCBoxedExpr
ObjCBoxedExpr - used for generalized expression boxing.
Definition: ExprObjC.h:128
clang::CodeGen::CodeGenFunction::EmitObjCCollectionLiteral
llvm::Value * EmitObjCCollectionLiteral(const Expr *E, const ObjCMethodDecl *MethodWithObjects)
Definition: CGObjC.cpp:121
clang::OMF_autorelease
@ OMF_autorelease
Definition: IdentifierTable.h:706
clang::ObjCProtocolDecl::protocols
protocol_range protocols() const
Definition: DeclObjC.h:2117
clang::Type::isBlockPointerType
bool isBlockPointerType() const
Definition: Type.h:6756
clang::CodeGen::ObjCEntrypoints::objc_retainAutoreleasedReturnValue
llvm::Function * objc_retainAutoreleasedReturnValue
id objc_retainAutoreleasedReturnValue(id);
Definition: CodeGenModule.h:177
clang::interp::APInt
llvm::APInt APInt
Definition: Integral.h:27
emitARCUnsafeClaimCallResult
static llvm::Value * emitARCUnsafeClaimCallResult(CodeGenFunction &CGF, const Expr *e)
Given that the given expression is some sort of call (which does not return retained),...
Definition: CGObjC.cpp:3005
clang::ObjCObjectPointerType::getInterfaceType
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition: Type.cpp:1676
clang::CodeGen::CodeGenFunction::EmitBlockCopyAndAutorelease
llvm::Value * EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty)
Definition: CGObjC.cpp:3863
clang::CodeGen::CodeGenFunction::emitARCCopyAssignWeak
void emitARCCopyAssignWeak(QualType Ty, Address DstAddr, Address SrcAddr)
Definition: CGObjC.cpp:2635
clang::OK_Ordinary
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:136
clang::CodeGen::TEK_Aggregate
@ TEK_Aggregate
Definition: CodeGenFunction.h:109
clang::CodeGen::RValue
RValue - This trivial value class is used to represent the result of an expression that is evaluated.
Definition: CGValue.h:39
clang::CodeGen::CodeGenModule::CreateRuntimeFunction
llvm::FunctionCallee CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList(), bool Local=false, bool AssumeConvergent=false)
Create or return a runtime function declaration with the specified type and name.
Definition: CodeGenModule.cpp:4025
emitARCOperationAfterCall
static llvm::Value * emitARCOperationAfterCall(CodeGenFunction &CGF, llvm::Value *value, ValueTransform doAfterCall, ValueTransform doFallback)
Insert code immediately after a call.
Definition: CGObjC.cpp:2935
clang::CodeGen::CGObjCRuntime::GetPropertyGetFunction
virtual llvm::FunctionCallee GetPropertyGetFunction()=0
Return the runtime function for getting properties.
type
clang::CodeGen::CodeGenFunction::EmitObjCConsumeObject
llvm::Value * EmitObjCConsumeObject(QualType T, llvm::Value *Ptr)
Produce the code for a CK_ARCConsumeObject.
Definition: CGObjC.cpp:2065
clang::CodeGen::CodeGenFunction::EmitARCDestroyWeak
void EmitARCDestroyWeak(Address addr)
void @objc_destroyWeak(i8** addr) Essentially objc_storeWeak(addr, nil).
Definition: CGObjC.cpp:2606
clang::CodeGen::CGObjCRuntime::GenerateMessageSend
virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF, ReturnValueSlot ReturnSlot, QualType ResultType, Selector Sel, llvm::Value *Receiver, const CallArgList &CallArgs, const ObjCInterfaceDecl *Class=nullptr, const ObjCMethodDecl *Method=nullptr)=0
Generate an Objective-C message send operation.
clang::CodeGen::CodeGenFunction::EmitARCRetainAutoreleaseReturnValue
llvm::Value * EmitARCRetainAutoreleaseReturnValue(llvm::Value *value)
Do a fused retain/autorelease of the given object.
Definition: CGObjC.cpp:2524
clang::CodeGen::CodeGenFunction::EmitObjCAtTryStmt
void EmitObjCAtTryStmt(const ObjCAtTryStmt &S)
Definition: CGObjC.cpp:2038
clang::PseudoObjectExpr::semantics_begin
semantics_iterator semantics_begin()
Definition: Expr.h:6168
clang::ObjCDictionaryLiteral::getNumElements
unsigned getNumElements() const
getNumElements - Return number of elements of objective-c dictionary literal.
Definition: ExprObjC.h:360
clang::CodeGen::CodeGenFunction::EmitCheckSourceLocation
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:3144
clang::CodeGen::CodeGenFunction::AutoreleaseResult
bool AutoreleaseResult
In ARC, whether we should autorelease the return value.
Definition: CodeGenFunction.h:536
clang::Type::isObjCRetainableType
bool isObjCRetainableType() const
Definition: Type.cpp:4335
Error
llvm::Error Error
Definition: ByteCodeEmitter.cpp:20
CodeGenFunction.h
clang::SourceRange
A trivial tuple used to represent a source range.
Definition: SourceLocation.h:210
shouldRetainObjCLifetime
static bool shouldRetainObjCLifetime(Qualifiers::ObjCLifetime lifetime)
Definition: CGObjC.cpp:2851
string
string(SUBSTRING ${CMAKE_CURRENT_BINARY_DIR} 0 ${PATH_LIB_START} PATH_HEAD) string(SUBSTRING $
Definition: CMakeLists.txt:22
clang::CodeGen::CodeGenFunction::EmitCall
RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, ReturnValueSlot ReturnValue, const CallArgList &Args, llvm::CallBase **callOrInvoke, bool IsMustTail, SourceLocation Loc)
EmitCall - Generate a call of the given function, expecting the given result type,...
Definition: CGCall.cpp:4687
clang::CodeGen::CodeGenFunction::EmitObjCMRRAutoreleasePoolPush
llvm::Value * EmitObjCMRRAutoreleasePoolPush()
Produce the code to do an MRR version objc_autoreleasepool_push.
Definition: CGObjC.cpp:2692
clang::ObjCIvarDecl::getNextIvar
ObjCIvarDecl * getNextIvar()
Definition: DeclObjC.h:1959
clang::ObjCAutoreleasePoolStmt::getSubStmt
const Stmt * getSubStmt() const
Definition: StmtObjC.h:404
clang::ObjCArrayLiteral::getNumElements
unsigned getNumElements() const
getNumElements - Return number of elements of objective-c array literal.
Definition: ExprObjC.h:229
clang::Decl::hasAttr
bool hasAttr() const
Definition: DeclBase.h:542
clang::CodeGen::CodeGenFunction::EmitCompoundStmtWithoutScope
Address EmitCompoundStmtWithoutScope(const CompoundStmt &S, bool GetLast=false, AggValueSlot AVS=AggValueSlot::ignored())
Definition: CGStmt.cpp:470
clang::ObjCPropertyImplDecl::getSetterCXXAssignment
Expr * getSetterCXXAssignment() const
Definition: DeclObjC.h:2862
clang::CodeGen::CodeGenFunction::CurCodeDecl
const Decl * CurCodeDecl
CurCodeDecl - This is the inner-most code context, which includes blocks.
Definition: CodeGenFunction.h:322
clang::ObjCImplementationDecl
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2548
clang::CXXConstructExpr::arg_end
arg_iterator arg_end()
Definition: ExprCXX.h:1598
clang::CodeGen::AggValueSlot::DoesNotNeedGCBarriers
@ DoesNotNeedGCBarriers
Definition: CGValue.h:554
clang::CodeGen::CodeGenFunction::EmitNounwindRuntimeCall
llvm::CallInst * EmitNounwindRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
clang::ObjCMessageExpr::getSelector
Selector getSelector() const
Definition: ExprObjC.cpp:293
clang::CodeGen::CGObjCRuntime::GetOptimizedPropertySetFunction
virtual llvm::FunctionCallee GetOptimizedPropertySetFunction(bool atomic, bool copy)=0
Return the runtime function for optimized setting properties.
clang::CodeGen::CodeGenFunction::destroyARCStrongPrecise
static Destroyer destroyARCStrongPrecise
Definition: CodeGenFunction.h:4342
clang::CodeGen::ObjCEntrypoints::clang_arc_noop_use
llvm::Function * clang_arc_noop_use
void clang.arc.noop.use(...);
Definition: CodeGenModule.h:206
clang::CodeGen::TargetCodeGenInfo::markARCOptimizedReturnCallsAsNoTail
virtual bool markARCOptimizedReturnCallsAsNoTail() const
Determine whether a call to objc_retainAutoreleasedReturnValue or objc_unsafeClaimAutoreleasedReturnV...
Definition: TargetInfo.h:185
clang::UnaryOperator::Create
static UnaryOperator * Create(const ASTContext &C, Expr *input, Opcode opc, QualType type, ExprValueKind VK, ExprObjectKind OK, SourceLocation l, bool CanOverflow, FPOptionsOverride FPFeatures)
Definition: Expr.cpp:4595
clang::ImplicitCastExpr::OnStack
@ OnStack
Definition: Expr.h:3644
clang::Qualifiers::OCL_Weak
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:178
clang::CodeGen::ObjCEntrypoints::objc_retainAutoreleaseReturnValue
llvm::Function * objc_retainAutoreleaseReturnValue
id objc_retainAutoreleaseReturnValue(id);
Definition: CodeGenModule.h:174
clang::CodeGen::CodeGenModule::setAtomicSetterHelperFnMap
void setAtomicSetterHelperFnMap(QualType Ty, llvm::Constant *Fn)
Definition: CodeGenModule.h:669
clang::ASTContext::VoidTy
CanQualType VoidTy
Definition: ASTContext.h:1096
llvm::SmallVector
Definition: LLVM.h:38
clang::IdentifierTable::get
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
Definition: IdentifierTable.h:596
clang::SourceLocation
Encodes a location in the source.
Definition: SourceLocation.h:86
clang::CodeGen::CodeGenModule::SetInternalFunctionAttributes
void SetInternalFunctionAttributes(GlobalDecl GD, llvm::Function *F, const CGFunctionInfo &FI)
Set the attributes on the LLVM function for the given decl and function info.
Definition: CodeGenModule.cpp:2193
clang::OMF_release
@ OMF_release
Definition: IdentifierTable.h:709
clang::CodeGen::CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction
llvm::Constant * GenerateObjCAtomicSetterCopyHelperFunction(const ObjCPropertyImplDecl *PID)
GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with non-trivial copy assignment...
Definition: CGObjC.cpp:3662
clang::CodeGen::LValue::getAddress
Address getAddress(CodeGenFunction &CGF) const
Definition: CGValue.h:341
clang::CodeGen::CGObjCRuntime::GetRuntimeProtocolList
std::vector< const ObjCProtocolDecl * > GetRuntimeProtocolList(ObjCProtocolDecl::protocol_iterator begin, ObjCProtocolDecl::protocol_iterator end)
Walk the list of protocol references from a class, category or protocol to traverse the DAG formed fr...
Definition: CGObjC.cpp:465
clang::ObjCRuntime::hasNativeARC
bool hasNativeARC() const
Does this runtime natively provide the ARC entrypoints?
Definition: ObjCRuntime.h:162
clang::CodeGen::CodeGenFunction::EmitLoadOfComplex
ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc)
EmitLoadOfComplex - Load a complex number from the specified l-value.
Definition: CGExprComplex.cpp:1145
clang::QualType::getNonReferenceType
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:6696
clang::CastExpr::getSubExpr
Expr * getSubExpr()
Definition: Expr.h:3525
clang::CodeGen::CodeGenModule::getSize
llvm::ConstantInt * getSize(CharUnits numChars)
Emit the given number of characters as a value of type size_t.
Definition: CodeGenModule.cpp:1076
clang::CodeGen::CodeGenFunction::EmitAnyExpr
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:212
emitAutoreleasedReturnValueMarker
static void emitAutoreleasedReturnValueMarker(CodeGenFunction &CGF)
Definition: CGObjC.cpp:2299
clang::CodeGen::ObjCEntrypoints::objc_autoreleaseReturnValue
llvm::Function * objc_autoreleaseReturnValue
id objc_autoreleaseReturnValue(id);
Definition: CodeGenModule.h:143
clang::CXXConstructExpr::requiresZeroInitialization
bool requiresZeroInitialization() const
Whether this construction first requires zero-initialization before the initializer is called.
Definition: ExprCXX.h:1571
clang::CodeGen::CodeGenTypeCache::getPointerAlign
CharUnits getPointerAlign() const
Definition: CodeGenTypeCache.h:117
clang::QualType
A (possibly-)qualified type.
Definition: Type.h:675
Attr.h
emitCPPObjectAtomicSetterCall
static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD, ObjCIvarDecl *ivar, llvm::Constant *AtomicHelperFn)
emitCPPObjectAtomicSetterCall - Call the runtime function to store the value from the first formal pa...
Definition: CGObjC.cpp:1334
clang::Selector::isUnarySelector
bool isUnarySelector() const
Definition: IdentifierTable.h:829
clang::CodeGen::CodeGenTypeCache::PointerAlignInBytes
unsigned char PointerAlignInBytes
Definition: CodeGenTypeCache.h:96
clang::CodeGen::LValue::getQuals
const Qualifiers & getQuals() const
Definition: CGValue.h:325
clang::cast
U cast(CodeGen::Address addr)
Definition: Address.h:174
clang::CodeGen::CodeGenModule::setAtomicGetterHelperFnMap
void setAtomicGetterHelperFnMap(QualType Ty, llvm::Constant *Fn)
Definition: CodeGenModule.h:677
clang::SanitizerSet::has
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.
Definition: Sanitizers.h:155
clang::CodeGen::CodeGenModule::getContext
ASTContext & getContext() const
Definition: CodeGenModule.h:697
clang::CodeGen::RequiredArgs::All
@ All
Definition: CGFunctionInfo.h:485
clang::QualType::getCanonicalType
QualType getCanonicalType() const
Definition: Type.h:6539
clang::FieldDecl
Represents a member of a struct/union/class.
Definition: Decl.h:2855
clang::CodeGen::CodeGenFunction::EmitARCDestroyStrong
void EmitARCDestroyStrong(Address addr, ARCPreciseLifetime_t precise)
Destroy a __strong variable.
Definition: CGObjC.cpp:2434
clang::Qualifiers
The collection of all-type qualifiers we support.
Definition: Type.h:147
clang::ParmVarDecl
Represents a parameter to a function.
Definition: Decl.h:1680
clang::ObjCProtocolDecl::getCanonicalDecl
ObjCProtocolDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this Objective-C protocol.
Definition: DeclObjC.h:2246
clang::ObjCPropertyImplDecl::getGetterMethodDecl
ObjCMethodDecl * getGetterMethodDecl() const
Definition: DeclObjC.h:2848
clang::ObjCObjectPointerType::getPointeeType
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:6160
clang::ObjCMethodDecl::getClassInterface
ObjCInterfaceDecl * getClassInterface()
Definition: DeclObjC.cpp:1176
clang::ObjCMessageExpr::arguments
llvm::iterator_range< arg_iterator > arguments()
Definition: ExprObjC.h:1453
clang::CodeGen::CodeGenFunction::createBasicBlock
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
Definition: CodeGenFunction.h:2430
clang::CodeGen::CodeGenFunction::EmitARCCopyWeak
void EmitARCCopyWeak(Address dst, Address src)
void @objc_copyWeak(i8** dest, i8** src) Disregards the current value in dest.
Definition: CGObjC.cpp:2629
clang::ObjCAtTryStmt
Represents Objective-C's @try ... @catch ... @finally statement.
Definition: StmtObjC.h:165
clang::CodeGen::CGBuilderTy::CreateStore
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
Definition: CGBuilder.h:97
CGObjCRuntime.h
hasUnalignedAtomics
static bool hasUnalignedAtomics(llvm::Triple::ArchType arch)
Determine whether the given architecture supports unaligned atomic accesses.
Definition: CGObjC.cpp:849
clang::ObjCPropertyImplDecl
ObjCPropertyImplDecl - Represents implementation declaration of a property in a class or category imp...
Definition: DeclObjC.h:2753
clang::CodeGen::ARCPreciseLifetime_t
ARCPreciseLifetime_t
Does an ARC strong l-value have precise lifetime?
Definition: CGValue.h:124
TargetInfo.h
clang::ObjCMessageExpr::getInstanceReceiver
Expr * getInstanceReceiver()
Returns the object expression (receiver) for an instance message, or null for a message that is not a...
Definition: ExprObjC.h:1250
clang::Qualifiers::OCL_ExplicitNone
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:168
clang::CodeGen::CodeGenTypes::arrangeBuiltinFunctionDeclaration
const CGFunctionInfo & arrangeBuiltinFunctionDeclaration(QualType resultType, const FunctionArgList &args)
A builtin function is a freestanding function using the default C conventions.
Definition: CGCall.cpp:666
llvm::Optional
Definition: LLVM.h:40
clang::ObjCMethodDecl::param_end
param_const_iterator param_end() const
Definition: DeclObjC.h:361
clang::UnaryOperator
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2163
clang::CodeGen::CodeGenModule::SetLLVMFunctionAttributes
void SetLLVMFunctionAttributes(GlobalDecl GD, const CGFunctionInfo &Info, llvm::Function *F, bool IsThunk)
Set the LLVM function attributes (sext, zext, etc).
Definition: CodeGenModule.cpp:1644
clang::CodeGen::CodeGenModule::getLangOpts
const LangOptions & getLangOpts() const
Definition: CodeGenModule.h:698
clang::Type::isVoidType
bool isVoidType() const
Definition: Type.h:7037
clang::CodeGen::CodeGenFunction::EmitARCStoreAutoreleasing
std::pair< LValue, llvm::Value * > EmitARCStoreAutoreleasing(const BinaryOperator *e)
Definition: CGObjC.cpp:3607
clang::CodeGen::LValue::isARCPreciseLifetime
ARCPreciseLifetime_t isARCPreciseLifetime() const
Definition: CGValue.h:299
clang::CodeGen::CodeGenFunction::shouldUseFusedARCCalls
bool shouldUseFusedARCCalls()
Definition: CodeGenFunction.h:1991
emitStructSetterCall
static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD, ObjCIvarDecl *ivar)
emitStructSetterCall - Call the runtime function to store the value from the first formal parameter i...
Definition: CGObjC.cpp:1290
Expression
clang::CodeGen::CodeGenModule::getAtomicGetterHelperFnMap
llvm::Constant * getAtomicGetterHelperFnMap(QualType Ty)
Definition: CodeGenModule.h:674
clang::LangOptions::GCOnly
@ GCOnly
Definition: LangOptions.h:83
clang::CodeGen::CodeGenFunction::EmitObjCThrowOperand
llvm::Value * EmitObjCThrowOperand(const Expr *expr)
Definition: CGObjC.cpp:3470
clang::CodeGen::CodeGenFunction::getDestroyer
Destroyer * getDestroyer(QualType::DestructionKind destructionKind)
Definition: CGDecl.cpp:2091
clang::CodeGen::EHCleanup
@ EHCleanup
Denotes a cleanup that should run when a scope is exited using exceptional control flow (a throw stat...
Definition: EHScopeStack.h:80
clang::ObjCForCollectionStmt
Represents Objective-C's collection statement.
Definition: StmtObjC.h:23
clang::CodeGen::CodeGenFunction::EmitStoreOfScalar
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...
Definition: CodeGenFunction.h:3848
clang::PseudoObjectExpr::semantics_end
semantics_iterator semantics_end()
Definition: Expr.h:6174
clang::BinaryOperator::getOpcode
Opcode getOpcode() const
Definition: Expr.h:3851
clang::ObjCInterfaceType::getDecl
ObjCInterfaceDecl * getDecl() const
Get the declaration of this interface.
Definition: Type.cpp:823
clang::CodeGen::CodeGenModule::getTargetCodeGenInfo
const TargetCodeGenInfo & getTargetCodeGenInfo()
Definition: TargetInfo.cpp:11336
clang::CodeGen::CodeGenFunction::EmitARCRetainAutoreleasedReturnValue
llvm::Value * EmitARCRetainAutoreleasedReturnValue(llvm::Value *value)
Retain the given object which is the result of a function call.
Definition: CGObjC.cpp:2387
clang::CodeGen::CodeGenFunction::GenerateObjCSetter
void GenerateObjCSetter(ObjCImplementationDecl *IMP, const ObjCPropertyImplDecl *PID)
GenerateObjCSetter - Synthesize an Objective-C property setter function for the given property.
Definition: CGObjC.cpp:1582
clang::CodeGen::CodeGenFunction::TCK_Store
@ TCK_Store
Checking the destination of a store. Must be suitably sized and aligned.
Definition: CodeGenFunction.h:2957
clang::CodeGen::CodeGenFunction::EmitObjCMessageExpr
RValue EmitObjCMessageExpr(const ObjCMessageExpr *E, ReturnValueSlot Return=ReturnValueSlot())
Definition: CGObjC.cpp:572
clang::CodeGen::ObjCEntrypoints::objc_autoreleasePoolPush
llvm::Function * objc_autoreleasePoolPush
void *objc_autoreleasePoolPush(void);
Definition: CodeGenModule.h:133
clang::CodeGen::CGDebugInfo::EmitLexicalBlockEnd
void EmitLexicalBlockEnd(CGBuilderTy &Builder, SourceLocation Loc)
Emit metadata to indicate the end of a new lexical block and pop the current block.
Definition: CGDebugInfo.cpp:4311
setARCRuntimeFunctionLinkage
static void setARCRuntimeFunctionLinkage(CodeGenModule &CGM, llvm::Value *RTF)
Definition: CGObjC.cpp:2099
clang::Token
Token - This structure provides full information about a lexed token.
Definition: Token.h:34
clang::CodeGen::CGBuilderTy::CreateStructGEP
Address CreateStructGEP(Address Addr, unsigned Index, const llvm::Twine &Name="")
Definition: CGBuilder.h:189
clang::ObjCMessageExpr::SuperClass
@ SuperClass
The receiver is a superclass.
Definition: ExprObjC.h:1094
clang::ObjCObjectType::getInterface
ObjCInterfaceDecl * getInterface() const
Gets the interface declaration for this object type, if the base type really is an interface.
Definition: Type.h:6127
clang::CodeGen::CodeGenFunction::EmitStmt
void EmitStmt(const Stmt *S, ArrayRef< const Attr * > Attrs=None)
EmitStmt - Emit the code for the statement.
Definition: CGStmt.cpp:53
ConstantEmitter.h
clang::ASTContext::toBits
int64_t toBits(CharUnits CharSize) const
Convert a size in characters to a size in bits.
Definition: ASTContext.cpp:2456
clang::CodeGen::CodeGenFunction::JumpDest::getBlock
llvm::BasicBlock * getBlock() const
Definition: CodeGenFunction.h:246
emitARCValueOperation
static llvm::Value * emitARCValueOperation(CodeGenFunction &CGF, llvm::Value *value, llvm::Type *returnType, llvm::Function *&fn, llvm::Intrinsic::ID IntID, llvm::CallInst::TailCallKind tailKind=llvm::CallInst::TCK_None)
Perform an operation having the signature i8* (i8*) where a null input causes a no-op and returns nul...
Definition: CGObjC.cpp:2126
clang::ArrayType::Normal
@ Normal
Definition: Type.h:2903
clang::Expr::isXValue
bool isXValue() const
Definition: Expr.h:272
clang::ObjCObjectPointerType::getObjectType
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:6185
clang::Expr::isGLValue
bool isGLValue() const
Definition: Expr.h:273
clang::CodeGen::CallArgList::add
void add(RValue rvalue, QualType type)
Definition: CGCall.h:286
clang::CodeGen::CodeGenFunction::EmitStoreThroughLValue
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:2118
clang::CodeGen::CodeGenFunction::Builder
CGBuilderTy Builder
Definition: CodeGenFunction.h:269
CGDebugInfo.h
clang::ObjCImplDecl::getClassInterface
const ObjCInterfaceDecl * getClassInterface() const
Definition: DeclObjC.h:2436
clang::CodeGen::CodeGenTypes::ConvertType
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
Definition: CodeGenTypes.cpp:401
clang::ObjCArrayLiteral::getArrayWithObjectsMethod
ObjCMethodDecl * getArrayWithObjectsMethod() const
Definition: ExprObjC.h:241
clang::OpaqueValueExpr
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1135
tryEmitARCRetainScalarExpr
static TryEmitResult tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e)
Definition: CGObjC.cpp:3403
clang::CodeGen::CodeGenTypeCache::VoidPtrTy
llvm::PointerType * VoidPtrTy
Definition: CodeGenTypeCache.h:56
clang::ObjCMethodDecl::createImplicitParams
void createImplicitParams(ASTContext &Context, const ObjCInterfaceDecl *ID)
createImplicitParams - Used to lazily create the self and cmd implicit parameters.
Definition: DeclObjC.cpp:1155
emitARCLoadOperation
static llvm::Value * emitARCLoadOperation(CodeGenFunction &CGF, Address addr, llvm::Function *&fn, llvm::Intrinsic::ID IntID)
Perform an operation having the following signature: i8* (i8**)
Definition: CGObjC.cpp:2150
clang::CodeGen::CodeGenFunction::GetAddrOfLocalVar
Address GetAddrOfLocalVar(const VarDecl *VD)
GetAddrOfLocalVar - Return the address of a local variable.
Definition: CodeGenFunction.h:2720
clang::CodeGen::CodeGenFunction::EmitObjCStringLiteral
llvm::Value * EmitObjCStringLiteral(const ObjCStringLiteral *E)
Emits an instance of NSConstantString representing the object.
Definition: CGObjC.cpp:48
clang::ObjCObjectType
Represents a class type in Objective C.
Definition: Type.h:5892
clang::ObjCArrayLiteral
ObjCArrayLiteral - used for objective-c array containers; as in: @["Hello", NSApp,...
Definition: ExprObjC.h:190
clang::CodeGen::CodeGenFunction::destroyARCWeak
static Destroyer destroyARCWeak
Definition: CodeGenFunction.h:4343
DeclObjC.h
clang::ObjCMessageExpr::isDelegateInitCall
bool isDelegateInitCall() const
isDelegateInitCall - Answers whether this message send has been tagged as a "delegate init call",...
Definition: ExprObjC.h:1403
clang::CodeGen::ARCImpreciseLifetime
@ ARCImpreciseLifetime
Definition: CGValue.h:125
clang::CodeGen::CodeGenFunction::EmitARCLoadWeak
llvm::Value * EmitARCLoadWeak(Address addr)
i8* @objc_loadWeak(i8** addr) Essentially objc_autorelease(objc_loadWeakRetained(addr)).
Definition: CGObjC.cpp:2561
clang::CodeGen::CGObjCRuntime::GetCppAtomicObjectGetFunction
virtual llvm::FunctionCallee GetCppAtomicObjectGetFunction()=0
API for atomic copying of qualified aggregates with non-trivial copy assignment (c++) in getter.
clang::GlobalDecl
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:56
clang::CodeGen::ObjCEntrypoints::clang_arc_use
llvm::Function * clang_arc_use
void clang.arc.use(...);
Definition: CodeGenModule.h:203
clang::CodeGen::AlignmentSource::Decl
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
clang::ASTContext::getTypeAlignInChars
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
Definition: ASTContext.cpp:2471
clang::ObjCMethodDecl::param_const_iterator
const ParmVarDecl *const * param_const_iterator
Definition: DeclObjC.h:352
clang::CodeGen::CodeGenFunction::EmitLoadOfScalar
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...
Definition: CodeGenFunction.h:3826
clang::CodeGen::CodeGenFunction::ComplexPairTy
std::pair< llvm::Value *, llvm::Value * > ComplexPairTy
Definition: CodeGenFunction.h:267
clang::CodeGen::ReturnValueSlot
ReturnValueSlot - Contains the address where the return value of a function can be stored,...
Definition: CGCall.h:360
clang::CodeGen::CodeGenFunction::EmitObjCDictionaryLiteral
llvm::Value * EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E)
Definition: CGObjC.cpp:248
arch
CudaArch arch
Definition: Cuda.cpp:73
clang::CodeGen::CodeGenFunction::EmitObjCAutoreleasePoolPush
llvm::Value * EmitObjCAutoreleasePoolPush()
Produce the code to do a objc_autoreleasepool_push.
Definition: CGObjC.cpp:2652
clang::CXXConstructExpr::arg_begin
arg_iterator arg_begin()
Definition: ExprCXX.h:1597
clang::CodeGen::ObjCEntrypoints::objc_copyWeak
llvm::Function * objc_copyWeak
void objc_copyWeak(id *dest, id *src);
Definition: CodeGenModule.h:146
clang::IdentifierInfo::isStr
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
Definition: IdentifierTable.h:176
clang::ObjCPropertyAttribute::kind_atomic
@ kind_atomic
Definition: DeclObjCCommon.h:32
clang::ASTContext::getObjCIdType
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:2033
clang::CodeGen::CGObjCRuntime::EmitThrowStmt
virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtThrowStmt &S, bool ClearInsertionPoint=true)=0
clang::ObjCPropertyImplDecl::getSetterMethodDecl
ObjCMethodDecl * getSetterMethodDecl() const
Definition: DeclObjC.h:2851
clang::Type::isReferenceType
bool isReferenceType() const
Definition: Type.h:6760
clang::CallExpr::getCallee
Expr * getCallee()
Definition: Expr.h:2951
clang::Type::isObjCClassType
bool isObjCClassType() const
Definition: Type.h:6915
V
#define V(N, I)
Definition: ASTContext.h:3176
clang::CodeGen::CodeGenTypes::arrangeObjCMethodDeclaration
const CGFunctionInfo & arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD)
Objective-C methods are C functions with some implicit parameters.
Definition: CGCall.cpp:471
clang::CodeGen::CodeGenFunction::emitScalarConstant
llvm::Value * emitScalarConstant(const ConstantEmission &Constant, Expr *E)
Definition: CGExpr.cpp:1610
clang::QualType::hasNonTrivialObjCLifetime
bool hasNonTrivialObjCLifetime() const
Definition: Type.h:1132
clang::CodeGen::CodeGenFunction::GenerateObjCCtorDtorMethod
void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP, ObjCMethodDecl *MD, bool ctor)
Definition: CGObjC.cpp:1662
clang::ReturnStmt::Create
static ReturnStmt * Create(const ASTContext &Ctx, SourceLocation RL, Expr *E, const VarDecl *NRVOCandidate)
Create a return statement.
Definition: Stmt.cpp:1193
clang::ast_matchers::expr
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
Definition: ASTMatchersInternal.cpp:890
clang::CodeGen::CodeGenFunction::RunCleanupsScope
Enters a new scope for capturing cleanups, all of which will be executed once the scope is exited.
Definition: CodeGenFunction.h:872
clang::CodeGen::CodeGenModule::SetLLVMFunctionAttributesForDefinition
void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F)
Set the LLVM function attributes which only apply to a function definition.
Definition: CodeGenModule.cpp:1888
clang::RecordType
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:4647
clang::CodeGen::ObjCEntrypoints::retainAutoreleasedReturnValueMarker
llvm::InlineAsm * retainAutoreleasedReturnValueMarker
A void(void) inline asm to use to mark that the return value of a call will be immediately retain.
Definition: CodeGenModule.h:200
clang::CodeGen::CodeGenFunction::GenerateObjCMethod
void GenerateObjCMethod(const ObjCMethodDecl *OMD)
Generate an Objective-C method.
Definition: CGObjC.cpp:805
clang::CompoundStmt
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1401
clang::CodeGen::CGObjCRuntime::GetSelector
virtual llvm::Value * GetSelector(CodeGenFunction &CGF, Selector Sel)=0
Get a selector for the specified name and type values.
clang::CodeGen::CodeGenFunction::getCurrentProfileCount
uint64_t getCurrentProfileCount()
Get the profiler's current count.
Definition: CodeGenFunction.h:1545
clang::ObjCSelectorExpr
ObjCSelectorExpr used for @selector in Objective-C.
Definition: ExprObjC.h:454
clang::Type::hasPointerRepresentation
bool hasPointerRepresentation() const
Whether this type is represented natively as a pointer.
Definition: Type.h:7184
clang::ObjCPropertyDecl::isAtomic
bool isAtomic() const
isAtomic - Return true if the property is atomic.
Definition: DeclObjC.h:839
emitARCRetainLoadOfScalar
static llvm::Value * emitARCRetainLoadOfScalar(CodeGenFunction &CGF, LValue lvalue, QualType type)
Definition: CGObjC.cpp:3407
clang::CodeGen::CodeGenFunction::EmitARCAutorelease
llvm::Value * EmitARCAutorelease(llvm::Value *value)
Autorelease the given object.
Definition: CGObjC.cpp:2505
clang::Selector::getNameForSlot
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
Definition: IdentifierTable.cpp:514
clang::CodeGen::EHScopeStack::Cleanup
Information for lazily generating a cleanup.
Definition: EHScopeStack.h:141
clang::CodeGen::ObjCEntrypoints::objc_release
llvm::Function * objc_release
void objc_release(id);
Definition: CodeGenModule.h:183
clang::LangOptions::ObjCRuntime
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:390
clang::OMF_retain
@ OMF_retain
Definition: IdentifierTable.h:710
clang::CodeGen::ARCPreciseLifetime
@ ARCPreciseLifetime
Definition: CGValue.h:125
clang::CodeGen::CodeGenFunction::emitDestroy
void emitDestroy(Address addr, QualType type, Destroyer *destroyer, bool useEHCleanupForArray)
emitDestroy - Immediately perform the destruction of the given object.
Definition: CGDecl.cpp:2192
clang::CodeGen::CodeGenModule::getObjCRuntime
CGObjCRuntime & getObjCRuntime()
Return a reference to the configured Objective-C runtime.
Definition: CodeGenModule.h:588
clang::CodeGen::CodeGenFunction::EmitObjCRetainNonBlock
llvm::Value * EmitObjCRetainNonBlock(llvm::Value *value, llvm::Type *returnType)
Retain the given object, with normal retain semantics.
Definition: CGObjC.cpp:2786
clang::CodeGen::CodeGenFunction::generateObjCSetterBody
void generateObjCSetterBody(const ObjCImplementationDecl *classImpl, const ObjCPropertyImplDecl *propImpl, llvm::Constant *AtomicHelperFn)
Definition: CGObjC.cpp:1401
clang::BinaryOperator
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3807
emitOptimizedARCReturnCall
static llvm::Value * emitOptimizedARCReturnCall(llvm::Value *value, bool IsRetainRV, CodeGenFunction &CGF)
Definition: CGObjC.cpp:2338
clang::CodeGen::CGObjCRuntime::EmitNSAutoreleasePoolClassRef
virtual llvm::Value * EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF)
Definition: CGObjCRuntime.h:275
clang::Qualifiers::OCL_Strong
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:175
clang::Scope
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:40
clang::ObjCAtThrowStmt
Represents Objective-C's @throw statement.
Definition: StmtObjC.h:357
clang::CodeGen::CodeGenFunction::AutoVarEmission
Definition: CodeGenFunction.h:3054
clang::SelectorTable::getSelector
Selector getSelector(unsigned NumArgs, IdentifierInfo **IIV)
Can create any sort of selector.
Definition: IdentifierTable.cpp:713
clang::CodeGen::CodeGenFunction::EmitObjCBoxedExpr
llvm::Value * EmitObjCBoxedExpr(const ObjCBoxedExpr *E)
EmitObjCBoxedExpr - This routine generates code to call the appropriate expression boxing method.
Definition: CGObjC.cpp:62
clang::CodeGen::CodeGenFunction::EmitCheck
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 either trap or call a handler function in the UBSan runtime with the p...
Definition: CGExpr.cpp:3278
clang::ASTContext::Selectors
SelectorTable & Selectors
Definition: ASTContext.h:656
clang::CharUnits::fromQuantity
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:63
object
clang::ObjCStringLiteral
ObjCStringLiteral, used for Objective-C string literals i.e.
Definition: ExprObjC.h:52
clang::BlockExpr::getBlockDecl
const BlockDecl * getBlockDecl() const
Definition: Expr.h:5982
clang::CodeGen::CodeGenFunction::EmitARCUnsafeUnretainedScalarExpr
llvm::Value * EmitARCUnsafeUnretainedScalarExpr(const Expr *expr)
EmitARCUnsafeUnretainedScalarExpr - Semantically equivalent to immediately releasing the resut of Emi...
Definition: CGObjC.cpp:3546
clang::CodeGen::CodeGenModule::getCodeGenOpts
const CodeGenOptions & getCodeGenOpts() const
Definition: CodeGenModule.h:703
clang::ObjCDictionaryElement::Key
Expr * Key
The key for the dictionary element.
Definition: ExprObjC.h:265
clang::CodeGen::CodeGenFunction::EmitARCAutoreleaseReturnValue
llvm::Value * EmitARCAutoreleaseReturnValue(llvm::Value *value)
Autorelease the given object.
Definition: CGObjC.cpp:2514
clang::ObjCMethodDecl::getMethodFamily
ObjCMethodFamily getMethodFamily() const
Determines the family of this method.
Definition: DeclObjC.cpp:1018
clang::CodeGen::Address::getType
llvm::PointerType * getType() const
Return the type of the pointer value.
Definition: Address.h:99
clang::Decl::getBodyRBrace
SourceLocation getBodyRBrace() const
getBodyRBrace - Gets the right brace of the body, if a body exists.
Definition: DeclBase.cpp:952
clang::FPOptionsOverride
Represents difference between two FPOptions values.
Definition: LangOptions.h:713
clang::CodeGen::CodeGenFunction::AutoVarEmission::invalid
static AutoVarEmission invalid()
Definition: CodeGenFunction.h:3095
clang::ASTContext
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:208
clang::GetUnarySelector
Selector GetUnarySelector(StringRef name, ASTContext &Ctx)
Utility function for constructing an unary selector.
Definition: ASTContext.h:3322
clang::ASTContext::getSizeType
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
Definition: ASTContext.cpp:5823
CGFunctionInfo.h
clang::CodeGen::CodeGenFunction::EmitObjCExtendObjectLifetime
llvm::Value * EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr)
Definition: CGObjC.cpp:2073
clang::CodeGen::CodeGenFunction::EmitObjCAllocInit
llvm::Value * EmitObjCAllocInit(llvm::Value *value, llvm::Type *resultType)
Definition: CGObjC.cpp:2733
clang::CPlusPlus
@ CPlusPlus
Definition: LangStandard.h:53
clang::CodeGen::CodeGenFunction::EmitARCStoreWeak
llvm::Value * EmitARCStoreWeak(Address addr, llvm::Value *value, bool ignored)
i8* @objc_storeWeak(i8** addr, i8* value) Returns value.
Definition: CGObjC.cpp:2576
clang::ObjCDictionaryLiteral
ObjCDictionaryLiteral - AST node to represent objective-c dictionary literals; as in:"name" : NSUserN...
Definition: ExprObjC.h:306
Diagnostic.h
clang::CodeGen::CodeGenFunction::EmitRuntimeCall
llvm::CallInst * EmitRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
clang::Selector::getNumArgs
unsigned getNumArgs() const
Definition: IdentifierTable.cpp:492
clang::CodeGen::TEK_Complex
@ TEK_Complex
Definition: CodeGenFunction.h:108
ValueTransform
llvm::function_ref< llvm::Value *(CodeGenFunction &CGF, llvm::Value *value)> ValueTransform
Definition: CGObjC.cpp:2929
clang::PseudoObjectExpr::const_semantics_iterator
const typedef Expr *const * const_semantics_iterator
Definition: Expr.h:6167
clang::Type::getAs
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:7243
clang::CodeGen::CodeGenFunction::getDebugInfo
CGDebugInfo * getDebugInfo()
Definition: CodeGenFunction.h:1983
clang::CodeGen::ObjCEntrypoints::objc_storeStrong
llvm::Function * objc_storeStrong
void objc_storeStrong(id*, id);
Definition: CodeGenModule.h:190
clang::CodeGen::CodeGenFunction::ConstantEmission
Definition: CodeGenFunction.h:3934
clang::ObjCMethodDecl::getSelector
Selector getSelector() const
Definition: DeclObjC.h:330
emitARCCopyOperation
static void emitARCCopyOperation(CodeGenFunction &CGF, Address dst, Address src, llvm::Function *&fn, llvm::Intrinsic::ID IntID)
Perform an operation having the following signature: void (i8**, i8**)
Definition: CGObjC.cpp:2197
tryEmitSpecializedAllocInit
static Optional< llvm::Value * > tryEmitSpecializedAllocInit(CodeGenFunction &CGF, const ObjCMessageExpr *OME)
Instead of '[[MyClass alloc] init]', try to generate 'objc_alloc_init(MyClass)'.
Definition: CGObjC.cpp:524
clang::CodeGen::CodeGenTypeCache::VoidTy
llvm::Type * VoidTy
void
Definition: CodeGenTypeCache.h:34
clang::ObjCRuntime::hasARCUnsafeClaimAutoreleasedReturnValue
bool hasARCUnsafeClaimAutoreleasedReturnValue() const
Is objc_unsafeClaimAutoreleasedReturnValue available?
Definition: ObjCRuntime.h:403
clang::ObjCPropertyImplDecl::getGetterCXXConstructor
Expr * getGetterCXXConstructor() const
Definition: DeclObjC.h:2854
clang::ObjCMethodDecl::isDirectMethod
bool isDirectMethod() const
True if the method is tagged as objc_direct.
Definition: DeclObjC.cpp:836
clang::TargetInfo::getPlatformMinVersion
VersionTuple getPlatformMinVersion() const
Retrieve the minimum desired version of the platform, to which the program should be compiled.
Definition: TargetInfo.h:1482
clang::ObjCMethodDecl::getSelfDecl
ImplicitParamDecl * getSelfDecl() const
Definition: DeclObjC.h:423
clang::PseudoObjectExpr
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:6100
clang::ObjCAtSynchronizedStmt
Represents Objective-C's @synchronized statement.
Definition: StmtObjC.h:302
clang::ObjCMessageExpr::getReceiverKind
ReceiverKind getReceiverKind() const
Determine the kind of receiver that this message is being sent to.
Definition: ExprObjC.h:1224
clang::CodeGen::CodeGenModule::getModule
llvm::Module & getModule() const
Definition: CodeGenModule.h:704
clang::CodeGen::CGObjCRuntime::EmitTryStmt
virtual void EmitTryStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtTryStmt &S)=0
clang::CodeGen::CodeGenFunction::EmitARCStoreStrongCall
llvm::Value * EmitARCStoreStrongCall(Address addr, llvm::Value *value, bool resultIgnored)
Store into a strong object.
Definition: CGObjC.cpp:2448
clang::ASTContext::getTypeSize
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2285
emitIsPlatformVersionAtLeast
static llvm::Value * emitIsPlatformVersionAtLeast(CodeGenFunction &CGF, const VersionTuple &Version)
Definition: CGObjC.cpp:3905
clang::CodeGen::CGDebugInfo
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
Definition: CGDebugInfo.h:55
clang::DeclRefExpr::getDecl
ValueDecl * getDecl()
Definition: Expr.h:1295
clang::CodeGen::CodeGenFunction::getCleanupKind
CleanupKind getCleanupKind(QualType::DestructionKind kind)
Definition: CodeGenFunction.h:2090
clang::ImplicitParamDecl
Definition: Decl.h:1613
clang::ObjCMessageExpr::Class
@ Class
The receiver is a class.
Definition: ExprObjC.h:1088
clang::CodeGen::LValue::getType
QualType getType() const
Definition: CGValue.h:278
clang::CodeGen::CGObjCRuntime::EnumerationMutationFunction
virtual llvm::FunctionCallee EnumerationMutationFunction()=0
EnumerationMutationFunction - Return the function that's called by the compiler when a mutation is de...
clang::TypeInfoChars::Width
CharUnits Width
Definition: ASTContext.h:193
clang::interp::Cast
bool Cast(InterpState &S, CodePtr OpPC)
Definition: Interp.h:802
ASTContext.h
clang::VarDecl
Represents a variable declaration or definition.
Definition: Decl.h:874
clang::ObjCMethodDecl::getReturnType
QualType getReturnType() const
Definition: DeclObjC.h:332
clang::CodeGen::CGObjCRuntime::GetGetStructFunction
virtual llvm::FunctionCallee GetGetStructFunction()=0
clang::Type::getPointeeType
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:625
clang::CodeGen::CodeGenModule::getTypes
CodeGenTypes & getTypes()
Definition: CodeGenModule.h:721
clang::dataflow::var
static constexpr Variable var(Literal L)
Returns the variable of L.
Definition: WatchedLiteralsSolver.cpp:71
clang::CXXConstructExpr::getConstructor
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1532
clang::CodeGen::CGObjCRuntime::GenerateProtocolRef
virtual llvm::Value * GenerateProtocolRef(CodeGenFunction &CGF, const ObjCProtocolDecl *OPD)=0
Emit the code to return the named protocol as an object, as in a @protocol expression.
clang::ExprWithCleanups
Represents an expression – generally a full-expression – that introduces cleanups to be run at the en...
Definition: ExprCXX.h:3359
clang::CodeGen::CodeGenFunction::EmitAutoVarInit
void EmitAutoVarInit(const AutoVarEmission &emission)
Definition: CGDecl.cpp:1811
clang::ObjCDictionaryLiteral::getDictWithObjectsMethod
ObjCMethodDecl * getDictWithObjectsMethod() const
Definition: ExprObjC.h:376
llvm::DenseSet
Definition: Sema.h:77
clang::CodeGen::AggValueSlot::IsDestructed
@ IsDestructed
Definition: CGValue.h:551
getBaseMachOPlatformID
static unsigned getBaseMachOPlatformID(const llvm::Triple &TT)
Definition: CGObjC.cpp:3887
clang::CodeGen::CodeGenFunction::EmitAutoVarAlloca
AutoVarEmission EmitAutoVarAlloca(const VarDecl &var)
EmitAutoVarAlloca - Emit the alloca and debug information for a local variable.
Definition: CGDecl.cpp:1424
clang::CodeGen::CodeGenFunction::getLLVMContext
llvm::LLVMContext & getLLVMContext()
Definition: CodeGenFunction.h:2025
clang::CodeGen::CodeGenFunction::EmitObjCAutorelease
llvm::Value * EmitObjCAutorelease(llvm::Value *value, llvm::Type *returnType)
Autorelease the given object.
Definition: CGObjC.cpp:2776
clang::Type::isAtomicType
bool isAtomicType() const
Definition: Type.h:6889
clang::CodeGen::CodeGenFunction::getContext
ASTContext & getContext() const
Definition: CodeGenFunction.h:1982
clang::ObjCMethodDecl::getEndLoc
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclObjC.cpp:1012
clang::CodeGen::NormalCleanup
@ NormalCleanup
Denotes a cleanup that should run when a scope is exited using normal control flow (falling off the e...
Definition: EHScopeStack.h:84
clang::CodeGen::CodeGenFunction::incrementProfileCounter
void incrementProfileCounter(const Stmt *S, llvm::Value *StepV=nullptr)
Increment the profiler's counter for the given statement by StepV.
Definition: CodeGenFunction.h:1523
clang::CodeGen::CodeGenFunction::FinishFunction
void FinishFunction(SourceLocation EndLoc=SourceLocation())
FinishFunction - Complete IR generation of the current function.
Definition: CodeGenFunction.cpp:325
clang::CodeGen::Address
An aligned address.
Definition: Address.h:74
AppendFirstImpliedRuntimeProtocols
static void AppendFirstImpliedRuntimeProtocols(const ObjCProtocolDecl *PD, llvm::UniqueVector< const ObjCProtocolDecl * > &PDs)
Definition: CGObjC.cpp:451
clang::CodeGen::CodeGenFunction::getJumpDestInCurrentScope
JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target)
The given basic block lies in the current EH scope, but may be a target of a potentially scope-crossi...
Definition: CodeGenFunction.h:1145
clang::CodeGen::CodeGenFunction::EmitARCRetainAutoreleaseNonBlock
llvm::Value * EmitARCRetainAutoreleaseNonBlock(llvm::Value *value)
Do a fused retain/autorelease of the given object.
Definition: CGObjC.cpp:2553
CodeGenModule.h
clang::ObjCPropertyDecl::getType
QualType getType() const
Definition: DeclObjC.h:800
clang::CodeGen::CodeGenFunction::EmitObjCForCollectionStmt
void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S)
Definition: CGObjC.cpp:1714
clang::CodeGen::CodeGenFunction::getARCCleanupKind
CleanupKind getARCCleanupKind()
Retrieves the default cleanup kind for an ARC cleanup.
Definition: CodeGenFunction.h:4276
clang::FunctionDecl::Create
static FunctionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation NLoc, DeclarationName N, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin=false, bool isInlineSpecified=false, bool hasWrittenPrototype=true, ConstexprSpecKind ConstexprKind=ConstexprSpecKind::Unspecified, Expr *TrailingRequiresClause=nullptr)
Definition: Decl.h:2044
clang::CodeGen::CodeGenFunction::SanOpts
SanitizerSet SanOpts
Sanitizers enabled for this function.
Definition: CodeGenFunction.h:518
clang::CodeGen::CGBuilderTy::CreateGEP
Address CreateGEP(Address Addr, llvm::Value *Index, const llvm::Twine &Name="")
Definition: CGBuilder.h:261
clang::CodeGen::CodeGenFunction::getEvaluationKind
static TypeEvaluationKind getEvaluationKind(QualType T)
getEvaluationKind - Return the TypeEvaluationKind of QualType T.
Definition: CodeGenFunction.cpp:216
clang::CodeGen::CGObjCRuntime::GetPropertySetFunction
virtual llvm::FunctionCallee GetPropertySetFunction()=0
Return the runtime function for setting properties.
clang::Selector::getMethodFamily
ObjCMethodFamily getMethodFamily() const
Derive the conventional family of this method.
Definition: IdentifierTable.h:876
clang::CXXConstructExpr::hadMultipleCandidates
bool hadMultipleCandidates() const
Whether the referred constructor was resolved from an overloaded set having size greater than 1.
Definition: ExprCXX.h:1543
clang::CodeGen::CodeGenModule::getAtomicSetterHelperFnMap
llvm::Constant * getAtomicSetterHelperFnMap(QualType Ty)
Definition: CodeGenModule.h:666
clang::CodeGen::CodeGenFunction::EmitObjCArrayLiteral
llvm::Value * EmitObjCArrayLiteral(const ObjCArrayLiteral *E)
Definition: CGObjC.cpp:244
getKind
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1008
clang::CodeGen::ObjCEntrypoints::objc_autorelease
llvm::Function * objc_autorelease
id objc_autorelease(id);
Definition: CodeGenModule.h:136
clang::CodeGen::CodeGenFunction::emitARCIntrinsicUse
static Destroyer emitARCIntrinsicUse
Definition: CodeGenFunction.h:4344
clang::ObjCMessageExpr
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:940
tryEmitARCRetainLoadOfScalar
static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF, LValue lvalue, QualType type)
Definition: CGObjC.cpp:2866
clang::CodeGen::CodeGenFunction::EmitObjCAllocWithZone
llvm::Value * EmitObjCAllocWithZone(llvm::Value *value, llvm::Type *returnType)
Allocate the given objc object.
Definition: CGObjC.cpp:2726
clang::CodeGen::ObjCEntrypoints::objc_retainAutorelease
llvm::Function * objc_retainAutorelease
id objc_retainAutorelease(id);
Definition: CodeGenModule.h:171
clang::CastExpr::getCastKind
CastKind getCastKind() const
Definition: Expr.h:3519
clang::Qualifiers::OCL_Autoreleasing
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:181
StmtObjC.h
getARCIntrinsic
static llvm::Function * getARCIntrinsic(llvm::Intrinsic::ID IntID, CodeGenModule &CGM)
Definition: CGObjC.cpp:2116
clang::CodeGen::CodeGenFunction::EmitAnyExprToMem
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:241
clang::Qualifiers::setObjCLifetime
void setObjCLifetime(ObjCLifetime type)
Definition: Type.h:340
clang::CodeGen::CGCallee::forDirect
static CGCallee forDirect(llvm::Constant *functionPtr, const CGCalleeInfo &abstractInfo=CGCalleeInfo())
Definition: CGCall.h:133
clang::CXXOperatorCallExpr::Create
static CXXOperatorCallExpr * Create(const ASTContext &Ctx, OverloadedOperatorKind OpKind, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation OperatorLoc, FPOptionsOverride FPFeatures, ADLCallKind UsesADL=NotADL)
Definition: ExprCXX.cpp:558
clang::Qualifiers::ObjCLifetime
ObjCLifetime
Definition: Type.h:162
clang::CodeGen::CodeGenFunction::EmitARCRetainScalarExpr
llvm::Value * EmitARCRetainScalarExpr(const Expr *expr)
EmitARCRetainScalarExpr - Semantically equivalent to EmitARCRetainObject(e->getType(),...
Definition: CGObjC.cpp:3421
clang::SC_Static
@ SC_Static
Definition: Specifiers.h:237
clang::CodeGen::CodeGenModule::getTarget
const TargetInfo & getTarget() const
Definition: CodeGenModule.h:709
clang::QualType::getUnqualifiedType
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:6580
clang::CodeGen::ObjCEntrypoints::objc_alloc_init
llvm::FunctionCallee objc_alloc_init
void objc_alloc_init(id);
Definition: CodeGenModule.h:123
clang::CodeGen::CodeGenFunction::CurGD
GlobalDecl CurGD
CurGD - The GlobalDecl for the current function being compiled.
Definition: CodeGenFunction.h:345
clang::CodeGen::CodeGenTypeCache::Int32Ty
llvm::IntegerType * Int32Ty
Definition: CodeGenTypeCache.h:37
clang::CodeGen::CodeGenFunction::destroyARCStrongImprecise
static Destroyer destroyARCStrongImprecise
Definition: CodeGenFunction.h:4341
clang::Type::isObjCObjectPointerType
bool isObjCObjectPointerType() const
Definition: Type.h:6876
clang::CodeGen::ObjCEntrypoints::objc_retain
llvm::Function * objc_retain
id objc_retain(id);
Definition: CodeGenModule.h:164
clang::ObjCPropertyDecl::getSetterKind
SetterKind getSetterKind() const
getSetterKind - Return the method used for doing assignment in the property setter.
Definition: DeclObjC.h:869
shouldEmitSeparateBlockRetain
static bool shouldEmitSeparateBlockRetain(const Expr *e)
Determine whether it might be important to emit a separate objc_retain_block on the result of the giv...
Definition: CGObjC.cpp:3031
clang::CodeGen::ObjCEntrypoints::objc_initWeak
llvm::Function * objc_initWeak
id objc_initWeak(id*, id);
Definition: CodeGenModule.h:152
clang::CodeGen::CodeGenModule::IsPlatformVersionAtLeastFn
llvm::FunctionCallee IsPlatformVersionAtLeastFn
Definition: CodeGenModule.h:631
clang::CodeGen::CGObjCRuntime::GenerateMessageSendSuper
virtual CodeGen::RValue GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF, ReturnValueSlot ReturnSlot, QualType ResultType, Selector Sel, const ObjCInterfaceDecl *Class, bool isCategoryImpl, llvm::Value *Self, bool IsClassMessage, const CallArgList &CallArgs, const ObjCMethodDecl *Method=nullptr)=0
Generate an Objective-C message send operation to the super class initiated in a method for Class and...
clang::CodeGen::CGObjCRuntime::EmitSynchronizedStmt
virtual void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtSynchronizedStmt &S)=0
clang::VK_LValue
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:124
clang::ObjCPropertyDecl::Copy
@ Copy
Definition: DeclObjC.h:736
clang::CodeGen::CodeGenTypes::GetFunctionType
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
Definition: CGCall.cpp:1613
clang::CodeGen::CodeGenModule::getDataLayout
const llvm::DataLayout & getDataLayout() const
Definition: CodeGenModule.h:706
clang::Type::castAs
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:7310
clang::ObjCDictionaryLiteral::getKeyValueElement
ObjCDictionaryElement getKeyValueElement(unsigned Index) const
Definition: ExprObjC.h:362
clang::CodeGen::CodeGenFunction::EmitObjCAlloc
llvm::Value * EmitObjCAlloc(llvm::Value *value, llvm::Type *returnType)
Allocate the given objc object.
Definition: CGObjC.cpp:2717
clang::ObjCRuntime::hasAtomicCopyHelper
bool hasAtomicCopyHelper() const
Definition: ObjCRuntime.h:389
clang::Expr::IgnoreParenCasts
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:2952
clang::TargetInfo::getTriple
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1160
clang::CodeGen::CodeGenFunction::OpaqueValueMappingData
A non-RAII class containing all the information about a bound opaque value.
Definition: CodeGenFunction.h:1255
clang::ObjCObjectPointerType
Represents a pointer to an Objective C object.
Definition: Type.h:6148
clang::CodeGen::ObjCEntrypoints::objc_autoreleasePoolPopInvoke
llvm::FunctionCallee objc_autoreleasePoolPopInvoke
void objc_autoreleasePoolPop(void*); Note this method is used when we are using exception handling
Definition: CodeGenModule.h:130
clang::CodeGen::CodeGenFunction::StartFunction
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.
Definition: CodeGenFunction.cpp:709
clang::ObjCImplementationDecl::inits
init_range inits()
Definition: DeclObjC.h:2610
clang::CodeGen::CGObjCRuntime::GeneratePossiblySpecializedMessageSend
CodeGen::RValue GeneratePossiblySpecializedMessageSend(CodeGenFunction &CGF, ReturnValueSlot Return, QualType ResultType, Selector Sel, llvm::Value *Receiver, const CallArgList &Args, const ObjCInterfaceDecl *OID, const ObjCMethodDecl *Method, bool isClassMessage)
Generate an Objective-C message send operation.
Definition: CGObjC.cpp:437
clang::BinaryOperator::Create
static BinaryOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures)
Definition: Expr.cpp:4538
clang::CodeGen::LValue
LValue - This represents an lvalue references.
Definition: CGValue.h:171
clang::CodeGen::CodeGenFunction::EHStack
EHScopeStack EHStack
Definition: CodeGenFunction.h:619
clang::CodeGen::CodeGenFunction::getOverlapForReturnValue
AggValueSlot::Overlap_t getOverlapForReturnValue()
Determine whether a return value slot may overlap some other object.
Definition: CodeGenFunction.h:2681
clang::CodeGen::CGObjCRuntime::GenerateMethod
virtual llvm::Function * GenerateMethod(const ObjCMethodDecl *OMD, const ObjCContainerDecl *CD)=0
Generate a function preamble for a method with the specified types.
clang::VK_PRValue
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:120
clang::CodeGen::CodeGenFunction::MakeNaturalAlignAddrLValue
LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T)
Definition: CodeGenFunction.cpp:187
clang::CodeGen::AggValueSlot::forAddr
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:574
clang::CodeGen::CodeGenFunction::EmitDeclRefLValue
LValue EmitDeclRefLValue(const DeclRefExpr *E)
Definition: CGExpr.cpp:2746
clang::ASTContext::VoidPtrTy
CanQualType VoidPtrTy
Definition: ASTContext.h:1123
clang::FieldDecl::isBitField
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:2933
clang::Type::isPointerType
bool isPointerType() const
Definition: Type.h:6748
clang::CodeGen::CodeGenFunction::EmitARCStoreUnsafeUnretained
std::pair< LValue, llvm::Value * > EmitARCStoreUnsafeUnretained(const BinaryOperator *e, bool ignored)
Definition: CGObjC.cpp:3557
clang::CodeGen::CodeGenFunction::EmitCallOrInvoke
llvm::CallBase * EmitCallOrInvoke(llvm::FunctionCallee Callee, ArrayRef< llvm::Value * > Args, const Twine &Name="")
Emits a call or invoke instruction to the given function, depending on the current state of the EH st...
Definition: CGCall.cpp:4541
clang::CodeGen::Address::getPointer
llvm::Value * getPointer() const
Definition: Address.h:93
clang::CodeGen::CodeGenModule::ErrorUnsupported
void ErrorUnsupported(const Stmt *S, const char *Type)
Print out an error that codegen doesn't support the specified stmt yet.
Definition: CodeGenModule.cpp:1059
clang::CodeGen::CodeGenFunction
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
Definition: CodeGenFunction.h:231
clang::CodeGen::CodeGenModule::getObjCFastEnumerationStateType
QualType getObjCFastEnumerationStateType()
Retrieve the record type that describes the state of an Objective-C fast enumeration loop (for....
Definition: CodeGenModule.cpp:5539
clang::ValueDecl
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:674
clang::CodeGen::CGObjCRuntime::~CGObjCRuntime
virtual ~CGObjCRuntime()
Definition: CGObjC.cpp:4033
clang::CodeGen::CodeGenFunction::getBundlesForFunclet
SmallVector< llvm::OperandBundleDef, 1 > getBundlesForFunclet(llvm::Value *Callee)
Definition: CGCall.cpp:4473
clang::CodeGen::CGObjCRuntime::GenerateDirectMethodPrologue
virtual void GenerateDirectMethodPrologue(CodeGenFunction &CGF, llvm::Function *Fn, const ObjCMethodDecl *OMD, const ObjCContainerDecl *CD)=0
Generates prologue for direct Objective-C Methods.
clang::LangOptions::NonGC
@ NonGC
Definition: LangOptions.h:83
clang::ObjCArrayLiteral::getElement
Expr * getElement(unsigned Index)
getElement - Return the Element at the specified index.
Definition: ExprObjC.h:232
clang::BinaryOperator::getLHS
Expr * getLHS() const
Definition: Expr.h:3856
clang::CharUnits::isZero
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:116
clang::CodeGen::CodeGenModule::CreateRuntimeVariable
llvm::Constant * CreateRuntimeVariable(llvm::Type *Ty, StringRef Name)
Create a new runtime global variable with the specified type and name.
Definition: CodeGenModule.cpp:4376
clang::CodeGen::AggValueSlot::IsNotAliased
@ IsNotAliased
Definition: CGValue.h:550
clang::ASTContext::Idents
IdentifierTable & Idents
Definition: ASTContext.h:655
clang::ObjCProtocolExpr
ObjCProtocolExpr used for protocol expression in Objective-C.
Definition: ExprObjC.h:504
clang::CodeGen::CodeGenFunction::EmitARCMoveWeak
void EmitARCMoveWeak(Address dst, Address src)
void @objc_moveWeak(i8** dest, i8** src) Disregards the current value in dest.
Definition: CGObjC.cpp:2620
clang::ObjCImplDecl
Definition: DeclObjC.h:2421
clang::CodeGen::CodeGenModule
This class organizes the cross-function state that is used while generating LLVM code.
Definition: CodeGenModule.h:275
clang::QualType::DK_objc_strong_lifetime
@ DK_objc_strong_lifetime
Definition: Type.h:1213
clang::CodeGen::CodeGenFunction::EmitARCRelease
void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise)
Release the given object.
Definition: CGObjC.cpp:2405
shouldExtendReceiverForInnerPointerMessage
static bool shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message)
Decide whether to extend the lifetime of the receiver of a returns-inner-pointer message.
Definition: CGObjC.cpp:288
clang::BlockExpr
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:5970
llvm::ArrayRef
Definition: LLVM.h:34
Value
Value
Definition: UninitializedValues.cpp:102
clang::ObjCPropertyDecl::SetterKind
SetterKind
Definition: DeclObjC.h:736
clang::CodeGen::CodeGenModule::getTriple
const llvm::Triple & getTriple() const
Definition: CodeGenModule.h:710
clang::CodeGen::CodeGenFunction::EmitAggExpr
void EmitAggExpr(const Expr *E, AggValueSlot AS)
EmitAggExpr - Emit the computation of the specified expression of aggregate type.
Definition: CGExprAgg.cpp:1993
clang::ObjCPropertyDecl
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:732
clang::ObjCMethodDecl::isInstanceMethod
bool isInstanceMethod() const
Definition: DeclObjC.h:431
clang::CodeGen::Address::invalid
static Address invalid()
Definition: Address.h:90
clang::CodeGen::CGBuilderTy::CreateAlignedLoad
llvm::LoadInst * CreateAlignedLoad(llvm::Type *Ty, llvm::Value *Addr, CharUnits Align, const llvm::Twine &Name="")
Definition: CGBuilder.h:87
clang::CodeGen::AggValueSlot::forLValue
static AggValueSlot forLValue(const LValue &LV, CodeGenFunction &CGF, IsDestructed_t isDestructed, NeedsGCBarriers_t needsGC, IsAliased_t isAliased, Overlap_t mayOverlap, IsZeroed_t isZeroed=IsNotZeroed, IsSanitizerChecked_t isChecked=IsNotSanitizerChecked)
Definition: CGValue.h:587
clang::CodeGen::CodeGenFunction::EmitObjCAtSynchronizedStmt
void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S)
Definition: CGObjC.cpp:2046
clang::CodeGen::CGObjCRuntime::GenerateConstantString
virtual ConstantAddress GenerateConstantString(const StringLiteral *)=0
Generate a constant string object.
clang::CodeGen::ObjCEntrypoints::objc_loadWeak
llvm::Function * objc_loadWeak
id objc_loadWeak(id*);
Definition: CodeGenModule.h:155
clang::Type::getAsObjCInterfacePointerType
const ObjCObjectPointerType * getAsObjCInterfacePointerType() const
Definition: Type.cpp:1736
clang::CodeGen::CGCallee
All available information about a concrete callee.
Definition: CGCall.h:63
clang::CodeGen::FunctionArgList
FunctionArgList - Type for representing both the decl and type of parameters to a function.
Definition: CGCall.h:356
clang::QualType::DestructionKind
DestructionKind
Definition: Type.h:1210
clang::CodeGen::CodeGenFunction::getTypes
CodeGenTypes & getTypes() const
Definition: CodeGenFunction.h:1981
clang::Selector::getIdentifierInfoForSlot
IdentifierInfo * getIdentifierInfoForSlot(unsigned argIndex) const
Retrieve the identifier at a given position in the selector.
Definition: IdentifierTable.cpp:503
clang::ObjCInterfaceDecl::getSuperClass
ObjCInterfaceDecl * getSuperClass() const
Definition: DeclObjC.cpp:351
clang::CodeGen::CGObjCRuntime::GetCppAtomicObjectSetFunction
virtual llvm::FunctionCallee GetCppAtomicObjectSetFunction()=0
API for atomic copying of qualified aggregates with non-trivial copy assignment (c++) in setter.
clang::CodeGen::CodeGenFunction::ConvertType
llvm::Type * ConvertType(QualType T)
Definition: CodeGenFunction.cpp:212
clang::CodeGen::ObjCEntrypoints::objc_destroyWeak
llvm::Function * objc_destroyWeak
void objc_destroyWeak(id*);
Definition: CodeGenModule.h:149
clang::ObjCBoxedExpr::getBoxingMethod
ObjCMethodDecl * getBoxingMethod() const
Definition: ExprObjC.h:147
clang::CodeGen::CodeGenFunction::EmitARCIntrinsicUse
void EmitARCIntrinsicUse(ArrayRef< llvm::Value * > values)
Given a number of pointers, inform the optimizer that they're being intrinsically used up until this ...
Definition: CGObjC.cpp:2080
clang::CodeGen::CodeGenTypes
This class organizes the cross-module state that is used while lowering AST types to LLVM types.
Definition: CodeGenTypes.h:54
clang::CodeGen::ObjCEntrypoints::objc_releaseRuntimeFunction
llvm::FunctionCallee objc_releaseRuntimeFunction
void objc_release(id); Note th