clang  7.0.0svn
CGObjC.cpp
Go to the documentation of this file.
1 //===---- CGObjC.cpp - Emit LLVM Code for Objective-C ---------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This contains code to emit Objective-C code as LLVM code.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CGDebugInfo.h"
15 #include "CGObjCRuntime.h"
16 #include "CodeGenFunction.h"
17 #include "CodeGenModule.h"
18 #include "TargetInfo.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/StmtObjC.h"
22 #include "clang/Basic/Diagnostic.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/IR/CallSite.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/InlineAsm.h"
28 using namespace clang;
29 using namespace CodeGen;
30 
31 typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
32 static TryEmitResult
35  QualType ET,
36  RValue Result);
37 
38 /// Given the address of a variable of pointer type, find the correct
39 /// null to store into it.
40 static llvm::Constant *getNullForVariable(Address addr) {
41  llvm::Type *type = addr.getElementType();
42  return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
43 }
44 
45 /// Emits an instance of NSConstantString representing the object.
47 {
48  llvm::Constant *C =
50  // FIXME: This bitcast should just be made an invariant on the Runtime.
51  return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
52 }
53 
54 /// EmitObjCBoxedExpr - This routine generates code to call
55 /// the appropriate expression boxing method. This will either be
56 /// one of +[NSNumber numberWith<Type>:], or +[NSString stringWithUTF8String:],
57 /// or [NSValue valueWithBytes:objCType:].
58 ///
61  // Generate the correct selector for this literal's concrete type.
62  // Get the method.
63  const ObjCMethodDecl *BoxingMethod = E->getBoxingMethod();
64  const Expr *SubExpr = E->getSubExpr();
65  assert(BoxingMethod && "BoxingMethod is null");
66  assert(BoxingMethod->isClassMethod() && "BoxingMethod must be a class method");
67  Selector Sel = BoxingMethod->getSelector();
68 
69  // Generate a reference to the class pointer, which will be the receiver.
70  // Assumes that the method was introduced in the class that should be
71  // messaged (avoids pulling it out of the result type).
72  CGObjCRuntime &Runtime = CGM.getObjCRuntime();
73  const ObjCInterfaceDecl *ClassDecl = BoxingMethod->getClassInterface();
74  llvm::Value *Receiver = Runtime.GetClass(*this, ClassDecl);
75 
76  CallArgList Args;
77  const ParmVarDecl *ArgDecl = *BoxingMethod->param_begin();
78  QualType ArgQT = ArgDecl->getType().getUnqualifiedType();
79 
80  // ObjCBoxedExpr supports boxing of structs and unions
81  // via [NSValue valueWithBytes:objCType:]
82  const QualType ValueType(SubExpr->getType().getCanonicalType());
83  if (ValueType->isObjCBoxableRecordType()) {
84  // Emit CodeGen for first parameter
85  // and cast value to correct type
86  Address Temporary = CreateMemTemp(SubExpr->getType());
87  EmitAnyExprToMem(SubExpr, Temporary, Qualifiers(), /*isInit*/ true);
88  Address BitCast = Builder.CreateBitCast(Temporary, ConvertType(ArgQT));
89  Args.add(RValue::get(BitCast.getPointer()), ArgQT);
90 
91  // Create char array to store type encoding
92  std::string Str;
93  getContext().getObjCEncodingForType(ValueType, Str);
94  llvm::Constant *GV = CGM.GetAddrOfConstantCString(Str).getPointer();
95 
96  // Cast type encoding to correct type
97  const ParmVarDecl *EncodingDecl = BoxingMethod->parameters()[1];
98  QualType EncodingQT = EncodingDecl->getType().getUnqualifiedType();
99  llvm::Value *Cast = Builder.CreateBitCast(GV, ConvertType(EncodingQT));
100 
101  Args.add(RValue::get(Cast), EncodingQT);
102  } else {
103  Args.add(EmitAnyExpr(SubExpr), ArgQT);
104  }
105 
106  RValue result = Runtime.GenerateMessageSend(
107  *this, ReturnValueSlot(), BoxingMethod->getReturnType(), Sel, Receiver,
108  Args, ClassDecl, BoxingMethod);
109  return Builder.CreateBitCast(result.getScalarVal(),
110  ConvertType(E->getType()));
111 }
112 
114  const ObjCMethodDecl *MethodWithObjects) {
115  ASTContext &Context = CGM.getContext();
116  const ObjCDictionaryLiteral *DLE = nullptr;
117  const ObjCArrayLiteral *ALE = dyn_cast<ObjCArrayLiteral>(E);
118  if (!ALE)
119  DLE = cast<ObjCDictionaryLiteral>(E);
120 
121  // Optimize empty collections by referencing constants, when available.
122  uint64_t NumElements =
123  ALE ? ALE->getNumElements() : DLE->getNumElements();
124  if (NumElements == 0 && CGM.getLangOpts().ObjCRuntime.hasEmptyCollections()) {
125  StringRef ConstantName = ALE ? "__NSArray0__" : "__NSDictionary0__";
127  llvm::Constant *Constant =
128  CGM.CreateRuntimeVariable(ConvertType(IdTy), ConstantName);
129  LValue LV = MakeNaturalAlignAddrLValue(Constant, IdTy);
130  llvm::Value *Ptr = EmitLoadOfScalar(LV, E->getLocStart());
131  cast<llvm::LoadInst>(Ptr)->setMetadata(
132  CGM.getModule().getMDKindID("invariant.load"),
133  llvm::MDNode::get(getLLVMContext(), None));
134  return Builder.CreateBitCast(Ptr, ConvertType(E->getType()));
135  }
136 
137  // Compute the type of the array we're initializing.
138  llvm::APInt APNumElements(Context.getTypeSize(Context.getSizeType()),
139  NumElements);
140  QualType ElementType = Context.getObjCIdType().withConst();
141  QualType ElementArrayType
142  = Context.getConstantArrayType(ElementType, APNumElements,
143  ArrayType::Normal, /*IndexTypeQuals=*/0);
144 
145  // Allocate the temporary array(s).
146  Address Objects = CreateMemTemp(ElementArrayType, "objects");
147  Address Keys = Address::invalid();
148  if (DLE)
149  Keys = CreateMemTemp(ElementArrayType, "keys");
150 
151  // In ARC, we may need to do extra work to keep all the keys and
152  // values alive until after the call.
153  SmallVector<llvm::Value *, 16> NeededObjects;
154  bool TrackNeededObjects =
155  (getLangOpts().ObjCAutoRefCount &&
156  CGM.getCodeGenOpts().OptimizationLevel != 0);
157 
158  // Perform the actual initialialization of the array(s).
159  for (uint64_t i = 0; i < NumElements; i++) {
160  if (ALE) {
161  // Emit the element and store it to the appropriate array slot.
162  const Expr *Rhs = ALE->getElement(i);
163  LValue LV = MakeAddrLValue(
165  ElementType, AlignmentSource::Decl);
166 
167  llvm::Value *value = EmitScalarExpr(Rhs);
168  EmitStoreThroughLValue(RValue::get(value), LV, true);
169  if (TrackNeededObjects) {
170  NeededObjects.push_back(value);
171  }
172  } else {
173  // Emit the key and store it to the appropriate array slot.
174  const Expr *Key = DLE->getKeyValueElement(i).Key;
175  LValue KeyLV = MakeAddrLValue(
177  ElementType, AlignmentSource::Decl);
178  llvm::Value *keyValue = EmitScalarExpr(Key);
179  EmitStoreThroughLValue(RValue::get(keyValue), KeyLV, /*isInit=*/true);
180 
181  // Emit the value and store it to the appropriate array slot.
182  const Expr *Value = DLE->getKeyValueElement(i).Value;
183  LValue ValueLV = MakeAddrLValue(
185  ElementType, AlignmentSource::Decl);
186  llvm::Value *valueValue = EmitScalarExpr(Value);
187  EmitStoreThroughLValue(RValue::get(valueValue), ValueLV, /*isInit=*/true);
188  if (TrackNeededObjects) {
189  NeededObjects.push_back(keyValue);
190  NeededObjects.push_back(valueValue);
191  }
192  }
193  }
194 
195  // Generate the argument list.
196  CallArgList Args;
197  ObjCMethodDecl::param_const_iterator PI = MethodWithObjects->param_begin();
198  const ParmVarDecl *argDecl = *PI++;
199  QualType ArgQT = argDecl->getType().getUnqualifiedType();
200  Args.add(RValue::get(Objects.getPointer()), ArgQT);
201  if (DLE) {
202  argDecl = *PI++;
203  ArgQT = argDecl->getType().getUnqualifiedType();
204  Args.add(RValue::get(Keys.getPointer()), ArgQT);
205  }
206  argDecl = *PI;
207  ArgQT = argDecl->getType().getUnqualifiedType();
208  llvm::Value *Count =
209  llvm::ConstantInt::get(CGM.getTypes().ConvertType(ArgQT), NumElements);
210  Args.add(RValue::get(Count), ArgQT);
211 
212  // Generate a reference to the class pointer, which will be the receiver.
213  Selector Sel = MethodWithObjects->getSelector();
214  QualType ResultType = E->getType();
215  const ObjCObjectPointerType *InterfacePointerType
216  = ResultType->getAsObjCInterfacePointerType();
217  ObjCInterfaceDecl *Class
218  = InterfacePointerType->getObjectType()->getInterface();
219  CGObjCRuntime &Runtime = CGM.getObjCRuntime();
220  llvm::Value *Receiver = Runtime.GetClass(*this, Class);
221 
222  // Generate the message send.
223  RValue result = Runtime.GenerateMessageSend(
224  *this, ReturnValueSlot(), MethodWithObjects->getReturnType(), Sel,
225  Receiver, Args, Class, MethodWithObjects);
226 
227  // The above message send needs these objects, but in ARC they are
228  // passed in a buffer that is essentially __unsafe_unretained.
229  // Therefore we must prevent the optimizer from releasing them until
230  // after the call.
231  if (TrackNeededObjects) {
232  EmitARCIntrinsicUse(NeededObjects);
233  }
234 
235  return Builder.CreateBitCast(result.getScalarVal(),
236  ConvertType(E->getType()));
237 }
238 
241 }
242 
244  const ObjCDictionaryLiteral *E) {
246 }
247 
248 /// Emit a selector.
250  // Untyped selector.
251  // Note that this implementation allows for non-constant strings to be passed
252  // as arguments to @selector(). Currently, the only thing preventing this
253  // behaviour is the type checking in the front end.
254  return CGM.getObjCRuntime().GetSelector(*this, E->getSelector());
255 }
256 
258  // FIXME: This should pass the Decl not the name.
259  return CGM.getObjCRuntime().GenerateProtocolRef(*this, E->getProtocol());
260 }
261 
262 /// \brief Adjust the type of an Objective-C object that doesn't match up due
263 /// to type erasure at various points, e.g., related result types or the use
264 /// of parameterized classes.
266  RValue Result) {
267  if (!ExpT->isObjCRetainableType())
268  return Result;
269 
270  // If the converted types are the same, we're done.
271  llvm::Type *ExpLLVMTy = CGF.ConvertType(ExpT);
272  if (ExpLLVMTy == Result.getScalarVal()->getType())
273  return Result;
274 
275  // We have applied a substitution. Cast the rvalue appropriately.
276  return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
277  ExpLLVMTy));
278 }
279 
280 /// Decide whether to extend the lifetime of the receiver of a
281 /// returns-inner-pointer message.
282 static bool
284  switch (message->getReceiverKind()) {
285 
286  // For a normal instance message, we should extend unless the
287  // receiver is loaded from a variable with precise lifetime.
289  const Expr *receiver = message->getInstanceReceiver();
290 
291  // Look through OVEs.
292  if (auto opaque = dyn_cast<OpaqueValueExpr>(receiver)) {
293  if (opaque->getSourceExpr())
294  receiver = opaque->getSourceExpr()->IgnoreParens();
295  }
296 
297  const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver);
298  if (!ice || ice->getCastKind() != CK_LValueToRValue) return true;
299  receiver = ice->getSubExpr()->IgnoreParens();
300 
301  // Look through OVEs.
302  if (auto opaque = dyn_cast<OpaqueValueExpr>(receiver)) {
303  if (opaque->getSourceExpr())
304  receiver = opaque->getSourceExpr()->IgnoreParens();
305  }
306 
307  // Only __strong variables.
308  if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
309  return true;
310 
311  // All ivars and fields have precise lifetime.
312  if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver))
313  return false;
314 
315  // Otherwise, check for variables.
316  const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr());
317  if (!declRef) return true;
318  const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl());
319  if (!var) return true;
320 
321  // All variables have precise lifetime except local variables with
322  // automatic storage duration that aren't specially marked.
323  return (var->hasLocalStorage() &&
324  !var->hasAttr<ObjCPreciseLifetimeAttr>());
325  }
326 
329  // It's never necessary for class objects.
330  return false;
331 
333  // We generally assume that 'self' lives throughout a method call.
334  return false;
335  }
336 
337  llvm_unreachable("invalid receiver kind");
338 }
339 
340 /// Given an expression of ObjC pointer type, check whether it was
341 /// immediately loaded from an ARC __weak l-value.
342 static const Expr *findWeakLValue(const Expr *E) {
343  assert(E->getType()->isObjCRetainableType());
344  E = E->IgnoreParens();
345  if (auto CE = dyn_cast<CastExpr>(E)) {
346  if (CE->getCastKind() == CK_LValueToRValue) {
347  if (CE->getSubExpr()->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
348  return CE->getSubExpr();
349  }
350  }
351 
352  return nullptr;
353 }
354 
356  ReturnValueSlot Return) {
357  // Only the lookup mechanism and first two arguments of the method
358  // implementation vary between runtimes. We can get the receiver and
359  // arguments in generic code.
360 
361  bool isDelegateInit = E->isDelegateInitCall();
362 
363  const ObjCMethodDecl *method = E->getMethodDecl();
364 
365  // If the method is -retain, and the receiver's being loaded from
366  // a __weak variable, peephole the entire operation to objc_loadWeakRetained.
367  if (method && E->getReceiverKind() == ObjCMessageExpr::Instance &&
368  method->getMethodFamily() == OMF_retain) {
369  if (auto lvalueExpr = findWeakLValue(E->getInstanceReceiver())) {
370  LValue lvalue = EmitLValue(lvalueExpr);
371  llvm::Value *result = EmitARCLoadWeakRetained(lvalue.getAddress());
372  return AdjustObjCObjectType(*this, E->getType(), RValue::get(result));
373  }
374  }
375 
376  // We don't retain the receiver in delegate init calls, and this is
377  // safe because the receiver value is always loaded from 'self',
378  // which we zero out. We don't want to Block_copy block receivers,
379  // though.
380  bool retainSelf =
381  (!isDelegateInit &&
382  CGM.getLangOpts().ObjCAutoRefCount &&
383  method &&
384  method->hasAttr<NSConsumesSelfAttr>());
385 
386  CGObjCRuntime &Runtime = CGM.getObjCRuntime();
387  bool isSuperMessage = false;
388  bool isClassMessage = false;
389  ObjCInterfaceDecl *OID = nullptr;
390  // Find the receiver
391  QualType ReceiverType;
392  llvm::Value *Receiver = nullptr;
393  switch (E->getReceiverKind()) {
395  ReceiverType = E->getInstanceReceiver()->getType();
396  if (retainSelf) {
398  E->getInstanceReceiver());
399  Receiver = ter.getPointer();
400  if (ter.getInt()) retainSelf = false;
401  } else
402  Receiver = EmitScalarExpr(E->getInstanceReceiver());
403  break;
404 
405  case ObjCMessageExpr::Class: {
406  ReceiverType = E->getClassReceiver();
407  const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
408  assert(ObjTy && "Invalid Objective-C class message send");
409  OID = ObjTy->getInterface();
410  assert(OID && "Invalid Objective-C class message send");
411  Receiver = Runtime.GetClass(*this, OID);
412  isClassMessage = true;
413  break;
414  }
415 
417  ReceiverType = E->getSuperType();
418  Receiver = LoadObjCSelf();
419  isSuperMessage = true;
420  break;
421 
423  ReceiverType = E->getSuperType();
424  Receiver = LoadObjCSelf();
425  isSuperMessage = true;
426  isClassMessage = true;
427  break;
428  }
429 
430  if (retainSelf)
431  Receiver = EmitARCRetainNonBlock(Receiver);
432 
433  // In ARC, we sometimes want to "extend the lifetime"
434  // (i.e. retain+autorelease) of receivers of returns-inner-pointer
435  // messages.
436  if (getLangOpts().ObjCAutoRefCount && method &&
437  method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
439  Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
440 
441  QualType ResultType = method ? method->getReturnType() : E->getType();
442 
443  CallArgList Args;
444  EmitCallArgs(Args, method, E->arguments(), /*AC*/AbstractCallee(method));
445 
446  // For delegate init calls in ARC, do an unsafe store of null into
447  // self. This represents the call taking direct ownership of that
448  // value. We have to do this after emitting the other call
449  // arguments because they might also reference self, but we don't
450  // have to worry about any of them modifying self because that would
451  // be an undefined read and write of an object in unordered
452  // expressions.
453  if (isDelegateInit) {
454  assert(getLangOpts().ObjCAutoRefCount &&
455  "delegate init calls should only be marked in ARC");
456 
457  // Do an unsafe store of null into self.
458  Address selfAddr =
459  GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
460  Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
461  }
462 
463  RValue result;
464  if (isSuperMessage) {
465  // super is only valid in an Objective-C method
466  const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
467  bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
468  result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
469  E->getSelector(),
470  OMD->getClassInterface(),
471  isCategoryImpl,
472  Receiver,
473  isClassMessage,
474  Args,
475  method);
476  } else {
477  result = Runtime.GenerateMessageSend(*this, Return, ResultType,
478  E->getSelector(),
479  Receiver, Args, OID,
480  method);
481  }
482 
483  // For delegate init calls in ARC, implicitly store the result of
484  // the call back into self. This takes ownership of the value.
485  if (isDelegateInit) {
486  Address selfAddr =
487  GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
488  llvm::Value *newSelf = result.getScalarVal();
489 
490  // The delegate return type isn't necessarily a matching type; in
491  // fact, it's quite likely to be 'id'.
492  llvm::Type *selfTy = selfAddr.getElementType();
493  newSelf = Builder.CreateBitCast(newSelf, selfTy);
494 
495  Builder.CreateStore(newSelf, selfAddr);
496  }
497 
498  return AdjustObjCObjectType(*this, E->getType(), result);
499 }
500 
501 namespace {
502 struct FinishARCDealloc final : EHScopeStack::Cleanup {
503  void Emit(CodeGenFunction &CGF, Flags flags) override {
504  const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
505 
506  const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
507  const ObjCInterfaceDecl *iface = impl->getClassInterface();
508  if (!iface->getSuperClass()) return;
509 
510  bool isCategory = isa<ObjCCategoryImplDecl>(impl);
511 
512  // Call [super dealloc] if we have a superclass.
513  llvm::Value *self = CGF.LoadObjCSelf();
514 
515  CallArgList args;
517  CGF.getContext().VoidTy,
518  method->getSelector(),
519  iface,
520  isCategory,
521  self,
522  /*is class msg*/ false,
523  args,
524  method);
525  }
526 };
527 }
528 
529 /// StartObjCMethod - Begin emission of an ObjCMethod. This generates
530 /// the LLVM function and sets the other context used by
531 /// CodeGenFunction.
533  const ObjCContainerDecl *CD) {
534  SourceLocation StartLoc = OMD->getLocStart();
535  FunctionArgList args;
536  // Check if we should generate debug info for this method.
537  if (OMD->hasAttr<NoDebugAttr>())
538  DebugInfo = nullptr; // disable debug info indefinitely for this function
539 
540  llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
541 
543  CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
544 
545  args.push_back(OMD->getSelfDecl());
546  args.push_back(OMD->getCmdDecl());
547 
548  args.append(OMD->param_begin(), OMD->param_end());
549 
550  CurGD = OMD;
551  CurEHLocation = OMD->getLocEnd();
552 
553  StartFunction(OMD, OMD->getReturnType(), Fn, FI, args,
554  OMD->getLocation(), StartLoc);
555 
556  // In ARC, certain methods get an extra cleanup.
557  if (CGM.getLangOpts().ObjCAutoRefCount &&
558  OMD->isInstanceMethod() &&
559  OMD->getSelector().isUnarySelector()) {
560  const IdentifierInfo *ident =
562  if (ident->isStr("dealloc"))
563  EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
564  }
565 }
566 
568  LValue lvalue, QualType type);
569 
570 /// Generate an Objective-C method. An Objective-C method is a C function with
571 /// its pointer, name, and types registered in the class struture.
573  StartObjCMethod(OMD, OMD->getClassInterface());
574  PGO.assignRegionCounters(GlobalDecl(OMD), CurFn);
575  assert(isa<CompoundStmt>(OMD->getBody()));
577  EmitCompoundStmtWithoutScope(*cast<CompoundStmt>(OMD->getBody()));
579 }
580 
581 /// emitStructGetterCall - Call the runtime function to load a property
582 /// into the return value slot.
584  bool isAtomic, bool hasStrong) {
585  ASTContext &Context = CGF.getContext();
586 
587  Address src =
588  CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
589  .getAddress();
590 
591  // objc_copyStruct (ReturnValue, &structIvar,
592  // sizeof (Type of Ivar), isAtomic, false);
593  CallArgList args;
594 
595  Address dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
596  args.add(RValue::get(dest.getPointer()), Context.VoidPtrTy);
597 
598  src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
599  args.add(RValue::get(src.getPointer()), Context.VoidPtrTy);
600 
601  CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
602  args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
603  args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
604  args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
605 
606  llvm::Constant *fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
607  CGCallee callee = CGCallee::forDirect(fn);
608  CGF.EmitCall(CGF.getTypes().arrangeBuiltinFunctionCall(Context.VoidTy, args),
609  callee, ReturnValueSlot(), args);
610 }
611 
612 /// Determine whether the given architecture supports unaligned atomic
613 /// accesses. They don't have to be fast, just faster than a function
614 /// call and a mutex.
615 static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
616  // FIXME: Allow unaligned atomic load/store on x86. (It is not
617  // currently supported by the backend.)
618  return 0;
619 }
620 
621 /// Return the maximum size that permits atomic accesses for the given
622 /// architecture.
624  llvm::Triple::ArchType arch) {
625  // ARM has 8-byte atomic accesses, but it's not clear whether we
626  // want to rely on them here.
627 
628  // In the default case, just assume that any size up to a pointer is
629  // fine given adequate alignment.
631 }
632 
633 namespace {
634  class PropertyImplStrategy {
635  public:
636  enum StrategyKind {
637  /// The 'native' strategy is to use the architecture's provided
638  /// reads and writes.
639  Native,
640 
641  /// Use objc_setProperty and objc_getProperty.
642  GetSetProperty,
643 
644  /// Use objc_setProperty for the setter, but use expression
645  /// evaluation for the getter.
646  SetPropertyAndExpressionGet,
647 
648  /// Use objc_copyStruct.
649  CopyStruct,
650 
651  /// The 'expression' strategy is to emit normal assignment or
652  /// lvalue-to-rvalue expressions.
653  Expression
654  };
655 
656  StrategyKind getKind() const { return StrategyKind(Kind); }
657 
658  bool hasStrongMember() const { return HasStrong; }
659  bool isAtomic() const { return IsAtomic; }
660  bool isCopy() const { return IsCopy; }
661 
662  CharUnits getIvarSize() const { return IvarSize; }
663  CharUnits getIvarAlignment() const { return IvarAlignment; }
664 
665  PropertyImplStrategy(CodeGenModule &CGM,
666  const ObjCPropertyImplDecl *propImpl);
667 
668  private:
669  unsigned Kind : 8;
670  unsigned IsAtomic : 1;
671  unsigned IsCopy : 1;
672  unsigned HasStrong : 1;
673 
674  CharUnits IvarSize;
675  CharUnits IvarAlignment;
676  };
677 }
678 
679 /// Pick an implementation strategy for the given property synthesis.
680 PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
681  const ObjCPropertyImplDecl *propImpl) {
682  const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
683  ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
684 
685  IsCopy = (setterKind == ObjCPropertyDecl::Copy);
686  IsAtomic = prop->isAtomic();
687  HasStrong = false; // doesn't matter here.
688 
689  // Evaluate the ivar's size and alignment.
690  ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
691  QualType ivarType = ivar->getType();
692  std::tie(IvarSize, IvarAlignment) =
693  CGM.getContext().getTypeInfoInChars(ivarType);
694 
695  // If we have a copy property, we always have to use getProperty/setProperty.
696  // TODO: we could actually use setProperty and an expression for non-atomics.
697  if (IsCopy) {
698  Kind = GetSetProperty;
699  return;
700  }
701 
702  // Handle retain.
703  if (setterKind == ObjCPropertyDecl::Retain) {
704  // In GC-only, there's nothing special that needs to be done.
705  if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
706  // fallthrough
707 
708  // In ARC, if the property is non-atomic, use expression emission,
709  // which translates to objc_storeStrong. This isn't required, but
710  // it's slightly nicer.
711  } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) {
712  // Using standard expression emission for the setter is only
713  // acceptable if the ivar is __strong, which won't be true if
714  // the property is annotated with __attribute__((NSObject)).
715  // TODO: falling all the way back to objc_setProperty here is
716  // just laziness, though; we could still use objc_storeStrong
717  // if we hacked it right.
718  if (ivarType.getObjCLifetime() == Qualifiers::OCL_Strong)
719  Kind = Expression;
720  else
721  Kind = SetPropertyAndExpressionGet;
722  return;
723 
724  // Otherwise, we need to at least use setProperty. However, if
725  // the property isn't atomic, we can use normal expression
726  // emission for the getter.
727  } else if (!IsAtomic) {
728  Kind = SetPropertyAndExpressionGet;
729  return;
730 
731  // Otherwise, we have to use both setProperty and getProperty.
732  } else {
733  Kind = GetSetProperty;
734  return;
735  }
736  }
737 
738  // If we're not atomic, just use expression accesses.
739  if (!IsAtomic) {
740  Kind = Expression;
741  return;
742  }
743 
744  // Properties on bitfield ivars need to be emitted using expression
745  // accesses even if they're nominally atomic.
746  if (ivar->isBitField()) {
747  Kind = Expression;
748  return;
749  }
750 
751  // GC-qualified or ARC-qualified ivars need to be emitted as
752  // expressions. This actually works out to being atomic anyway,
753  // except for ARC __strong, but that should trigger the above code.
754  if (ivarType.hasNonTrivialObjCLifetime() ||
755  (CGM.getLangOpts().getGC() &&
756  CGM.getContext().getObjCGCAttrKind(ivarType))) {
757  Kind = Expression;
758  return;
759  }
760 
761  // Compute whether the ivar has strong members.
762  if (CGM.getLangOpts().getGC())
763  if (const RecordType *recordType = ivarType->getAs<RecordType>())
764  HasStrong = recordType->getDecl()->hasObjectMember();
765 
766  // We can never access structs with object members with a native
767  // access, because we need to use write barriers. This is what
768  // objc_copyStruct is for.
769  if (HasStrong) {
770  Kind = CopyStruct;
771  return;
772  }
773 
774  // Otherwise, this is target-dependent and based on the size and
775  // alignment of the ivar.
776 
777  // If the size of the ivar is not a power of two, give up. We don't
778  // want to get into the business of doing compare-and-swaps.
779  if (!IvarSize.isPowerOfTwo()) {
780  Kind = CopyStruct;
781  return;
782  }
783 
784  llvm::Triple::ArchType arch =
785  CGM.getTarget().getTriple().getArch();
786 
787  // Most architectures require memory to fit within a single cache
788  // line, so the alignment has to be at least the size of the access.
789  // Otherwise we have to grab a lock.
790  if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
791  Kind = CopyStruct;
792  return;
793  }
794 
795  // If the ivar's size exceeds the architecture's maximum atomic
796  // access size, we have to use CopyStruct.
797  if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
798  Kind = CopyStruct;
799  return;
800  }
801 
802  // Otherwise, we can use native loads and stores.
803  Kind = Native;
804 }
805 
806 /// \brief Generate an Objective-C property getter function.
807 ///
808 /// The given Decl must be an ObjCImplementationDecl. \@synthesize
809 /// is illegal within a category.
811  const ObjCPropertyImplDecl *PID) {
812  llvm::Constant *AtomicHelperFn =
814  const ObjCPropertyDecl *PD = PID->getPropertyDecl();
815  ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
816  assert(OMD && "Invalid call to generate getter (empty method)");
817  StartObjCMethod(OMD, IMP->getClassInterface());
818 
819  generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn);
820 
821  FinishFunction();
822 }
823 
824 static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
825  const Expr *getter = propImpl->getGetterCXXConstructor();
826  if (!getter) return true;
827 
828  // Sema only makes only of these when the ivar has a C++ class type,
829  // so the form is pretty constrained.
830 
831  // If the property has a reference type, we might just be binding a
832  // reference, in which case the result will be a gl-value. We should
833  // treat this as a non-trivial operation.
834  if (getter->isGLValue())
835  return false;
836 
837  // If we selected a trivial copy-constructor, we're okay.
838  if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
839  return (construct->getConstructor()->isTrivial());
840 
841  // The constructor might require cleanups (in which case it's never
842  // trivial).
843  assert(isa<ExprWithCleanups>(getter));
844  return false;
845 }
846 
847 /// emitCPPObjectAtomicGetterCall - Call the runtime function to
848 /// copy the ivar into the resturn slot.
850  llvm::Value *returnAddr,
851  ObjCIvarDecl *ivar,
852  llvm::Constant *AtomicHelperFn) {
853  // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
854  // AtomicHelperFn);
855  CallArgList args;
856 
857  // The 1st argument is the return Slot.
858  args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
859 
860  // The 2nd argument is the address of the ivar.
861  llvm::Value *ivarAddr =
863  CGF.LoadObjCSelf(), ivar, 0).getPointer();
864  ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
865  args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
866 
867  // Third argument is the helper function.
868  args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
869 
870  llvm::Constant *copyCppAtomicObjectFn =
872  CGCallee callee = CGCallee::forDirect(copyCppAtomicObjectFn);
873  CGF.EmitCall(
875  callee, ReturnValueSlot(), args);
876 }
877 
878 void
880  const ObjCPropertyImplDecl *propImpl,
881  const ObjCMethodDecl *GetterMethodDecl,
882  llvm::Constant *AtomicHelperFn) {
883  // If there's a non-trivial 'get' expression, we just have to emit that.
884  if (!hasTrivialGetExpr(propImpl)) {
885  if (!AtomicHelperFn) {
887  /*nrvo*/ nullptr);
888  EmitReturnStmt(ret);
889  }
890  else {
891  ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
893  ivar, AtomicHelperFn);
894  }
895  return;
896  }
897 
898  const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
899  QualType propType = prop->getType();
900  ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl();
901 
902  ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
903 
904  // Pick an implementation strategy.
905  PropertyImplStrategy strategy(CGM, propImpl);
906  switch (strategy.getKind()) {
907  case PropertyImplStrategy::Native: {
908  // We don't need to do anything for a zero-size struct.
909  if (strategy.getIvarSize().isZero())
910  return;
911 
913 
914  // Currently, all atomic accesses have to be through integer
915  // types, so there's no point in trying to pick a prettier type.
916  uint64_t ivarSize = getContext().toBits(strategy.getIvarSize());
917  llvm::Type *bitcastType = llvm::Type::getIntNTy(getLLVMContext(), ivarSize);
918  bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
919 
920  // Perform an atomic load. This does not impose ordering constraints.
921  Address ivarAddr = LV.getAddress();
922  ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
923  llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
924  load->setAtomic(llvm::AtomicOrdering::Unordered);
925 
926  // Store that value into the return address. Doing this with a
927  // bitcast is likely to produce some pretty ugly IR, but it's not
928  // the *most* terrible thing in the world.
929  llvm::Type *retTy = ConvertType(getterMethod->getReturnType());
930  uint64_t retTySize = CGM.getDataLayout().getTypeSizeInBits(retTy);
931  llvm::Value *ivarVal = load;
932  if (ivarSize > retTySize) {
933  llvm::Type *newTy = llvm::Type::getIntNTy(getLLVMContext(), retTySize);
934  ivarVal = Builder.CreateTrunc(load, newTy);
935  bitcastType = newTy->getPointerTo();
936  }
937  Builder.CreateStore(ivarVal,
938  Builder.CreateBitCast(ReturnValue, bitcastType));
939 
940  // Make sure we don't do an autorelease.
941  AutoreleaseResult = false;
942  return;
943  }
944 
945  case PropertyImplStrategy::GetSetProperty: {
946  llvm::Constant *getPropertyFn =
948  if (!getPropertyFn) {
949  CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
950  return;
951  }
952  CGCallee callee = CGCallee::forDirect(getPropertyFn);
953 
954  // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
955  // FIXME: Can't this be simpler? This might even be worse than the
956  // corresponding gcc code.
957  llvm::Value *cmd =
958  Builder.CreateLoad(GetAddrOfLocalVar(getterMethod->getCmdDecl()), "cmd");
960  llvm::Value *ivarOffset =
961  EmitIvarOffset(classImpl->getClassInterface(), ivar);
962 
963  CallArgList args;
964  args.add(RValue::get(self), getContext().getObjCIdType());
965  args.add(RValue::get(cmd), getContext().getObjCSelType());
966  args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
967  args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
968  getContext().BoolTy);
969 
970  // FIXME: We shouldn't need to get the function info here, the
971  // runtime already should have computed it to build the function.
972  llvm::Instruction *CallInstruction;
973  RValue RV = EmitCall(
974  getTypes().arrangeBuiltinFunctionCall(propType, args),
975  callee, ReturnValueSlot(), args, &CallInstruction);
976  if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(CallInstruction))
977  call->setTailCall();
978 
979  // We need to fix the type here. Ivars with copy & retain are
980  // always objects so we don't need to worry about complex or
981  // aggregates.
983  RV.getScalarVal(),
984  getTypes().ConvertType(getterMethod->getReturnType())));
985 
986  EmitReturnOfRValue(RV, propType);
987 
988  // objc_getProperty does an autorelease, so we should suppress ours.
989  AutoreleaseResult = false;
990 
991  return;
992  }
993 
994  case PropertyImplStrategy::CopyStruct:
995  emitStructGetterCall(*this, ivar, strategy.isAtomic(),
996  strategy.hasStrongMember());
997  return;
998 
999  case PropertyImplStrategy::Expression:
1000  case PropertyImplStrategy::SetPropertyAndExpressionGet: {
1002 
1003  QualType ivarType = ivar->getType();
1004  switch (getEvaluationKind(ivarType)) {
1005  case TEK_Complex: {
1008  /*init*/ true);
1009  return;
1010  }
1011  case TEK_Aggregate: {
1012  // The return value slot is guaranteed to not be aliased, but
1013  // that's not necessarily the same as "on the stack", so
1014  // we still potentially need objc_memmove_collectable.
1015  EmitAggregateCopy(/* Dest= */ MakeAddrLValue(ReturnValue, ivarType),
1016  /* Src= */ LV, ivarType);
1017  return; }
1018  case TEK_Scalar: {
1019  llvm::Value *value;
1020  if (propType->isReferenceType()) {
1021  value = LV.getAddress().getPointer();
1022  } else {
1023  // We want to load and autoreleaseReturnValue ARC __weak ivars.
1025  if (getLangOpts().ObjCAutoRefCount) {
1026  value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
1027  } else {
1028  value = EmitARCLoadWeak(LV.getAddress());
1029  }
1030 
1031  // Otherwise we want to do a simple load, suppressing the
1032  // final autorelease.
1033  } else {
1034  value = EmitLoadOfLValue(LV, SourceLocation()).getScalarVal();
1035  AutoreleaseResult = false;
1036  }
1037 
1038  value = Builder.CreateBitCast(
1039  value, ConvertType(GetterMethodDecl->getReturnType()));
1040  }
1041 
1042  EmitReturnOfRValue(RValue::get(value), propType);
1043  return;
1044  }
1045  }
1046  llvm_unreachable("bad evaluation kind");
1047  }
1048 
1049  }
1050  llvm_unreachable("bad @property implementation strategy!");
1051 }
1052 
1053 /// emitStructSetterCall - Call the runtime function to store the value
1054 /// from the first formal parameter into the given ivar.
1056  ObjCIvarDecl *ivar) {
1057  // objc_copyStruct (&structIvar, &Arg,
1058  // sizeof (struct something), true, false);
1059  CallArgList args;
1060 
1061  // The first argument is the address of the ivar.
1062  llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
1063  CGF.LoadObjCSelf(), ivar, 0)
1064  .getPointer();
1065  ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1066  args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
1067 
1068  // The second argument is the address of the parameter variable.
1069  ParmVarDecl *argVar = *OMD->param_begin();
1070  DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
1072  llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer();
1073  argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1074  args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
1075 
1076  // The third argument is the sizeof the type.
1077  llvm::Value *size =
1078  CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
1079  args.add(RValue::get(size), CGF.getContext().getSizeType());
1080 
1081  // The fourth argument is the 'isAtomic' flag.
1082  args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
1083 
1084  // The fifth argument is the 'hasStrong' flag.
1085  // FIXME: should this really always be false?
1086  args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
1087 
1088  llvm::Constant *fn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
1089  CGCallee callee = CGCallee::forDirect(fn);
1090  CGF.EmitCall(
1092  callee, ReturnValueSlot(), args);
1093 }
1094 
1095 /// emitCPPObjectAtomicSetterCall - Call the runtime function to store
1096 /// the value from the first formal parameter into the given ivar, using
1097 /// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
1099  ObjCMethodDecl *OMD,
1100  ObjCIvarDecl *ivar,
1101  llvm::Constant *AtomicHelperFn) {
1102  // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
1103  // AtomicHelperFn);
1104  CallArgList args;
1105 
1106  // The first argument is the address of the ivar.
1107  llvm::Value *ivarAddr =
1109  CGF.LoadObjCSelf(), ivar, 0).getPointer();
1110  ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1111  args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
1112 
1113  // The second argument is the address of the parameter variable.
1114  ParmVarDecl *argVar = *OMD->param_begin();
1115  DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
1117  llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer();
1118  argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1119  args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
1120 
1121  // Third argument is the helper function.
1122  args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
1123 
1124  llvm::Constant *fn =
1126  CGCallee callee = CGCallee::forDirect(fn);
1127  CGF.EmitCall(
1129  callee, ReturnValueSlot(), args);
1130 }
1131 
1132 
1133 static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1134  Expr *setter = PID->getSetterCXXAssignment();
1135  if (!setter) return true;
1136 
1137  // Sema only makes only of these when the ivar has a C++ class type,
1138  // so the form is pretty constrained.
1139 
1140  // An operator call is trivial if the function it calls is trivial.
1141  // This also implies that there's nothing non-trivial going on with
1142  // the arguments, because operator= can only be trivial if it's a
1143  // synthesized assignment operator and therefore both parameters are
1144  // references.
1145  if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
1146  if (const FunctionDecl *callee
1147  = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1148  if (callee->isTrivial())
1149  return true;
1150  return false;
1151  }
1152 
1153  assert(isa<ExprWithCleanups>(setter));
1154  return false;
1155 }
1156 
1158  if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
1159  return false;
1161 }
1162 
1163 void
1165  const ObjCPropertyImplDecl *propImpl,
1166  llvm::Constant *AtomicHelperFn) {
1167  const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
1168  ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
1169  ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
1170 
1171  // Just use the setter expression if Sema gave us one and it's
1172  // non-trivial.
1173  if (!hasTrivialSetExpr(propImpl)) {
1174  if (!AtomicHelperFn)
1175  // If non-atomic, assignment is called directly.
1176  EmitStmt(propImpl->getSetterCXXAssignment());
1177  else
1178  // If atomic, assignment is called via a locking api.
1179  emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
1180  AtomicHelperFn);
1181  return;
1182  }
1183 
1184  PropertyImplStrategy strategy(CGM, propImpl);
1185  switch (strategy.getKind()) {
1186  case PropertyImplStrategy::Native: {
1187  // We don't need to do anything for a zero-size struct.
1188  if (strategy.getIvarSize().isZero())
1189  return;
1190 
1191  Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
1192 
1193  LValue ivarLValue =
1194  EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
1195  Address ivarAddr = ivarLValue.getAddress();
1196 
1197  // Currently, all atomic accesses have to be through integer
1198  // types, so there's no point in trying to pick a prettier type.
1199  llvm::Type *bitcastType =
1200  llvm::Type::getIntNTy(getLLVMContext(),
1201  getContext().toBits(strategy.getIvarSize()));
1202 
1203  // Cast both arguments to the chosen operation type.
1204  argAddr = Builder.CreateElementBitCast(argAddr, bitcastType);
1205  ivarAddr = Builder.CreateElementBitCast(ivarAddr, bitcastType);
1206 
1207  // This bitcast load is likely to cause some nasty IR.
1208  llvm::Value *load = Builder.CreateLoad(argAddr);
1209 
1210  // Perform an atomic store. There are no memory ordering requirements.
1211  llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
1212  store->setAtomic(llvm::AtomicOrdering::Unordered);
1213  return;
1214  }
1215 
1216  case PropertyImplStrategy::GetSetProperty:
1217  case PropertyImplStrategy::SetPropertyAndExpressionGet: {
1218 
1219  llvm::Constant *setOptimizedPropertyFn = nullptr;
1220  llvm::Constant *setPropertyFn = nullptr;
1221  if (UseOptimizedSetter(CGM)) {
1222  // 10.8 and iOS 6.0 code and GC is off
1223  setOptimizedPropertyFn =
1224  CGM.getObjCRuntime()
1225  .GetOptimizedPropertySetFunction(strategy.isAtomic(),
1226  strategy.isCopy());
1227  if (!setOptimizedPropertyFn) {
1228  CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1229  return;
1230  }
1231  }
1232  else {
1233  setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1234  if (!setPropertyFn) {
1235  CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1236  return;
1237  }
1238  }
1239 
1240  // Emit objc_setProperty((id) self, _cmd, offset, arg,
1241  // <is-atomic>, <is-copy>).
1242  llvm::Value *cmd =
1243  Builder.CreateLoad(GetAddrOfLocalVar(setterMethod->getCmdDecl()));
1244  llvm::Value *self =
1246  llvm::Value *ivarOffset =
1247  EmitIvarOffset(classImpl->getClassInterface(), ivar);
1248  Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
1249  llvm::Value *arg = Builder.CreateLoad(argAddr, "arg");
1250  arg = Builder.CreateBitCast(arg, VoidPtrTy);
1251 
1252  CallArgList args;
1253  args.add(RValue::get(self), getContext().getObjCIdType());
1254  args.add(RValue::get(cmd), getContext().getObjCSelType());
1255  if (setOptimizedPropertyFn) {
1256  args.add(RValue::get(arg), getContext().getObjCIdType());
1257  args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1258  CGCallee callee = CGCallee::forDirect(setOptimizedPropertyFn);
1259  EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
1260  callee, ReturnValueSlot(), args);
1261  } else {
1262  args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1263  args.add(RValue::get(arg), getContext().getObjCIdType());
1264  args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1265  getContext().BoolTy);
1266  args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1267  getContext().BoolTy);
1268  // FIXME: We shouldn't need to get the function info here, the runtime
1269  // already should have computed it to build the function.
1270  CGCallee callee = CGCallee::forDirect(setPropertyFn);
1271  EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
1272  callee, ReturnValueSlot(), args);
1273  }
1274 
1275  return;
1276  }
1277 
1278  case PropertyImplStrategy::CopyStruct:
1279  emitStructSetterCall(*this, setterMethod, ivar);
1280  return;
1281 
1282  case PropertyImplStrategy::Expression:
1283  break;
1284  }
1285 
1286  // Otherwise, fake up some ASTs and emit a normal assignment.
1287  ValueDecl *selfDecl = setterMethod->getSelfDecl();
1288  DeclRefExpr self(selfDecl, false, selfDecl->getType(),
1291  selfDecl->getType(), CK_LValueToRValue, &self,
1292  VK_RValue);
1293  ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
1295  &selfLoad, true, true);
1296 
1297  ParmVarDecl *argDecl = *setterMethod->param_begin();
1298  QualType argType = argDecl->getType().getNonReferenceType();
1299  DeclRefExpr arg(argDecl, false, argType, VK_LValue, SourceLocation());
1301  argType.getUnqualifiedType(), CK_LValueToRValue,
1302  &arg, VK_RValue);
1303 
1304  // The property type can differ from the ivar type in some situations with
1305  // Objective-C pointer types, we can always bit cast the RHS in these cases.
1306  // The following absurdity is just to ensure well-formed IR.
1307  CastKind argCK = CK_NoOp;
1308  if (ivarRef.getType()->isObjCObjectPointerType()) {
1309  if (argLoad.getType()->isObjCObjectPointerType())
1310  argCK = CK_BitCast;
1311  else if (argLoad.getType()->isBlockPointerType())
1312  argCK = CK_BlockPointerToObjCPointerCast;
1313  else
1314  argCK = CK_CPointerToObjCPointerCast;
1315  } else if (ivarRef.getType()->isBlockPointerType()) {
1316  if (argLoad.getType()->isBlockPointerType())
1317  argCK = CK_BitCast;
1318  else
1319  argCK = CK_AnyPointerToBlockPointerCast;
1320  } else if (ivarRef.getType()->isPointerType()) {
1321  argCK = CK_BitCast;
1322  }
1324  ivarRef.getType(), argCK, &argLoad,
1325  VK_RValue);
1326  Expr *finalArg = &argLoad;
1327  if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1328  argLoad.getType()))
1329  finalArg = &argCast;
1330 
1331 
1332  BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
1333  ivarRef.getType(), VK_RValue, OK_Ordinary,
1334  SourceLocation(), FPOptions());
1335  EmitStmt(&assign);
1336 }
1337 
1338 /// \brief Generate an Objective-C property setter function.
1339 ///
1340 /// The given Decl must be an ObjCImplementationDecl. \@synthesize
1341 /// is illegal within a category.
1343  const ObjCPropertyImplDecl *PID) {
1344  llvm::Constant *AtomicHelperFn =
1346  const ObjCPropertyDecl *PD = PID->getPropertyDecl();
1347  ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
1348  assert(OMD && "Invalid call to generate setter (empty method)");
1349  StartObjCMethod(OMD, IMP->getClassInterface());
1350 
1351  generateObjCSetterBody(IMP, PID, AtomicHelperFn);
1352 
1353  FinishFunction();
1354 }
1355 
1356 namespace {
1357  struct DestroyIvar final : EHScopeStack::Cleanup {
1358  private:
1359  llvm::Value *addr;
1360  const ObjCIvarDecl *ivar;
1361  CodeGenFunction::Destroyer *destroyer;
1362  bool useEHCleanupForArray;
1363  public:
1364  DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1365  CodeGenFunction::Destroyer *destroyer,
1366  bool useEHCleanupForArray)
1367  : addr(addr), ivar(ivar), destroyer(destroyer),
1368  useEHCleanupForArray(useEHCleanupForArray) {}
1369 
1370  void Emit(CodeGenFunction &CGF, Flags flags) override {
1371  LValue lvalue
1372  = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1373  CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
1374  flags.isForNormalCleanup() && useEHCleanupForArray);
1375  }
1376  };
1377 }
1378 
1379 /// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1381  Address addr,
1382  QualType type) {
1383  llvm::Value *null = getNullForVariable(addr);
1384  CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1385 }
1386 
1388  ObjCImplementationDecl *impl) {
1390 
1391  llvm::Value *self = CGF.LoadObjCSelf();
1392 
1393  const ObjCInterfaceDecl *iface = impl->getClassInterface();
1394  for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
1395  ivar; ivar = ivar->getNextIvar()) {
1396  QualType type = ivar->getType();
1397 
1398  // Check whether the ivar is a destructible type.
1399  QualType::DestructionKind dtorKind = type.isDestructedType();
1400  if (!dtorKind) continue;
1401 
1402  CodeGenFunction::Destroyer *destroyer = nullptr;
1403 
1404  // Use a call to objc_storeStrong to destroy strong ivars, for the
1405  // general benefit of the tools.
1406  if (dtorKind == QualType::DK_objc_strong_lifetime) {
1407  destroyer = destroyARCStrongWithStore;
1408 
1409  // Otherwise use the default for the destruction kind.
1410  } else {
1411  destroyer = CGF.getDestroyer(dtorKind);
1412  }
1413 
1414  CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1415 
1416  CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1417  cleanupKind & EHCleanup);
1418  }
1419 
1420  assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1421 }
1422 
1424  ObjCMethodDecl *MD,
1425  bool ctor) {
1427  StartObjCMethod(MD, IMP->getClassInterface());
1428 
1429  // Emit .cxx_construct.
1430  if (ctor) {
1431  // Suppress the final autorelease in ARC.
1432  AutoreleaseResult = false;
1433 
1434  for (const auto *IvarInit : IMP->inits()) {
1435  FieldDecl *Field = IvarInit->getAnyMember();
1436  ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
1438  LoadObjCSelf(), Ivar, 0);
1439  EmitAggExpr(IvarInit->getInit(),
1443  }
1444  // constructor returns 'self'.
1445  CodeGenTypes &Types = CGM.getTypes();
1446  QualType IdTy(CGM.getContext().getObjCIdType());
1447  llvm::Value *SelfAsId =
1448  Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1449  EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
1450 
1451  // Emit .cxx_destruct.
1452  } else {
1453  emitCXXDestructMethod(*this, IMP);
1454  }
1455  FinishFunction();
1456 }
1457 
1459  VarDecl *Self = cast<ObjCMethodDecl>(CurFuncDecl)->getSelfDecl();
1460  DeclRefExpr DRE(Self, /*is enclosing local*/ (CurFuncDecl != CurCodeDecl),
1461  Self->getType(), VK_LValue, SourceLocation());
1463 }
1464 
1466  const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1467  ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
1468  const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1469  getContext().getCanonicalType(selfDecl->getType()));
1470  return PTy->getPointeeType();
1471 }
1472 
1474  llvm::Constant *EnumerationMutationFnPtr =
1476  if (!EnumerationMutationFnPtr) {
1477  CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1478  return;
1479  }
1480  CGCallee EnumerationMutationFn =
1481  CGCallee::forDirect(EnumerationMutationFnPtr);
1482 
1483  CGDebugInfo *DI = getDebugInfo();
1484  if (DI)
1486 
1487  RunCleanupsScope ForScope(*this);
1488 
1489  // The local variable comes into scope immediately.
1491  if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1492  variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1493 
1494  JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
1495 
1496  // Fast enumeration state.
1497  QualType StateTy = CGM.getObjCFastEnumerationStateType();
1498  Address StatePtr = CreateMemTemp(StateTy, "state.ptr");
1499  EmitNullInitialization(StatePtr, StateTy);
1500 
1501  // Number of elements in the items array.
1502  static const unsigned NumItems = 16;
1503 
1504  // Fetch the countByEnumeratingWithState:objects:count: selector.
1505  IdentifierInfo *II[] = {
1506  &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1507  &CGM.getContext().Idents.get("objects"),
1508  &CGM.getContext().Idents.get("count")
1509  };
1510  Selector FastEnumSel =
1511  CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
1512 
1513  QualType ItemsTy =
1514  getContext().getConstantArrayType(getContext().getObjCIdType(),
1515  llvm::APInt(32, NumItems),
1516  ArrayType::Normal, 0);
1517  Address ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
1518 
1519  // Emit the collection pointer. In ARC, we do a retain.
1520  llvm::Value *Collection;
1521  if (getLangOpts().ObjCAutoRefCount) {
1522  Collection = EmitARCRetainScalarExpr(S.getCollection());
1523 
1524  // Enter a cleanup to do the release.
1525  EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1526  } else {
1527  Collection = EmitScalarExpr(S.getCollection());
1528  }
1529 
1530  // The 'continue' label needs to appear within the cleanup for the
1531  // collection object.
1532  JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1533 
1534  // Send it our message:
1535  CallArgList Args;
1536 
1537  // The first argument is a temporary of the enumeration-state type.
1538  Args.add(RValue::get(StatePtr.getPointer()),
1539  getContext().getPointerType(StateTy));
1540 
1541  // The second argument is a temporary array with space for NumItems
1542  // pointers. We'll actually be loading elements from the array
1543  // pointer written into the control state; this buffer is so that
1544  // collections that *aren't* backed by arrays can still queue up
1545  // batches of elements.
1546  Args.add(RValue::get(ItemsPtr.getPointer()),
1547  getContext().getPointerType(ItemsTy));
1548 
1549  // The third argument is the capacity of that temporary array.
1550  llvm::Type *NSUIntegerTy = ConvertType(getContext().getNSUIntegerType());
1551  llvm::Constant *Count = llvm::ConstantInt::get(NSUIntegerTy, NumItems);
1552  Args.add(RValue::get(Count), getContext().getNSUIntegerType());
1553 
1554  // Start the enumeration.
1555  RValue CountRV =
1557  getContext().getNSUIntegerType(),
1558  FastEnumSel, Collection, Args);
1559 
1560  // The initial number of objects that were returned in the buffer.
1561  llvm::Value *initialBufferLimit = CountRV.getScalarVal();
1562 
1563  llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1564  llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
1565 
1566  llvm::Value *zero = llvm::Constant::getNullValue(NSUIntegerTy);
1567 
1568  // If the limit pointer was zero to begin with, the collection is
1569  // empty; skip all this. Set the branch weight assuming this has the same
1570  // probability of exiting the loop as any other loop exit.
1571  uint64_t EntryCount = getCurrentProfileCount();
1572  Builder.CreateCondBr(
1573  Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"), EmptyBB,
1574  LoopInitBB,
1575  createProfileWeights(EntryCount, getProfileCount(S.getBody())));
1576 
1577  // Otherwise, initialize the loop.
1578  EmitBlock(LoopInitBB);
1579 
1580  // Save the initial mutations value. This is the value at an
1581  // address that was written into the state object by
1582  // countByEnumeratingWithState:objects:count:.
1583  Address StateMutationsPtrPtr = Builder.CreateStructGEP(
1584  StatePtr, 2, 2 * getPointerSize(), "mutationsptr.ptr");
1585  llvm::Value *StateMutationsPtr
1586  = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
1587 
1588  llvm::Value *initialMutations =
1589  Builder.CreateAlignedLoad(StateMutationsPtr, getPointerAlign(),
1590  "forcoll.initial-mutations");
1591 
1592  // Start looping. This is the point we return to whenever we have a
1593  // fresh, non-empty batch of objects.
1594  llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1595  EmitBlock(LoopBodyBB);
1596 
1597  // The current index into the buffer.
1598  llvm::PHINode *index = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.index");
1599  index->addIncoming(zero, LoopInitBB);
1600 
1601  // The current buffer size.
1602  llvm::PHINode *count = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.count");
1603  count->addIncoming(initialBufferLimit, LoopInitBB);
1604 
1606 
1607  // Check whether the mutations value has changed from where it was
1608  // at start. StateMutationsPtr should actually be invariant between
1609  // refreshes.
1610  StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
1611  llvm::Value *currentMutations
1612  = Builder.CreateAlignedLoad(StateMutationsPtr, getPointerAlign(),
1613  "statemutations");
1614 
1615  llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
1616  llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
1617 
1618  Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1619  WasNotMutatedBB, WasMutatedBB);
1620 
1621  // If so, call the enumeration-mutation function.
1622  EmitBlock(WasMutatedBB);
1623  llvm::Value *V =
1624  Builder.CreateBitCast(Collection,
1625  ConvertType(getContext().getObjCIdType()));
1626  CallArgList Args2;
1627  Args2.add(RValue::get(V), getContext().getObjCIdType());
1628  // FIXME: We shouldn't need to get the function info here, the runtime already
1629  // should have computed it to build the function.
1630  EmitCall(
1632  EnumerationMutationFn, ReturnValueSlot(), Args2);
1633 
1634  // Otherwise, or if the mutation function returns, just continue.
1635  EmitBlock(WasNotMutatedBB);
1636 
1637  // Initialize the element variable.
1638  RunCleanupsScope elementVariableScope(*this);
1639  bool elementIsVariable;
1640  LValue elementLValue;
1641  QualType elementType;
1642  if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
1643  // Initialize the variable, in case it's a __block variable or something.
1644  EmitAutoVarInit(variable);
1645 
1646  const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
1647  DeclRefExpr tempDRE(const_cast<VarDecl*>(D), false, D->getType(),
1649  elementLValue = EmitLValue(&tempDRE);
1650  elementType = D->getType();
1651  elementIsVariable = true;
1652 
1653  if (D->isARCPseudoStrong())
1654  elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
1655  } else {
1656  elementLValue = LValue(); // suppress warning
1657  elementType = cast<Expr>(S.getElement())->getType();
1658  elementIsVariable = false;
1659  }
1660  llvm::Type *convertedElementType = ConvertType(elementType);
1661 
1662  // Fetch the buffer out of the enumeration state.
1663  // TODO: this pointer should actually be invariant between
1664  // refreshes, which would help us do certain loop optimizations.
1665  Address StateItemsPtr = Builder.CreateStructGEP(
1666  StatePtr, 1, getPointerSize(), "stateitems.ptr");
1667  llvm::Value *EnumStateItems =
1668  Builder.CreateLoad(StateItemsPtr, "stateitems");
1669 
1670  // Fetch the value at the current index from the buffer.
1671  llvm::Value *CurrentItemPtr =
1672  Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
1673  llvm::Value *CurrentItem =
1674  Builder.CreateAlignedLoad(CurrentItemPtr, getPointerAlign());
1675 
1676  // Cast that value to the right type.
1677  CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1678  "currentitem");
1679 
1680  // Make sure we have an l-value. Yes, this gets evaluated every
1681  // time through the loop.
1682  if (!elementIsVariable) {
1683  elementLValue = EmitLValue(cast<Expr>(S.getElement()));
1684  EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
1685  } else {
1686  EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue,
1687  /*isInit*/ true);
1688  }
1689 
1690  // If we do have an element variable, this assignment is the end of
1691  // its initialization.
1692  if (elementIsVariable)
1693  EmitAutoVarCleanups(variable);
1694 
1695  // Perform the loop body, setting up break and continue labels.
1696  BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
1697  {
1698  RunCleanupsScope Scope(*this);
1699  EmitStmt(S.getBody());
1700  }
1701  BreakContinueStack.pop_back();
1702 
1703  // Destroy the element variable now.
1704  elementVariableScope.ForceCleanup();
1705 
1706  // Check whether there are more elements.
1707  EmitBlock(AfterBody.getBlock());
1708 
1709  llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
1710 
1711  // First we check in the local buffer.
1712  llvm::Value *indexPlusOne =
1713  Builder.CreateAdd(index, llvm::ConstantInt::get(NSUIntegerTy, 1));
1714 
1715  // If we haven't overrun the buffer yet, we can continue.
1716  // Set the branch weights based on the simplifying assumption that this is
1717  // like a while-loop, i.e., ignoring that the false branch fetches more
1718  // elements and then returns to the loop.
1719  Builder.CreateCondBr(
1720  Builder.CreateICmpULT(indexPlusOne, count), LoopBodyBB, FetchMoreBB,
1721  createProfileWeights(getProfileCount(S.getBody()), EntryCount));
1722 
1723  index->addIncoming(indexPlusOne, AfterBody.getBlock());
1724  count->addIncoming(count, AfterBody.getBlock());
1725 
1726  // Otherwise, we have to fetch more elements.
1727  EmitBlock(FetchMoreBB);
1728 
1729  CountRV =
1731  getContext().getNSUIntegerType(),
1732  FastEnumSel, Collection, Args);
1733 
1734  // If we got a zero count, we're done.
1735  llvm::Value *refetchCount = CountRV.getScalarVal();
1736 
1737  // (note that the message send might split FetchMoreBB)
1738  index->addIncoming(zero, Builder.GetInsertBlock());
1739  count->addIncoming(refetchCount, Builder.GetInsertBlock());
1740 
1741  Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1742  EmptyBB, LoopBodyBB);
1743 
1744  // No more elements.
1745  EmitBlock(EmptyBB);
1746 
1747  if (!elementIsVariable) {
1748  // If the element was not a declaration, set it to be null.
1749 
1750  llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1751  elementLValue = EmitLValue(cast<Expr>(S.getElement()));
1752  EmitStoreThroughLValue(RValue::get(null), elementLValue);
1753  }
1754 
1755  if (DI)
1757 
1758  ForScope.ForceCleanup();
1759  EmitBlock(LoopEnd.getBlock());
1760 }
1761 
1763  CGM.getObjCRuntime().EmitTryStmt(*this, S);
1764 }
1765 
1767  CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1768 }
1769 
1771  const ObjCAtSynchronizedStmt &S) {
1772  CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
1773 }
1774 
1775 namespace {
1776  struct CallObjCRelease final : EHScopeStack::Cleanup {
1777  CallObjCRelease(llvm::Value *object) : object(object) {}
1778  llvm::Value *object;
1779 
1780  void Emit(CodeGenFunction &CGF, Flags flags) override {
1781  // Releases at the end of the full-expression are imprecise.
1782  CGF.EmitARCRelease(object, ARCImpreciseLifetime);
1783  }
1784  };
1785 }
1786 
1787 /// Produce the code for a CK_ARCConsumeObject. Does a primitive
1788 /// release at the end of the full-expression.
1790  llvm::Value *object) {
1791  // If we're in a conditional branch, we need to make the cleanup
1792  // conditional.
1793  pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
1794  return object;
1795 }
1796 
1798  llvm::Value *value) {
1799  return EmitARCRetainAutorelease(type, value);
1800 }
1801 
1802 /// Given a number of pointers, inform the optimizer that they're
1803 /// being intrinsically used up until this point in the program.
1805  llvm::Constant *&fn = CGM.getObjCEntrypoints().clang_arc_use;
1806  if (!fn) {
1807  llvm::FunctionType *fnType =
1808  llvm::FunctionType::get(CGM.VoidTy, None, true);
1809  fn = CGM.CreateRuntimeFunction(fnType, "clang.arc.use");
1810  }
1811 
1812  // This isn't really a "runtime" function, but as an intrinsic it
1813  // doesn't really matter as long as we align things up.
1814  EmitNounwindRuntimeCall(fn, values);
1815 }
1816 
1817 
1818 static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM,
1819  llvm::FunctionType *FTy,
1820  StringRef Name) {
1821  llvm::Constant *RTF = CGM.CreateRuntimeFunction(FTy, Name);
1822 
1823  if (auto *F = dyn_cast<llvm::Function>(RTF)) {
1824  // If the target runtime doesn't naturally support ARC, emit weak
1825  // references to the runtime support library. We don't really
1826  // permit this to fail, but we need a particular relocation style.
1827  if (!CGM.getLangOpts().ObjCRuntime.hasNativeARC() &&
1828  !CGM.getTriple().isOSBinFormatCOFF()) {
1829  F->setLinkage(llvm::Function::ExternalWeakLinkage);
1830  } else if (Name == "objc_retain" || Name == "objc_release") {
1831  // If we have Native ARC, set nonlazybind attribute for these APIs for
1832  // performance.
1833  F->addFnAttr(llvm::Attribute::NonLazyBind);
1834  }
1835  }
1836 
1837  return RTF;
1838 }
1839 
1840 /// Perform an operation having the signature
1841 /// i8* (i8*)
1842 /// where a null input causes a no-op and returns null.
1844  llvm::Value *value,
1845  llvm::Constant *&fn,
1846  StringRef fnName,
1847  bool isTailCall = false) {
1848  if (isa<llvm::ConstantPointerNull>(value))
1849  return value;
1850 
1851  if (!fn) {
1852  llvm::FunctionType *fnType =
1853  llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, false);
1854  fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1855  }
1856 
1857  // Cast the argument to 'id'.
1858  llvm::Type *origType = value->getType();
1859  value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1860 
1861  // Call the function.
1862  llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(fn, value);
1863  if (isTailCall)
1864  call->setTailCall();
1865 
1866  // Cast the result back to the original type.
1867  return CGF.Builder.CreateBitCast(call, origType);
1868 }
1869 
1870 /// Perform an operation having the following signature:
1871 /// i8* (i8**)
1873  Address addr,
1874  llvm::Constant *&fn,
1875  StringRef fnName) {
1876  if (!fn) {
1877  llvm::FunctionType *fnType =
1878  llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrPtrTy, false);
1879  fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1880  }
1881 
1882  // Cast the argument to 'id*'.
1883  llvm::Type *origType = addr.getElementType();
1884  addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1885 
1886  // Call the function.
1887  llvm::Value *result = CGF.EmitNounwindRuntimeCall(fn, addr.getPointer());
1888 
1889  // Cast the result back to a dereference of the original type.
1890  if (origType != CGF.Int8PtrTy)
1891  result = CGF.Builder.CreateBitCast(result, origType);
1892 
1893  return result;
1894 }
1895 
1896 /// Perform an operation having the following signature:
1897 /// i8* (i8**, i8*)
1899  Address addr,
1900  llvm::Value *value,
1901  llvm::Constant *&fn,
1902  StringRef fnName,
1903  bool ignored) {
1904  assert(addr.getElementType() == value->getType());
1905 
1906  if (!fn) {
1907  llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrTy };
1908 
1909  llvm::FunctionType *fnType
1910  = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false);
1911  fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1912  }
1913 
1914  llvm::Type *origType = value->getType();
1915 
1916  llvm::Value *args[] = {
1917  CGF.Builder.CreateBitCast(addr.getPointer(), CGF.Int8PtrPtrTy),
1918  CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy)
1919  };
1920  llvm::CallInst *result = CGF.EmitNounwindRuntimeCall(fn, args);
1921 
1922  if (ignored) return nullptr;
1923 
1924  return CGF.Builder.CreateBitCast(result, origType);
1925 }
1926 
1927 /// Perform an operation having the following signature:
1928 /// void (i8**, i8**)
1930  Address dst,
1931  Address src,
1932  llvm::Constant *&fn,
1933  StringRef fnName) {
1934  assert(dst.getType() == src.getType());
1935 
1936  if (!fn) {
1937  llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrPtrTy };
1938 
1939  llvm::FunctionType *fnType
1940  = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false);
1941  fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1942  }
1943 
1944  llvm::Value *args[] = {
1945  CGF.Builder.CreateBitCast(dst.getPointer(), CGF.Int8PtrPtrTy),
1947  };
1948  CGF.EmitNounwindRuntimeCall(fn, args);
1949 }
1950 
1951 /// Produce the code to do a retain. Based on the type, calls one of:
1952 /// call i8* \@objc_retain(i8* %value)
1953 /// call i8* \@objc_retainBlock(i8* %value)
1955  if (type->isBlockPointerType())
1956  return EmitARCRetainBlock(value, /*mandatory*/ false);
1957  else
1958  return EmitARCRetainNonBlock(value);
1959 }
1960 
1961 /// Retain the given object, with normal retain semantics.
1962 /// call i8* \@objc_retain(i8* %value)
1964  return emitARCValueOperation(*this, value,
1966  "objc_retain");
1967 }
1968 
1969 /// Retain the given block, with _Block_copy semantics.
1970 /// call i8* \@objc_retainBlock(i8* %value)
1971 ///
1972 /// \param mandatory - If false, emit the call with metadata
1973 /// indicating that it's okay for the optimizer to eliminate this call
1974 /// if it can prove that the block never escapes except down the stack.
1976  bool mandatory) {
1977  llvm::Value *result
1978  = emitARCValueOperation(*this, value,
1980  "objc_retainBlock");
1981 
1982  // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
1983  // tell the optimizer that it doesn't need to do this copy if the
1984  // block doesn't escape, where being passed as an argument doesn't
1985  // count as escaping.
1986  if (!mandatory && isa<llvm::Instruction>(result)) {
1987  llvm::CallInst *call
1988  = cast<llvm::CallInst>(result->stripPointerCasts());
1989  assert(call->getCalledValue() == CGM.getObjCEntrypoints().objc_retainBlock);
1990 
1991  call->setMetadata("clang.arc.copy_on_escape",
1992  llvm::MDNode::get(Builder.getContext(), None));
1993  }
1994 
1995  return result;
1996 }
1997 
1999  // Fetch the void(void) inline asm which marks that we're going to
2000  // do something with the autoreleased return value.
2001  llvm::InlineAsm *&marker
2003  if (!marker) {
2004  StringRef assembly
2005  = CGF.CGM.getTargetCodeGenInfo()
2007 
2008  // If we have an empty assembly string, there's nothing to do.
2009  if (assembly.empty()) {
2010 
2011  // Otherwise, at -O0, build an inline asm that we're going to call
2012  // in a moment.
2013  } else if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
2014  llvm::FunctionType *type =
2015  llvm::FunctionType::get(CGF.VoidTy, /*variadic*/false);
2016 
2017  marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
2018 
2019  // If we're at -O1 and above, we don't want to litter the code
2020  // with this marker yet, so leave a breadcrumb for the ARC
2021  // optimizer to pick up.
2022  } else {
2023  llvm::NamedMDNode *metadata =
2024  CGF.CGM.getModule().getOrInsertNamedMetadata(
2025  "clang.arc.retainAutoreleasedReturnValueMarker");
2026  assert(metadata->getNumOperands() <= 1);
2027  if (metadata->getNumOperands() == 0) {
2028  auto &ctx = CGF.getLLVMContext();
2029  metadata->addOperand(llvm::MDNode::get(ctx,
2030  llvm::MDString::get(ctx, assembly)));
2031  }
2032  }
2033  }
2034 
2035  // Call the marker asm if we made one, which we do only at -O0.
2036  if (marker)
2037  CGF.Builder.CreateCall(marker);
2038 }
2039 
2040 /// Retain the given object which is the result of a function call.
2041 /// call i8* \@objc_retainAutoreleasedReturnValue(i8* %value)
2042 ///
2043 /// Yes, this function name is one character away from a different
2044 /// call with completely different semantics.
2045 llvm::Value *
2048  return emitARCValueOperation(*this, value,
2050  "objc_retainAutoreleasedReturnValue");
2051 }
2052 
2053 /// Claim a possibly-autoreleased return value at +0. This is only
2054 /// valid to do in contexts which do not rely on the retain to keep
2055 /// the object valid for all of its uses; for example, when
2056 /// the value is ignored, or when it is being assigned to an
2057 /// __unsafe_unretained variable.
2058 ///
2059 /// call i8* \@objc_unsafeClaimAutoreleasedReturnValue(i8* %value)
2060 llvm::Value *
2063  return emitARCValueOperation(*this, value,
2065  "objc_unsafeClaimAutoreleasedReturnValue");
2066 }
2067 
2068 /// Release the given object.
2069 /// call void \@objc_release(i8* %value)
2071  ARCPreciseLifetime_t precise) {
2072  if (isa<llvm::ConstantPointerNull>(value)) return;
2073 
2074  llvm::Constant *&fn = CGM.getObjCEntrypoints().objc_release;
2075  if (!fn) {
2076  llvm::FunctionType *fnType =
2077  llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
2078  fn = createARCRuntimeFunction(CGM, fnType, "objc_release");
2079  }
2080 
2081  // Cast the argument to 'id'.
2082  value = Builder.CreateBitCast(value, Int8PtrTy);
2083 
2084  // Call objc_release.
2085  llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);
2086 
2087  if (precise == ARCImpreciseLifetime) {
2088  call->setMetadata("clang.imprecise_release",
2089  llvm::MDNode::get(Builder.getContext(), None));
2090  }
2091 }
2092 
2093 /// Destroy a __strong variable.
2094 ///
2095 /// At -O0, emit a call to store 'null' into the address;
2096 /// instrumenting tools prefer this because the address is exposed,
2097 /// but it's relatively cumbersome to optimize.
2098 ///
2099 /// At -O1 and above, just load and call objc_release.
2100 ///
2101 /// call void \@objc_storeStrong(i8** %addr, i8* null)
2103  ARCPreciseLifetime_t precise) {
2104  if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2105  llvm::Value *null = getNullForVariable(addr);
2106  EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
2107  return;
2108  }
2109 
2110  llvm::Value *value = Builder.CreateLoad(addr);
2111  EmitARCRelease(value, precise);
2112 }
2113 
2114 /// Store into a strong object. Always calls this:
2115 /// call void \@objc_storeStrong(i8** %addr, i8* %value)
2117  llvm::Value *value,
2118  bool ignored) {
2119  assert(addr.getElementType() == value->getType());
2120 
2121  llvm::Constant *&fn = CGM.getObjCEntrypoints().objc_storeStrong;
2122  if (!fn) {
2123  llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy };
2124  llvm::FunctionType *fnType
2125  = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false);
2126  fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong");
2127  }
2128 
2129  llvm::Value *args[] = {
2132  };
2133  EmitNounwindRuntimeCall(fn, args);
2134 
2135  if (ignored) return nullptr;
2136  return value;
2137 }
2138 
2139 /// Store into a strong object. Sometimes calls this:
2140 /// call void \@objc_storeStrong(i8** %addr, i8* %value)
2141 /// Other times, breaks it down into components.
2143  llvm::Value *newValue,
2144  bool ignored) {
2145  QualType type = dst.getType();
2146  bool isBlock = type->isBlockPointerType();
2147 
2148  // Use a store barrier at -O0 unless this is a block type or the
2149  // lvalue is inadequately aligned.
2150  if (shouldUseFusedARCCalls() &&
2151  !isBlock &&
2152  (dst.getAlignment().isZero() ||
2154  return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
2155  }
2156 
2157  // Otherwise, split it out.
2158 
2159  // Retain the new value.
2160  newValue = EmitARCRetain(type, newValue);
2161 
2162  // Read the old value.
2163  llvm::Value *oldValue = EmitLoadOfScalar(dst, SourceLocation());
2164 
2165  // Store. We do this before the release so that any deallocs won't
2166  // see the old value.
2167  EmitStoreOfScalar(newValue, dst);
2168 
2169  // Finally, release the old value.
2170  EmitARCRelease(oldValue, dst.isARCPreciseLifetime());
2171 
2172  return newValue;
2173 }
2174 
2175 /// Autorelease the given object.
2176 /// call i8* \@objc_autorelease(i8* %value)
2178  return emitARCValueOperation(*this, value,
2180  "objc_autorelease");
2181 }
2182 
2183 /// Autorelease the given object.
2184 /// call i8* \@objc_autoreleaseReturnValue(i8* %value)
2185 llvm::Value *
2187  return emitARCValueOperation(*this, value,
2189  "objc_autoreleaseReturnValue",
2190  /*isTailCall*/ true);
2191 }
2192 
2193 /// Do a fused retain/autorelease of the given object.
2194 /// call i8* \@objc_retainAutoreleaseReturnValue(i8* %value)
2195 llvm::Value *
2197  return emitARCValueOperation(*this, value,
2199  "objc_retainAutoreleaseReturnValue",
2200  /*isTailCall*/ true);
2201 }
2202 
2203 /// Do a fused retain/autorelease of the given object.
2204 /// call i8* \@objc_retainAutorelease(i8* %value)
2205 /// or
2206 /// %retain = call i8* \@objc_retainBlock(i8* %value)
2207 /// call i8* \@objc_autorelease(i8* %retain)
2209  llvm::Value *value) {
2210  if (!type->isBlockPointerType())
2211  return EmitARCRetainAutoreleaseNonBlock(value);
2212 
2213  if (isa<llvm::ConstantPointerNull>(value)) return value;
2214 
2215  llvm::Type *origType = value->getType();
2216  value = Builder.CreateBitCast(value, Int8PtrTy);
2217  value = EmitARCRetainBlock(value, /*mandatory*/ true);
2218  value = EmitARCAutorelease(value);
2219  return Builder.CreateBitCast(value, origType);
2220 }
2221 
2222 /// Do a fused retain/autorelease of the given object.
2223 /// call i8* \@objc_retainAutorelease(i8* %value)
2224 llvm::Value *
2226  return emitARCValueOperation(*this, value,
2228  "objc_retainAutorelease");
2229 }
2230 
2231 /// i8* \@objc_loadWeak(i8** %addr)
2232 /// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
2234  return emitARCLoadOperation(*this, addr,
2236  "objc_loadWeak");
2237 }
2238 
2239 /// i8* \@objc_loadWeakRetained(i8** %addr)
2241  return emitARCLoadOperation(*this, addr,
2243  "objc_loadWeakRetained");
2244 }
2245 
2246 /// i8* \@objc_storeWeak(i8** %addr, i8* %value)
2247 /// Returns %value.
2249  llvm::Value *value,
2250  bool ignored) {
2251  return emitARCStoreOperation(*this, addr, value,
2253  "objc_storeWeak", ignored);
2254 }
2255 
2256 /// i8* \@objc_initWeak(i8** %addr, i8* %value)
2257 /// Returns %value. %addr is known to not have a current weak entry.
2258 /// Essentially equivalent to:
2259 /// *addr = nil; objc_storeWeak(addr, value);
2261  // If we're initializing to null, just write null to memory; no need
2262  // to get the runtime involved. But don't do this if optimization
2263  // is enabled, because accounting for this would make the optimizer
2264  // much more complicated.
2265  if (isa<llvm::ConstantPointerNull>(value) &&
2266  CGM.getCodeGenOpts().OptimizationLevel == 0) {
2267  Builder.CreateStore(value, addr);
2268  return;
2269  }
2270 
2271  emitARCStoreOperation(*this, addr, value,
2273  "objc_initWeak", /*ignored*/ true);
2274 }
2275 
2276 /// void \@objc_destroyWeak(i8** %addr)
2277 /// Essentially objc_storeWeak(addr, nil).
2279  llvm::Constant *&fn = CGM.getObjCEntrypoints().objc_destroyWeak;
2280  if (!fn) {
2281  llvm::FunctionType *fnType =
2282  llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrPtrTy, false);
2283  fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak");
2284  }
2285 
2286  // Cast the argument to 'id*'.
2287  addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
2288 
2289  EmitNounwindRuntimeCall(fn, addr.getPointer());
2290 }
2291 
2292 /// void \@objc_moveWeak(i8** %dest, i8** %src)
2293 /// Disregards the current value in %dest. Leaves %src pointing to nothing.
2294 /// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
2296  emitARCCopyOperation(*this, dst, src,
2298  "objc_moveWeak");
2299 }
2300 
2301 /// void \@objc_copyWeak(i8** %dest, i8** %src)
2302 /// Disregards the current value in %dest. Essentially
2303 /// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
2305  emitARCCopyOperation(*this, dst, src,
2307  "objc_copyWeak");
2308 }
2309 
2310 /// Produce the code to do a objc_autoreleasepool_push.
2311 /// call i8* \@objc_autoreleasePoolPush(void)
2313  llvm::Constant *&fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPush;
2314  if (!fn) {
2315  llvm::FunctionType *fnType =
2316  llvm::FunctionType::get(Int8PtrTy, false);
2317  fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush");
2318  }
2319 
2320  return EmitNounwindRuntimeCall(fn);
2321 }
2322 
2323 /// Produce the code to do a primitive release.
2324 /// call void \@objc_autoreleasePoolPop(i8* %ptr)
2326  assert(value->getType() == Int8PtrTy);
2327 
2328  llvm::Constant *&fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPop;
2329  if (!fn) {
2330  llvm::FunctionType *fnType =
2331  llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
2332 
2333  // We don't want to use a weak import here; instead we should not
2334  // fall into this path.
2335  fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop");
2336  }
2337 
2338  // objc_autoreleasePoolPop can throw.
2339  EmitRuntimeCallOrInvoke(fn, value);
2340 }
2341 
2342 /// Produce the code to do an MRR version objc_autoreleasepool_push.
2343 /// Which is: [[NSAutoreleasePool alloc] init];
2344 /// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2345 /// init is declared as: - (id) init; in its NSObject super class.
2346 ///
2348  CGObjCRuntime &Runtime = CGM.getObjCRuntime();
2349  llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(*this);
2350  // [NSAutoreleasePool alloc]
2351  IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2352  Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2353  CallArgList Args;
2354  RValue AllocRV =
2355  Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2356  getContext().getObjCIdType(),
2357  AllocSel, Receiver, Args);
2358 
2359  // [Receiver init]
2360  Receiver = AllocRV.getScalarVal();
2361  II = &CGM.getContext().Idents.get("init");
2362  Selector InitSel = getContext().Selectors.getSelector(0, &II);
2363  RValue InitRV =
2364  Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2365  getContext().getObjCIdType(),
2366  InitSel, Receiver, Args);
2367  return InitRV.getScalarVal();
2368 }
2369 
2370 /// Produce the code to do a primitive release.
2371 /// [tmp drain];
2373  IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2374  Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2375  CallArgList Args;
2377  getContext().VoidTy, DrainSel, Arg, Args);
2378 }
2379 
2381  Address addr,
2382  QualType type) {
2384 }
2385 
2387  Address addr,
2388  QualType type) {
2390 }
2391 
2393  Address addr,
2394  QualType type) {
2395  CGF.EmitARCDestroyWeak(addr);
2396 }
2397 
2399  QualType type) {
2400  llvm::Value *value = CGF.Builder.CreateLoad(addr);
2401  CGF.EmitARCIntrinsicUse(value);
2402 }
2403 
2404 namespace {
2405  struct CallObjCAutoreleasePoolObject final : EHScopeStack::Cleanup {
2406  llvm::Value *Token;
2407 
2408  CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2409 
2410  void Emit(CodeGenFunction &CGF, Flags flags) override {
2411  CGF.EmitObjCAutoreleasePoolPop(Token);
2412  }
2413  };
2414  struct CallObjCMRRAutoreleasePoolObject final : EHScopeStack::Cleanup {
2415  llvm::Value *Token;
2416 
2417  CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2418 
2419  void Emit(CodeGenFunction &CGF, Flags flags) override {
2420  CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2421  }
2422  };
2423 }
2424 
2426  if (CGM.getLangOpts().ObjCAutoRefCount)
2427  EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2428  else
2429  EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2430 }
2431 
2433  LValue lvalue,
2434  QualType type) {
2435  switch (type.getObjCLifetime()) {
2436  case Qualifiers::OCL_None:
2440  return TryEmitResult(CGF.EmitLoadOfLValue(lvalue,
2442  false);
2443 
2444  case Qualifiers::OCL_Weak:
2445  return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()),
2446  true);
2447  }
2448 
2449  llvm_unreachable("impossible lifetime!");
2450 }
2451 
2453  const Expr *e) {
2454  e = e->IgnoreParens();
2455  QualType type = e->getType();
2456 
2457  // If we're loading retained from a __strong xvalue, we can avoid
2458  // an extra retain/release pair by zeroing out the source of this
2459  // "move" operation.
2460  if (e->isXValue() &&
2461  !type.isConstQualified() &&
2463  // Emit the lvalue.
2464  LValue lv = CGF.EmitLValue(e);
2465 
2466  // Load the object pointer.
2467  llvm::Value *result = CGF.EmitLoadOfLValue(lv,
2469 
2470  // Set the source pointer to NULL.
2472 
2473  return TryEmitResult(result, true);
2474  }
2475 
2476  // As a very special optimization, in ARC++, if the l-value is the
2477  // result of a non-volatile assignment, do a simple retain of the
2478  // result of the call to objc_storeWeak instead of reloading.
2479  if (CGF.getLangOpts().CPlusPlus &&
2480  !type.isVolatileQualified() &&
2482  isa<BinaryOperator>(e) &&
2483  cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2484  return TryEmitResult(CGF.EmitScalarExpr(e), false);
2485 
2486  return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2487 }
2488 
2489 typedef llvm::function_ref<llvm::Value *(CodeGenFunction &CGF,
2490  llvm::Value *value)>
2492 
2493 /// Insert code immediately after a call.
2495  llvm::Value *value,
2496  ValueTransform doAfterCall,
2497  ValueTransform doFallback) {
2498  if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2499  CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2500 
2501  // Place the retain immediately following the call.
2502  CGF.Builder.SetInsertPoint(call->getParent(),
2503  ++llvm::BasicBlock::iterator(call));
2504  value = doAfterCall(CGF, value);
2505 
2506  CGF.Builder.restoreIP(ip);
2507  return value;
2508  } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2509  CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2510 
2511  // Place the retain at the beginning of the normal destination block.
2512  llvm::BasicBlock *BB = invoke->getNormalDest();
2513  CGF.Builder.SetInsertPoint(BB, BB->begin());
2514  value = doAfterCall(CGF, value);
2515 
2516  CGF.Builder.restoreIP(ip);
2517  return value;
2518 
2519  // Bitcasts can arise because of related-result returns. Rewrite
2520  // the operand.
2521  } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2522  llvm::Value *operand = bitcast->getOperand(0);
2523  operand = emitARCOperationAfterCall(CGF, operand, doAfterCall, doFallback);
2524  bitcast->setOperand(0, operand);
2525  return bitcast;
2526 
2527  // Generic fall-back case.
2528  } else {
2529  // Retain using the non-block variant: we never need to do a copy
2530  // of a block that's been returned to us.
2531  return doFallback(CGF, value);
2532  }
2533 }
2534 
2535 /// Given that the given expression is some sort of call (which does
2536 /// not return retained), emit a retain following it.
2538  const Expr *e) {
2539  llvm::Value *value = CGF.EmitScalarExpr(e);
2540  return emitARCOperationAfterCall(CGF, value,
2541  [](CodeGenFunction &CGF, llvm::Value *value) {
2542  return CGF.EmitARCRetainAutoreleasedReturnValue(value);
2543  },
2544  [](CodeGenFunction &CGF, llvm::Value *value) {
2545  return CGF.EmitARCRetainNonBlock(value);
2546  });
2547 }
2548 
2549 /// Given that the given expression is some sort of call (which does
2550 /// not return retained), perform an unsafeClaim following it.
2552  const Expr *e) {
2553  llvm::Value *value = CGF.EmitScalarExpr(e);
2554  return emitARCOperationAfterCall(CGF, value,
2555  [](CodeGenFunction &CGF, llvm::Value *value) {
2557  },
2558  [](CodeGenFunction &CGF, llvm::Value *value) {
2559  return value;
2560  });
2561 }
2562 
2564  bool allowUnsafeClaim) {
2565  if (allowUnsafeClaim &&
2567  return emitARCUnsafeClaimCallResult(*this, E);
2568  } else {
2569  llvm::Value *value = emitARCRetainCallResult(*this, E);
2570  return EmitObjCConsumeObject(E->getType(), value);
2571  }
2572 }
2573 
2574 /// Determine whether it might be important to emit a separate
2575 /// objc_retain_block on the result of the given expression, or
2576 /// whether it's okay to just emit it in a +1 context.
2577 static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2578  assert(e->getType()->isBlockPointerType());
2579  e = e->IgnoreParens();
2580 
2581  // For future goodness, emit block expressions directly in +1
2582  // contexts if we can.
2583  if (isa<BlockExpr>(e))
2584  return false;
2585 
2586  if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2587  switch (cast->getCastKind()) {
2588  // Emitting these operations in +1 contexts is goodness.
2589  case CK_LValueToRValue:
2590  case CK_ARCReclaimReturnedObject:
2591  case CK_ARCConsumeObject:
2592  case CK_ARCProduceObject:
2593  return false;
2594 
2595  // These operations preserve a block type.
2596  case CK_NoOp:
2597  case CK_BitCast:
2598  return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2599 
2600  // These operations are known to be bad (or haven't been considered).
2601  case CK_AnyPointerToBlockPointerCast:
2602  default:
2603  return true;
2604  }
2605  }
2606 
2607  return true;
2608 }
2609 
2610 namespace {
2611 /// A CRTP base class for emitting expressions of retainable object
2612 /// pointer type in ARC.
2613 template <typename Impl, typename Result> class ARCExprEmitter {
2614 protected:
2615  CodeGenFunction &CGF;
2616  Impl &asImpl() { return *static_cast<Impl*>(this); }
2617 
2618  ARCExprEmitter(CodeGenFunction &CGF) : CGF(CGF) {}
2619 
2620 public:
2621  Result visit(const Expr *e);
2622  Result visitCastExpr(const CastExpr *e);
2623  Result visitPseudoObjectExpr(const PseudoObjectExpr *e);
2624  Result visitBinaryOperator(const BinaryOperator *e);
2625  Result visitBinAssign(const BinaryOperator *e);
2626  Result visitBinAssignUnsafeUnretained(const BinaryOperator *e);
2627  Result visitBinAssignAutoreleasing(const BinaryOperator *e);
2628  Result visitBinAssignWeak(const BinaryOperator *e);
2629  Result visitBinAssignStrong(const BinaryOperator *e);
2630 
2631  // Minimal implementation:
2632  // Result visitLValueToRValue(const Expr *e)
2633  // Result visitConsumeObject(const Expr *e)
2634  // Result visitExtendBlockObject(const Expr *e)
2635  // Result visitReclaimReturnedObject(const Expr *e)
2636  // Result visitCall(const Expr *e)
2637  // Result visitExpr(const Expr *e)
2638  //
2639  // Result emitBitCast(Result result, llvm::Type *resultType)
2640  // llvm::Value *getValueOfResult(Result result)
2641 };
2642 }
2643 
2644 /// Try to emit a PseudoObjectExpr under special ARC rules.
2645 ///
2646 /// This massively duplicates emitPseudoObjectRValue.
2647 template <typename Impl, typename Result>
2648 Result
2649 ARCExprEmitter<Impl,Result>::visitPseudoObjectExpr(const PseudoObjectExpr *E) {
2651 
2652  // Find the result expression.
2653  const Expr *resultExpr = E->getResultExpr();
2654  assert(resultExpr);
2655  Result result;
2656 
2658  i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
2659  const Expr *semantic = *i;
2660 
2661  // If this semantic expression is an opaque value, bind it
2662  // to the result of its source expression.
2663  if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2665  OVMA opaqueData;
2666 
2667  // If this semantic is the result of the pseudo-object
2668  // expression, try to evaluate the source as +1.
2669  if (ov == resultExpr) {
2670  assert(!OVMA::shouldBindAsLValue(ov));
2671  result = asImpl().visit(ov->getSourceExpr());
2672  opaqueData = OVMA::bind(CGF, ov,
2673  RValue::get(asImpl().getValueOfResult(result)));
2674 
2675  // Otherwise, just bind it.
2676  } else {
2677  opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2678  }
2679  opaques.push_back(opaqueData);
2680 
2681  // Otherwise, if the expression is the result, evaluate it
2682  // and remember the result.
2683  } else if (semantic == resultExpr) {
2684  result = asImpl().visit(semantic);
2685 
2686  // Otherwise, evaluate the expression in an ignored context.
2687  } else {
2688  CGF.EmitIgnoredExpr(semantic);
2689  }
2690  }
2691 
2692  // Unbind all the opaques now.
2693  for (unsigned i = 0, e = opaques.size(); i != e; ++i)
2694  opaques[i].unbind(CGF);
2695 
2696  return result;
2697 }
2698 
2699 template <typename Impl, typename Result>
2700 Result ARCExprEmitter<Impl,Result>::visitCastExpr(const CastExpr *e) {
2701  switch (e->getCastKind()) {
2702 
2703  // No-op casts don't change the type, so we just ignore them.
2704  case CK_NoOp:
2705  return asImpl().visit(e->getSubExpr());
2706 
2707  // These casts can change the type.
2708  case CK_CPointerToObjCPointerCast:
2709  case CK_BlockPointerToObjCPointerCast:
2710  case CK_AnyPointerToBlockPointerCast:
2711  case CK_BitCast: {
2712  llvm::Type *resultType = CGF.ConvertType(e->getType());
2713  assert(e->getSubExpr()->getType()->hasPointerRepresentation());
2714  Result result = asImpl().visit(e->getSubExpr());
2715  return asImpl().emitBitCast(result, resultType);
2716  }
2717 
2718  // Handle some casts specially.
2719  case CK_LValueToRValue:
2720  return asImpl().visitLValueToRValue(e->getSubExpr());
2721  case CK_ARCConsumeObject:
2722  return asImpl().visitConsumeObject(e->getSubExpr());
2723  case CK_ARCExtendBlockObject:
2724  return asImpl().visitExtendBlockObject(e->getSubExpr());
2725  case CK_ARCReclaimReturnedObject:
2726  return asImpl().visitReclaimReturnedObject(e->getSubExpr());
2727 
2728  // Otherwise, use the default logic.
2729  default:
2730  return asImpl().visitExpr(e);
2731  }
2732 }
2733 
2734 template <typename Impl, typename Result>
2735 Result
2736 ARCExprEmitter<Impl,Result>::visitBinaryOperator(const BinaryOperator *e) {
2737  switch (e->getOpcode()) {
2738  case BO_Comma:
2739  CGF.EmitIgnoredExpr(e->getLHS());
2740  CGF.EnsureInsertPoint();
2741  return asImpl().visit(e->getRHS());
2742 
2743  case BO_Assign:
2744  return asImpl().visitBinAssign(e);
2745 
2746  default:
2747  return asImpl().visitExpr(e);
2748  }
2749 }
2750 
2751 template <typename Impl, typename Result>
2752 Result ARCExprEmitter<Impl,Result>::visitBinAssign(const BinaryOperator *e) {
2753  switch (e->getLHS()->getType().getObjCLifetime()) {
2755  return asImpl().visitBinAssignUnsafeUnretained(e);
2756 
2757  case Qualifiers::OCL_Weak:
2758  return asImpl().visitBinAssignWeak(e);
2759 
2761  return asImpl().visitBinAssignAutoreleasing(e);
2762 
2764  return asImpl().visitBinAssignStrong(e);
2765 
2766  case Qualifiers::OCL_None:
2767  return asImpl().visitExpr(e);
2768  }
2769  llvm_unreachable("bad ObjC ownership qualifier");
2770 }
2771 
2772 /// The default rule for __unsafe_unretained emits the RHS recursively,
2773 /// stores into the unsafe variable, and propagates the result outward.
2774 template <typename Impl, typename Result>
2775 Result ARCExprEmitter<Impl,Result>::
2776  visitBinAssignUnsafeUnretained(const BinaryOperator *e) {
2777  // Recursively emit the RHS.
2778  // For __block safety, do this before emitting the LHS.
2779  Result result = asImpl().visit(e->getRHS());
2780 
2781  // Perform the store.
2782  LValue lvalue =
2784  CGF.EmitStoreThroughLValue(RValue::get(asImpl().getValueOfResult(result)),
2785  lvalue);
2786 
2787  return result;
2788 }
2789 
2790 template <typename Impl, typename Result>
2791 Result
2792 ARCExprEmitter<Impl,Result>::visitBinAssignAutoreleasing(const BinaryOperator *e) {
2793  return asImpl().visitExpr(e);
2794 }
2795 
2796 template <typename Impl, typename Result>
2797 Result
2798 ARCExprEmitter<Impl,Result>::visitBinAssignWeak(const BinaryOperator *e) {
2799  return asImpl().visitExpr(e);
2800 }
2801 
2802 template <typename Impl, typename Result>
2803 Result
2804 ARCExprEmitter<Impl,Result>::visitBinAssignStrong(const BinaryOperator *e) {
2805  return asImpl().visitExpr(e);
2806 }
2807 
2808 /// The general expression-emission logic.
2809 template <typename Impl, typename Result>
2810 Result ARCExprEmitter<Impl,Result>::visit(const Expr *e) {
2811  // We should *never* see a nested full-expression here, because if
2812  // we fail to emit at +1, our caller must not retain after we close
2813  // out the full-expression. This isn't as important in the unsafe
2814  // emitter.
2815  assert(!isa<ExprWithCleanups>(e));
2816 
2817  // Look through parens, __extension__, generic selection, etc.
2818  e = e->IgnoreParens();
2819 
2820  // Handle certain kinds of casts.
2821  if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
2822  return asImpl().visitCastExpr(ce);
2823 
2824  // Handle the comma operator.
2825  } else if (auto op = dyn_cast<BinaryOperator>(e)) {
2826  return asImpl().visitBinaryOperator(op);
2827 
2828  // TODO: handle conditional operators here
2829 
2830  // For calls and message sends, use the retained-call logic.
2831  // Delegate inits are a special case in that they're the only
2832  // returns-retained expression that *isn't* surrounded by
2833  // a consume.
2834  } else if (isa<CallExpr>(e) ||
2835  (isa<ObjCMessageExpr>(e) &&
2836  !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
2837  return asImpl().visitCall(e);
2838 
2839  // Look through pseudo-object expressions.
2840  } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
2841  return asImpl().visitPseudoObjectExpr(pseudo);
2842  }
2843 
2844  return asImpl().visitExpr(e);
2845 }
2846 
2847 namespace {
2848 
2849 /// An emitter for +1 results.
2850 struct ARCRetainExprEmitter :
2851  public ARCExprEmitter<ARCRetainExprEmitter, TryEmitResult> {
2852 
2853  ARCRetainExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
2854 
2855  llvm::Value *getValueOfResult(TryEmitResult result) {
2856  return result.getPointer();
2857  }
2858 
2859  TryEmitResult emitBitCast(TryEmitResult result, llvm::Type *resultType) {
2860  llvm::Value *value = result.getPointer();
2861  value = CGF.Builder.CreateBitCast(value, resultType);
2862  result.setPointer(value);
2863  return result;
2864  }
2865 
2866  TryEmitResult visitLValueToRValue(const Expr *e) {
2867  return tryEmitARCRetainLoadOfScalar(CGF, e);
2868  }
2869 
2870  /// For consumptions, just emit the subexpression and thus elide
2871  /// the retain/release pair.
2872  TryEmitResult visitConsumeObject(const Expr *e) {
2873  llvm::Value *result = CGF.EmitScalarExpr(e);
2874  return TryEmitResult(result, true);
2875  }
2876 
2877  /// Block extends are net +0. Naively, we could just recurse on
2878  /// the subexpression, but actually we need to ensure that the
2879  /// value is copied as a block, so there's a little filter here.
2880  TryEmitResult visitExtendBlockObject(const Expr *e) {
2881  llvm::Value *result; // will be a +0 value
2882 
2883  // If we can't safely assume the sub-expression will produce a
2884  // block-copied value, emit the sub-expression at +0.
2886  result = CGF.EmitScalarExpr(e);
2887 
2888  // Otherwise, try to emit the sub-expression at +1 recursively.
2889  } else {
2890  TryEmitResult subresult = asImpl().visit(e);
2891 
2892  // If that produced a retained value, just use that.
2893  if (subresult.getInt()) {
2894  return subresult;
2895  }
2896 
2897  // Otherwise it's +0.
2898  result = subresult.getPointer();
2899  }
2900 
2901  // Retain the object as a block.
2902  result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
2903  return TryEmitResult(result, true);
2904  }
2905 
2906  /// For reclaims, emit the subexpression as a retained call and
2907  /// skip the consumption.
2908  TryEmitResult visitReclaimReturnedObject(const Expr *e) {
2909  llvm::Value *result = emitARCRetainCallResult(CGF, e);
2910  return TryEmitResult(result, true);
2911  }
2912 
2913  /// When we have an undecorated call, retroactively do a claim.
2914  TryEmitResult visitCall(const Expr *e) {
2915  llvm::Value *result = emitARCRetainCallResult(CGF, e);
2916  return TryEmitResult(result, true);
2917  }
2918 
2919  // TODO: maybe special-case visitBinAssignWeak?
2920 
2921  TryEmitResult visitExpr(const Expr *e) {
2922  // We didn't find an obvious production, so emit what we've got and
2923  // tell the caller that we didn't manage to retain.
2924  llvm::Value *result = CGF.EmitScalarExpr(e);
2925  return TryEmitResult(result, false);
2926  }
2927 };
2928 }
2929 
2930 static TryEmitResult
2932  return ARCRetainExprEmitter(CGF).visit(e);
2933 }
2934 
2936  LValue lvalue,
2937  QualType type) {
2938  TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
2939  llvm::Value *value = result.getPointer();
2940  if (!result.getInt())
2941  value = CGF.EmitARCRetain(type, value);
2942  return value;
2943 }
2944 
2945 /// EmitARCRetainScalarExpr - Semantically equivalent to
2946 /// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
2947 /// best-effort attempt to peephole expressions that naturally produce
2948 /// retained objects.
2950  // The retain needs to happen within the full-expression.
2951  if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
2952  enterFullExpression(cleanups);
2953  RunCleanupsScope scope(*this);
2954  return EmitARCRetainScalarExpr(cleanups->getSubExpr());
2955  }
2956 
2957  TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2958  llvm::Value *value = result.getPointer();
2959  if (!result.getInt())
2960  value = EmitARCRetain(e->getType(), value);
2961  return value;
2962 }
2963 
2964 llvm::Value *
2966  // The retain needs to happen within the full-expression.
2967  if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
2968  enterFullExpression(cleanups);
2969  RunCleanupsScope scope(*this);
2970  return EmitARCRetainAutoreleaseScalarExpr(cleanups->getSubExpr());
2971  }
2972 
2973  TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2974  llvm::Value *value = result.getPointer();
2975  if (result.getInt())
2976  value = EmitARCAutorelease(value);
2977  else
2978  value = EmitARCRetainAutorelease(e->getType(), value);
2979  return value;
2980 }
2981 
2983  llvm::Value *result;
2984  bool doRetain;
2985 
2987  result = EmitScalarExpr(e);
2988  doRetain = true;
2989  } else {
2990  TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
2991  result = subresult.getPointer();
2992  doRetain = !subresult.getInt();
2993  }
2994 
2995  if (doRetain)
2996  result = EmitARCRetainBlock(result, /*mandatory*/ true);
2997  return EmitObjCConsumeObject(e->getType(), result);
2998 }
2999 
3001  // In ARC, retain and autorelease the expression.
3002  if (getLangOpts().ObjCAutoRefCount) {
3003  // Do so before running any cleanups for the full-expression.
3004  // EmitARCRetainAutoreleaseScalarExpr does this for us.
3006  }
3007 
3008  // Otherwise, use the normal scalar-expression emission. The
3009  // exception machinery doesn't do anything special with the
3010  // exception like retaining it, so there's no safety associated with
3011  // only running cleanups after the throw has started, and when it
3012  // matters it tends to be substantially inferior code.
3013  return EmitScalarExpr(expr);
3014 }
3015 
3016 namespace {
3017 
3018 /// An emitter for assigning into an __unsafe_unretained context.
3019 struct ARCUnsafeUnretainedExprEmitter :
3020  public ARCExprEmitter<ARCUnsafeUnretainedExprEmitter, llvm::Value*> {
3021 
3022  ARCUnsafeUnretainedExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
3023 
3024  llvm::Value *getValueOfResult(llvm::Value *value) {
3025  return value;
3026  }
3027 
3028  llvm::Value *emitBitCast(llvm::Value *value, llvm::Type *resultType) {
3029  return CGF.Builder.CreateBitCast(value, resultType);
3030  }
3031 
3032  llvm::Value *visitLValueToRValue(const Expr *e) {
3033  return CGF.EmitScalarExpr(e);
3034  }
3035 
3036  /// For consumptions, just emit the subexpression and perform the
3037  /// consumption like normal.
3038  llvm::Value *visitConsumeObject(const Expr *e) {
3039  llvm::Value *value = CGF.EmitScalarExpr(e);
3040  return CGF.EmitObjCConsumeObject(e->getType(), value);
3041  }
3042 
3043  /// No special logic for block extensions. (This probably can't
3044  /// actually happen in this emitter, though.)
3045  llvm::Value *visitExtendBlockObject(const Expr *e) {
3046  return CGF.EmitARCExtendBlockObject(e);
3047  }
3048 
3049  /// For reclaims, perform an unsafeClaim if that's enabled.
3050  llvm::Value *visitReclaimReturnedObject(const Expr *e) {
3051  return CGF.EmitARCReclaimReturnedObject(e, /*unsafe*/ true);
3052  }
3053 
3054  /// When we have an undecorated call, just emit it without adding
3055  /// the unsafeClaim.
3056  llvm::Value *visitCall(const Expr *e) {
3057  return CGF.EmitScalarExpr(e);
3058  }
3059 
3060  /// Just do normal scalar emission in the default case.
3061  llvm::Value *visitExpr(const Expr *e) {
3062  return CGF.EmitScalarExpr(e);
3063  }
3064 };
3065 }
3066 
3068  const Expr *e) {
3069  return ARCUnsafeUnretainedExprEmitter(CGF).visit(e);
3070 }
3071 
3072 /// EmitARCUnsafeUnretainedScalarExpr - Semantically equivalent to
3073 /// immediately releasing the resut of EmitARCRetainScalarExpr, but
3074 /// avoiding any spurious retains, including by performing reclaims
3075 /// with objc_unsafeClaimAutoreleasedReturnValue.
3077  // Look through full-expressions.
3078  if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3079  enterFullExpression(cleanups);
3080  RunCleanupsScope scope(*this);
3081  return emitARCUnsafeUnretainedScalarExpr(*this, cleanups->getSubExpr());
3082  }
3083 
3084  return emitARCUnsafeUnretainedScalarExpr(*this, e);
3085 }
3086 
3087 std::pair<LValue,llvm::Value*>
3089  bool ignored) {
3090  // Evaluate the RHS first. If we're ignoring the result, assume
3091  // that we can emit at an unsafe +0.
3092  llvm::Value *value;
3093  if (ignored) {
3095  } else {
3096  value = EmitScalarExpr(e->getRHS());
3097  }
3098 
3099  // Emit the LHS and perform the store.
3100  LValue lvalue = EmitLValue(e->getLHS());
3101  EmitStoreOfScalar(value, lvalue);
3102 
3103  return std::pair<LValue,llvm::Value*>(std::move(lvalue), value);
3104 }
3105 
3106 std::pair<LValue,llvm::Value*>
3108  bool ignored) {
3109  // Evaluate the RHS first.
3110  TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
3111  llvm::Value *value = result.getPointer();
3112 
3113  bool hasImmediateRetain = result.getInt();
3114 
3115  // If we didn't emit a retained object, and the l-value is of block
3116  // type, then we need to emit the block-retain immediately in case
3117  // it invalidates the l-value.
3118  if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
3119  value = EmitARCRetainBlock(value, /*mandatory*/ false);
3120  hasImmediateRetain = true;
3121  }
3122 
3123  LValue lvalue = EmitLValue(e->getLHS());
3124 
3125  // If the RHS was emitted retained, expand this.
3126  if (hasImmediateRetain) {
3127  llvm::Value *oldValue = EmitLoadOfScalar(lvalue, SourceLocation());
3128  EmitStoreOfScalar(value, lvalue);
3129  EmitARCRelease(oldValue, lvalue.isARCPreciseLifetime());
3130  } else {
3131  value = EmitARCStoreStrong(lvalue, value, ignored);
3132  }
3133 
3134  return std::pair<LValue,llvm::Value*>(lvalue, value);
3135 }
3136 
3137 std::pair<LValue,llvm::Value*>
3140  LValue lvalue = EmitLValue(e->getLHS());
3141 
3142  EmitStoreOfScalar(value, lvalue);
3143 
3144  return std::pair<LValue,llvm::Value*>(lvalue, value);
3145 }
3146 
3148  const ObjCAutoreleasePoolStmt &ARPS) {
3149  const Stmt *subStmt = ARPS.getSubStmt();
3150  const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
3151 
3152  CGDebugInfo *DI = getDebugInfo();
3153  if (DI)
3155 
3156  // Keep track of the current cleanup stack depth.
3157  RunCleanupsScope Scope(*this);
3158  if (CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
3160  EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
3161  } else {
3163  EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
3164  }
3165 
3166  for (const auto *I : S.body())
3167  EmitStmt(I);
3168 
3169  if (DI)
3171 }
3172 
3173 /// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
3174 /// make sure it survives garbage collection until this point.
3176  // We just use an inline assembly.
3177  llvm::FunctionType *extenderType
3178  = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
3179  llvm::Value *extender
3180  = llvm::InlineAsm::get(extenderType,
3181  /* assembly */ "",
3182  /* constraints */ "r",
3183  /* side effects */ true);
3184 
3185  object = Builder.CreateBitCast(object, VoidPtrTy);
3186  EmitNounwindRuntimeCall(extender, object);
3187 }
3188 
3189 /// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
3190 /// non-trivial copy assignment function, produce following helper function.
3191 /// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
3192 ///
3193 llvm::Constant *
3195  const ObjCPropertyImplDecl *PID) {
3196  if (!getLangOpts().CPlusPlus ||
3198  return nullptr;
3199  QualType Ty = PID->getPropertyIvarDecl()->getType();
3200  if (!Ty->isRecordType())
3201  return nullptr;
3202  const ObjCPropertyDecl *PD = PID->getPropertyDecl();
3204  return nullptr;
3205  llvm::Constant *HelperFn = nullptr;
3206  if (hasTrivialSetExpr(PID))
3207  return nullptr;
3208  assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
3209  if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
3210  return HelperFn;
3211 
3212  ASTContext &C = getContext();
3213  IdentifierInfo *II
3214  = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
3217  SourceLocation(),
3218  SourceLocation(), II, C.VoidTy,
3219  nullptr, SC_Static,
3220  false,
3221  false);
3222 
3223  QualType DestTy = C.getPointerType(Ty);
3224  QualType SrcTy = Ty;
3225  SrcTy.addConst();
3226  SrcTy = C.getPointerType(SrcTy);
3227 
3228  FunctionArgList args;
3229  ImplicitParamDecl DstDecl(getContext(), FD, SourceLocation(), /*Id=*/nullptr,
3230  DestTy, ImplicitParamDecl::Other);
3231  args.push_back(&DstDecl);
3232  ImplicitParamDecl SrcDecl(getContext(), FD, SourceLocation(), /*Id=*/nullptr,
3233  SrcTy, ImplicitParamDecl::Other);
3234  args.push_back(&SrcDecl);
3235 
3236  const CGFunctionInfo &FI =
3238 
3239  llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
3240 
3241  llvm::Function *Fn =
3243  "__assign_helper_atomic_property_",
3244  &CGM.getModule());
3245 
3246  CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
3247 
3248  StartFunction(FD, C.VoidTy, Fn, FI, args);
3249 
3250  DeclRefExpr DstExpr(&DstDecl, false, DestTy,
3252  UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(),
3253  VK_LValue, OK_Ordinary, SourceLocation(), false);
3254 
3255  DeclRefExpr SrcExpr(&SrcDecl, false, SrcTy,
3257  UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
3258  VK_LValue, OK_Ordinary, SourceLocation(), false);
3259 
3260  Expr *Args[2] = { &DST, &SRC };
3261  CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
3262  CXXOperatorCallExpr TheCall(C, OO_Equal, CalleeExp->getCallee(),
3263  Args, DestTy->getPointeeType(),
3265 
3266  EmitStmt(&TheCall);
3267 
3268  FinishFunction();
3269  HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
3270  CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
3271  return HelperFn;
3272 }
3273 
3274 llvm::Constant *
3276  const ObjCPropertyImplDecl *PID) {
3277  if (!getLangOpts().CPlusPlus ||
3279  return nullptr;
3280  const ObjCPropertyDecl *PD = PID->getPropertyDecl();
3281  QualType Ty = PD->getType();
3282  if (!Ty->isRecordType())
3283  return nullptr;
3285  return nullptr;
3286  llvm::Constant *HelperFn = nullptr;
3287 
3288  if (hasTrivialGetExpr(PID))
3289  return nullptr;
3290  assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
3291  if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
3292  return HelperFn;
3293 
3294 
3295  ASTContext &C = getContext();
3296  IdentifierInfo *II
3297  = &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
3300  SourceLocation(),
3301  SourceLocation(), II, C.VoidTy,
3302  nullptr, SC_Static,
3303  false,
3304  false);
3305 
3306  QualType DestTy = C.getPointerType(Ty);
3307  QualType SrcTy = Ty;
3308  SrcTy.addConst();
3309  SrcTy = C.getPointerType(SrcTy);
3310 
3311  FunctionArgList args;
3312  ImplicitParamDecl DstDecl(getContext(), FD, SourceLocation(), /*Id=*/nullptr,
3313  DestTy, ImplicitParamDecl::Other);
3314  args.push_back(&DstDecl);
3315  ImplicitParamDecl SrcDecl(getContext(), FD, SourceLocation(), /*Id=*/nullptr,
3316  SrcTy, ImplicitParamDecl::Other);
3317  args.push_back(&SrcDecl);
3318 
3319  const CGFunctionInfo &FI =
3321 
3322  llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
3323 
3324  llvm::Function *Fn =
3326  "__copy_helper_atomic_property_", &CGM.getModule());
3327 
3328  CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
3329 
3330  StartFunction(FD, C.VoidTy, Fn, FI, args);
3331 
3332  DeclRefExpr SrcExpr(&SrcDecl, false, SrcTy,
3334 
3335  UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
3336  VK_LValue, OK_Ordinary, SourceLocation(), false);
3337 
3338  CXXConstructExpr *CXXConstExpr =
3339  cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
3340 
3341  SmallVector<Expr*, 4> ConstructorArgs;
3342  ConstructorArgs.push_back(&SRC);
3343  ConstructorArgs.append(std::next(CXXConstExpr->arg_begin()),
3344  CXXConstExpr->arg_end());
3345 
3346  CXXConstructExpr *TheCXXConstructExpr =
3348  CXXConstExpr->getConstructor(),
3349  CXXConstExpr->isElidable(),
3350  ConstructorArgs,
3351  CXXConstExpr->hadMultipleCandidates(),
3352  CXXConstExpr->isListInitialization(),
3353  CXXConstExpr->isStdInitListInitialization(),
3354  CXXConstExpr->requiresZeroInitialization(),
3355  CXXConstExpr->getConstructionKind(),
3356  SourceRange());
3357 
3358  DeclRefExpr DstExpr(&DstDecl, false, DestTy,
3360 
3361  RValue DV = EmitAnyExpr(&DstExpr);
3362  CharUnits Alignment
3363  = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
3364  EmitAggExpr(TheCXXConstructExpr,
3365  AggValueSlot::forAddr(Address(DV.getScalarVal(), Alignment),
3366  Qualifiers(),
3370 
3371  FinishFunction();
3372  HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
3373  CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
3374  return HelperFn;
3375 }
3376 
3377 llvm::Value *
3379  // Get selectors for retain/autorelease.
3380  IdentifierInfo *CopyID = &getContext().Idents.get("copy");
3381  Selector CopySelector =
3383  IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
3384  Selector AutoreleaseSelector =
3385  getContext().Selectors.getNullarySelector(AutoreleaseID);
3386 
3387  // Emit calls to retain/autorelease.
3388  CGObjCRuntime &Runtime = CGM.getObjCRuntime();
3389  llvm::Value *Val = Block;
3390  RValue Result;
3391  Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3392  Ty, CopySelector,
3393  Val, CallArgList(), nullptr, nullptr);
3394  Val = Result.getScalarVal();
3395  Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3396  Ty, AutoreleaseSelector,
3397  Val, CallArgList(), nullptr, nullptr);
3398  Val = Result.getScalarVal();
3399  return Val;
3400 }
3401 
3402 llvm::Value *
3404  assert(Args.size() == 3 && "Expected 3 argument here!");
3405 
3406  if (!CGM.IsOSVersionAtLeastFn) {
3407  llvm::FunctionType *FTy =
3408  llvm::FunctionType::get(Int32Ty, {Int32Ty, Int32Ty, Int32Ty}, false);
3409  CGM.IsOSVersionAtLeastFn =
3410  CGM.CreateRuntimeFunction(FTy, "__isOSVersionAtLeast");
3411  }
3412 
3413  llvm::Value *CallRes =
3415 
3416  return Builder.CreateICmpNE(CallRes, llvm::Constant::getNullValue(Int32Ty));
3417 }
3418 
3419 void CodeGenModule::emitAtAvailableLinkGuard() {
3420  if (!IsOSVersionAtLeastFn)
3421  return;
3422  // @available requires CoreFoundation only on Darwin.
3423  if (!Target.getTriple().isOSDarwin())
3424  return;
3425  // Add -framework CoreFoundation to the linker commands. We still want to
3426  // emit the core foundation reference down below because otherwise if
3427  // CoreFoundation is not used in the code, the linker won't link the
3428  // framework.
3429  auto &Context = getLLVMContext();
3430  llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"),
3431  llvm::MDString::get(Context, "CoreFoundation")};
3432  LinkerOptionsMetadata.push_back(llvm::MDNode::get(Context, Args));
3433  // Emit a reference to a symbol from CoreFoundation to ensure that
3434  // CoreFoundation is linked into the final binary.
3435  llvm::FunctionType *FTy =
3436  llvm::FunctionType::get(Int32Ty, {VoidPtrTy}, false);
3437  llvm::Constant *CFFunc =
3438  CreateRuntimeFunction(FTy, "CFBundleGetVersionNumber");
3439 
3440  llvm::FunctionType *CheckFTy = llvm::FunctionType::get(VoidTy, {}, false);
3441  llvm::Function *CFLinkCheckFunc = cast<llvm::Function>(CreateBuiltinFunction(
3442  CheckFTy, "__clang_at_available_requires_core_foundation_framework"));
3443  CFLinkCheckFunc->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3444  CFLinkCheckFunc->setVisibility(llvm::GlobalValue::HiddenVisibility);
3445  CodeGenFunction CGF(*this);
3446  CGF.Builder.SetInsertPoint(CGF.createBasicBlock("", CFLinkCheckFunc));
3447  CGF.EmitNounwindRuntimeCall(CFFunc, llvm::Constant::getNullValue(VoidPtrTy));
3448  CGF.Builder.CreateUnreachable();
3449  addCompilerUsedGlobal(CFLinkCheckFunc);
3450 }
3451 
const CGFunctionInfo & arrangeBuiltinFunctionDeclaration(QualType resultType, const FunctionArgList &args)
A builtin function is a freestanding function using the default C conventions.
Definition: CGCall.cpp:640
const llvm::DataLayout & getDataLayout() const
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:78
The receiver is the instance of the superclass object.
Definition: ExprObjC.h:1060
ReturnValueSlot - Contains the address where the return value of a function can be stored...
Definition: CGCall.h:325
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
static bool UseOptimizedSetter(CodeGenModule &CGM)
Definition: CGObjC.cpp:1157
SourceLocation getRBracLoc() const
Definition: Stmt.h:684
Defines the clang::ASTContext interface.
bool isClassMethod() const
Definition: DeclObjC.h:457
Represents a function declaration or definition.
Definition: Decl.h:1696
llvm::Value * EmitARCStoreStrong(LValue lvalue, llvm::Value *value, bool resultIgnored)
Store into a strong object.
Definition: CGObjC.cpp:2142
The receiver is an object instance.
Definition: ExprObjC.h:1054
llvm::Value * EmitARCReclaimReturnedObject(const Expr *e, bool allowUnsafeClaim)
Definition: CGObjC.cpp:2563
Other implicit parameter.
Definition: Decl.h:1475
static llvm::Value * emitARCRetainCallResult(CodeGenFunction &CGF, const Expr *e)
Given that the given expression is some sort of call (which does not return retained), emit a retain following it.
Definition: CGObjC.cpp:2537
ObjCDictionaryElement getKeyValueElement(unsigned Index) const
Definition: ExprObjC.h:344
Smart pointer class that efficiently represents Objective-C method names.
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:1811
llvm::Value * EmitARCRetainAutoreleaseScalarExpr(const Expr *expr)
Definition: CGObjC.cpp:2965
static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl)
Definition: CGObjC.cpp:824
CanQualType VoidPtrTy
Definition: ASTContext.h:1012
Destroyer * getDestroyer(QualType::DestructionKind destructionKind)
Definition: CGDecl.cpp:1518
A (possibly-)qualified type.
Definition: Type.h:653
bool isBlockPointerType() const
Definition: Type.h:5956
static bool hasUnalignedAtomics(llvm::Triple::ArchType arch)
Determine whether the given architecture supports unaligned atomic accesses.
Definition: CGObjC.cpp:615
void EmitExtendGCLifetime(llvm::Value *object)
EmitExtendGCLifetime - Given a pointer to an Objective-C object, make sure it survives garbage collec...
Definition: CGObjC.cpp:3175
const CodeGenOptions & getCodeGenOpts() const
Selector getSelector() const
Definition: ExprObjC.cpp:312
llvm::Value * EmitARCExtendBlockObject(const Expr *expr)
Definition: CGObjC.cpp:2982
ObjCInterfaceDecl * getClassInterface()
Definition: DeclObjC.cpp:1101
virtual llvm::Function * GenerateMethod(const ObjCMethodDecl *OMD, const ObjCContainerDecl *CD)=0
Generate a function preamble for a method with the specified types.
ObjCIvarDecl * getPropertyIvarDecl() const
Definition: DeclObjC.h:2846
static AggValueSlot forLValue(const LValue &LV, IsDestructed_t isDestructed, NeedsGCBarriers_t needsGC, IsAliased_t isAliased, IsZeroed_t isZeroed=IsNotZeroed)
Definition: CGValue.h:517
void EmitARCDestroyWeak(Address addr)
void @objc_destroyWeak(i8** addr) Essentially objc_storeWeak(addr, nil).
Definition: CGObjC.cpp:2278
ObjCProtocolDecl * getProtocol() const
Definition: ExprObjC.h:490
Stmt - This represents one statement.
Definition: Stmt.h:66
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.
void EmitLexicalBlockEnd(CGBuilderTy &Builder, SourceLocation Loc)
Emit metadata to indicate the end of a new lexical block and pop the current block.
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:456
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:790
bool requiresCleanups() const
Determine whether this scope requires any cleanups.
Implements runtime-specific code generation functions.
Definition: CGObjCRuntime.h:63
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:820
bool isRecordType() const
Definition: Type.h:6021
static RValue AdjustObjCObjectType(CodeGenFunction &CGF, QualType ET, RValue Result)
Adjust the type of an Objective-C object that doesn&#39;t match up due to type erasure at various points...
Definition: CGObjC.cpp:265
llvm::Constant * objc_autoreleaseReturnValue
id objc_autoreleaseReturnValue(id);
const Decl * CurCodeDecl
CurCodeDecl - This is the inner-most code context, which includes blocks.
Opcode getOpcode() const
Definition: Expr.h:3039
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:5897
Expr * getSetterCXXAssignment() const
Definition: DeclObjC.h:2876
static Destroyer destroyARCStrongPrecise
Represents Objective-C&#39;s @throw statement.
Definition: StmtObjC.h:313
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:1840
void GenerateObjCSetter(ObjCImplementationDecl *IMP, const ObjCPropertyImplDecl *PID)
GenerateObjCSetter - Synthesize an Objective-C property setter function for the given property...
Definition: CGObjC.cpp:1342
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1239
const ObjCObjectPointerType * getAsObjCInterfacePointerType() const
Definition: Type.cpp:1567
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:116
QualType withConst() const
Definition: Type.h:823
llvm::Constant * objc_loadWeakRetained
id objc_loadWeakRetained(id*);
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
void EmitARCCopyWeak(Address dst, Address src)
void @objc_copyWeak(i8** dest, i8** src) Disregards the current value in dest.
Definition: CGObjC.cpp:2304
llvm::Value * EmitObjCMRRAutoreleasePoolPush()
Produce the code to do an MRR version objc_autoreleasepool_push.
Definition: CGObjC.cpp:2347
Floating point control options.
Definition: LangOptions.h:225
llvm::Constant * GenerateObjCAtomicSetterCopyHelperFunction(const ObjCPropertyImplDecl *PID)
GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with non-trivial copy assignment...
Definition: CGObjC.cpp:3194
llvm::Value * EmitARCRetainNonBlock(llvm::Value *value)
Retain the given object, with normal retain semantics.
Definition: CGObjC.cpp:1963
static llvm::Value * emitARCRetainLoadOfScalar(CodeGenFunction &CGF, LValue lvalue, QualType type)
Definition: CGObjC.cpp:2935
param_const_iterator param_end() const
Definition: DeclObjC.h:390
void createImplicitParams(ASTContext &Context, const ObjCInterfaceDecl *ID)
createImplicitParams - Used to lazily create the self and cmd implict parameters. ...
Definition: DeclObjC.cpp:1080
llvm::function_ref< llvm::Value *(CodeGenFunction &CGF, llvm::Value *value)> ValueTransform
Definition: CGObjC.cpp:2491
Address GetAddrOfLocalVar(const VarDecl *VD)
GetAddrOfLocalVar - Return the address of a local variable.
RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, ReturnValueSlot ReturnValue, const CallArgList &Args, llvm::Instruction **callOrInvoke, SourceLocation Loc)
EmitCall - Generate a call of the given function, expecting the given result type, and using the given argument list which specifies both the LLVM arguments and the types they were derived from.
Definition: CGCall.cpp:3683
Represents a variable declaration or definition.
Definition: Decl.h:812
Objects with "hidden" visibility are not seen by the dynamic linker.
Definition: Visibility.h:35
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6317
bool hasPointerRepresentation() const
Whether this type is represented natively as a pointer.
Definition: Type.h:6266
virtual StringRef getARCRetainAutoreleasedReturnValueMarker() const
Retrieve the address of a function to call immediately before calling objc_retainAutoreleasedReturnVa...
Definition: TargetInfo.h:156
SourceLocation getLocStart() const LLVM_READONLY
Definition: DeclObjC.h:321
uint64_t getProfileCount(const Stmt *S)
Get the profiler&#39;s count for the given statement.
llvm::Value * EmitObjCAutoreleasePoolPush()
Produce the code to do a objc_autoreleasepool_push.
Definition: CGObjC.cpp:2312
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
Definition: CGDebugInfo.h:54
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:139
llvm::Value * EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty)
Definition: CGObjC.cpp:3378
llvm::Value * getPointer() const
Definition: Address.h:38
llvm::Constant * getAtomicSetterHelperFnMap(QualType Ty)
Defines the Objective-C statement AST node classes.
Represents an expression – generally a full-expression – that introduces cleanups to be run at the ...
Definition: ExprCXX.h:3003
Represents a parameter to a function.
Definition: Decl.h:1515
llvm::Value * EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E)
Definition: CGObjC.cpp:243
The collection of all-type qualifiers we support.
Definition: Type.h:152
virtual llvm::Constant * GetOptimizedPropertySetFunction(bool atomic, bool copy)=0
Return the runtime function for optimized setting properties.
A jump destination is an abstract label, branching to which may require a jump out through normal cle...
bool isARCPseudoStrong() const
Determine whether this variable is an ARC pseudo-__strong variable.
Definition: Decl.h:1341
llvm::Value * EmitObjCThrowOperand(const Expr *expr)
Definition: CGObjC.cpp:3000
bool isXValue() const
Definition: Expr.h:251
const Stmt * getSubStmt() const
Definition: StmtObjC.h:356
const AstTypeMatcher< RecordType > recordType
Matches record types (e.g.
llvm::Constant * objc_autorelease
id objc_autorelease(id);
llvm::Constant * objc_copyWeak
void objc_copyWeak(id *dest, id *src);
llvm::Constant * getAtomicGetterHelperFnMap(QualType Ty)
One of these records is kept for each identifier that is lexed.
void emitDestroy(Address addr, QualType type, Destroyer *destroyer, bool useEHCleanupForArray)
emitDestroy - Immediately perform the destruction of the given object.
Definition: CGDecl.cpp:1594
Address getAddress() const
Definition: CGValue.h:324
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
Expr * getGetterCXXConstructor() const
Definition: DeclObjC.h:2868
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:583
Represents a class type in Objective C.
Definition: Type.h:5190
llvm::Constant * objc_loadWeak
id objc_loadWeak(id*);
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:149
const ParmVarDecl *const * param_const_iterator
Definition: DeclObjC.h:381
std::pair< LValue, llvm::Value * > EmitARCStoreAutoreleasing(const BinaryOperator *e)
Definition: CGObjC.cpp:3138
llvm::Constant * objc_retainAutoreleasedReturnValue
id objc_retainAutoreleasedReturnValue(id);
llvm::Value * EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr)
Definition: CGObjC.cpp:1797
bool hasOptimizedSetter() const
Does this runtime supports optimized setter entrypoints?
Definition: ObjCRuntime.h:175
static CXXConstructExpr * Create(const ASTContext &C, QualType T, SourceLocation Loc, CXXConstructorDecl *Ctor, bool Elidable, ArrayRef< Expr *> Args, bool HadMultipleCandidates, bool ListInitialization, bool StdInitListInitialization, bool ZeroInitialization, ConstructionKind ConstructKind, SourceRange ParenOrBraceRange)
Definition: ExprCXX.cpp:791
SetterKind getSetterKind() const
getSetterKind - Return the method used for doing assignment in the property setter.
Definition: DeclObjC.h:911
llvm::Value * EmitARCRetainAutoreleaseReturnValue(llvm::Value *value)
Do a fused retain/autorelease of the given object.
Definition: CGObjC.cpp:2196
Represents a member of a struct/union/class.
Definition: Decl.h:2488
CharUnits getAlignment() const
Definition: CGValue.h:313
StringLiteral * getString()
Definition: ExprObjC.h:63
bool isReferenceType() const
Definition: Type.h:5960
ObjCMethodDecl * getSetterMethodDecl() const
Definition: DeclObjC.h:942
Denotes a cleanup that should run when a scope is exited using exceptional control flow (a throw stat...
Definition: EHScopeStack.h:81
Token - This structure provides full information about a lexed token.
Definition: Token.h:35
llvm::Value * EmitARCAutoreleaseReturnValue(llvm::Value *value)
Autorelease the given object.
Definition: CGObjC.cpp:2186
void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP, ObjCMethodDecl *MD, bool ctor)
Definition: CGObjC.cpp:1423
Expr * getSubExpr()
Definition: Expr.h:2774
virtual llvm::Constant * GetPropertySetFunction()=0
Return the runtime function for setting properties.
CleanupKind getCleanupKind(QualType::DestructionKind kind)
ObjCArrayLiteral - used for objective-c array containers; as in: @["Hello", NSApp, [NSNumber numberWithInt:42]];.
Definition: ExprObjC.h:171
llvm::Value * EmitObjCBoxedExpr(const ObjCBoxedExpr *E)
EmitObjCBoxedExpr - This routine generates code to call the appropriate expression boxing method...
Definition: CGObjC.cpp:60
IdentifierTable & Idents
Definition: ASTContext.h:537
An r-value expression (a pr-value in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:107
Selector getSelector() const
Definition: ExprObjC.h:442
void EmitStoreOfScalar(llvm::Value *Value, Address Addr, bool Volatile, QualType Ty, AlignmentSource Source=AlignmentSource::Type, bool isInit=false, bool isNontemporal=false)
EmitStoreOfScalar - Store a scalar value to an address, taking care to appropriately convert from the...
ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc)
EmitLoadOfComplex - Load a complex number from the specified l-value.
const Expr *const * const_semantics_iterator
Definition: Expr.h:5049
bool isUnarySelector() const
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...
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:173
bool isGLValue() const
Definition: Expr.h:252
ObjCMethodFamily getMethodFamily() const
Determines the family of this method.
Definition: DeclObjC.cpp:943
llvm::Value * EmitARCStoreStrongCall(Address addr, llvm::Value *value, bool resultIgnored)
Store into a strong object.
Definition: CGObjC.cpp:2116
ARCPreciseLifetime_t isARCPreciseLifetime() const
Definition: CGValue.h:282
llvm::Constant * objc_initWeak
id objc_initWeak(id*, id);
llvm::Value * EmitObjCStringLiteral(const ObjCStringLiteral *E)
Emits an instance of NSConstantString representing the object.
Definition: CGObjC.cpp:46
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:2566
Selector getNullarySelector(IdentifierInfo *ID)
ObjCContainerDecl - Represents a container for method declarations.
Definition: DeclObjC.h:986
Address CreateElementBitCast(Address Addr, llvm::Type *Ty, const llvm::Twine &Name="")
Cast the element type of the given address to a different type, preserving information like the align...
Definition: CGBuilder.h:157
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
void EmitARCDestroyStrong(Address addr, ARCPreciseLifetime_t precise)
Destroy a __strong variable.
Definition: CGObjC.cpp:2102
static llvm::Value * emitARCUnsafeClaimCallResult(CodeGenFunction &CGF, const Expr *e)
Given that the given expression is some sort of call (which does not return retained), perform an unsafeClaim following it.
Definition: CGObjC.cpp:2551
Qualifiers::GC getObjCGCAttrKind(QualType Ty) const
Return one of the GCNone, Weak or Strong Objective-C garbage collection attributes.
SourceLocation getLBracLoc() const
Definition: Stmt.h:683
PropertyAttributeKind getPropertyAttributes() const
Definition: DeclObjC.h:857
semantics_iterator semantics_end()
Definition: Expr.h:5056
llvm::Constant * objc_release
void objc_release(id);
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:2998
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:5794
llvm::Value * EmitARCUnsafeUnretainedScalarExpr(const Expr *expr)
EmitARCUnsafeUnretainedScalarExpr - Semantically equivalent to immediately releasing the resut of Emi...
Definition: CGObjC.cpp:3076
void setAtomicGetterHelperFnMap(QualType Ty, llvm::Constant *Fn)
Defines the Diagnostic-related interfaces.
llvm::Value * EmitARCLoadWeak(Address addr)
i8* @objc_loadWeak(i8** addr) Essentially objc_autorelease(objc_loadWeakRetained(addr)).
Definition: CGObjC.cpp:2233
ObjCStringLiteral, used for Objective-C string literals i.e.
Definition: ExprObjC.h:51
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:39
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
llvm::Value * EmitARCRetainScalarExpr(const Expr *expr)
EmitARCRetainScalarExpr - Semantically equivalent to EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a best-effort attempt to peephole expressions that naturally produce retained objects.
Definition: CGObjC.cpp:2949
void EmitIgnoredExpr(const Expr *E)
EmitIgnoredExpr - Emit an expression in a context which ignores the result.
Definition: CGExpr.cpp:161
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:2577
Denotes a cleanup that should run when a scope is exited using normal control flow (falling off the e...
Definition: EHScopeStack.h:85
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:2723
void ForceCleanup(std::initializer_list< llvm::Value **> ValuesToReload={})
Force the emission of cleanups now, instead of waiting until this object is destroyed.
llvm::Constant * CreateRuntimeVariable(llvm::Type *Ty, StringRef Name)
Create a new runtime global variable with the specified type and name.
Expr * Key
The key for the dictionary element.
Definition: ExprObjC.h:241
ObjCMethodDecl * getArrayWithObjectsMethod() const
Definition: ExprObjC.h:222
virtual llvm::Constant * GetGetStructFunction()=0
GlobalDecl CurGD
CurGD - The GlobalDecl for the current function being compiled.
An ordinary object is located at an address in memory.
Definition: Specifiers.h:123
void incrementProfileCounter(const Stmt *S, llvm::Value *StepV=nullptr)
Increment the profiler&#39;s counter for the given statement by StepV.
uint64_t getCurrentProfileCount()
Get the profiler&#39;s current count.
Represents an ObjC class declaration.
Definition: DeclObjC.h:1191
SourceLocation getLocEnd() const LLVM_READONLY
Definition: DeclObjC.cpp:937
QualType getReturnType() const
Definition: DeclObjC.h:361
ObjCInterfaceDecl * getInterface() const
Gets the interface declaration for this object type, if the base type really is an interface...
Definition: Type.h:5425
static llvm::Constant * createARCRuntimeFunction(CodeGenModule &CGM, llvm::FunctionType *FTy, StringRef Name)
Definition: CGObjC.cpp:1818
static TryEmitResult tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e)
Definition: CGObjC.cpp:2931
bool isAtomic() const
isAtomic - Return true if the property is atomic.
Definition: DeclObjC.h:885
llvm::Value * EmitARCRetainAutoreleasedReturnValue(llvm::Value *value)
Retain the given object which is the result of a function call.
Definition: CGObjC.cpp:2046
static FunctionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation NLoc, DeclarationName N, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool isInlineSpecified=false, bool hasWrittenPrototype=true, bool isConstexprSpecified=false)
Definition: Decl.h:1891
llvm::Value * EmitARCRetainAutoreleaseNonBlock(llvm::Value *value)
Do a fused retain/autorelease of the given object.
Definition: CGObjC.cpp:2225
This object can be modified without requiring retains or releases.
Definition: Type.h:173
ObjCMethodDecl * getDictWithObjectsMethod() const
Definition: ExprObjC.h:358
llvm::Constant * CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList(), bool Local=false)
Create a new runtime function with the specified type and name.
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...
ObjCPropertyImplDecl - Represents implementation declaration of a property in a class or category imp...
Definition: DeclObjC.h:2778
RValue EmitObjCMessageExpr(const ObjCMessageExpr *E, ReturnValueSlot Return=ReturnValueSlot())
Definition: CGObjC.cpp:355
bool hasAttr() const
Definition: DeclBase.h:535
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:595
AutoVarEmission EmitAutoVarAlloca(const VarDecl &var)
EmitAutoVarAlloca - Emit the alloca and debug information for a local variable.
Definition: CGDecl.cpp:1015
std::pair< llvm::Value *, llvm::Value * > ComplexPairTy
llvm::CallInst * EmitNounwindRuntimeCall(llvm::Value *callee, const Twine &name="")
const TargetCodeGenInfo & getTargetCodeGenInfo()
void EmitAnyExprToMem(const Expr *E, Address Location, Qualifiers Quals, bool IsInitializer)
EmitAnyExprToMem - Emits the code necessary to evaluate an arbitrary expression into the given memory...
Definition: CGExpr.cpp:202
llvm::Constant * objc_storeStrong
void objc_storeStrong(id*, id);
CastKind
CastKind - The kind of operation required for a conversion.
RValue - This trivial value class is used to represent the result of an expression that is evaluated...
Definition: CGValue.h:39
CleanupKind getARCCleanupKind()
Retrieves the default cleanup kind for an ARC cleanup.
llvm::Value * EmitARCStoreWeak(Address addr, llvm::Value *value, bool ignored)
i8* @objc_storeWeak(i8** addr, i8* value) Returns value.
Definition: CGObjC.cpp:2248
static TypeEvaluationKind getEvaluationKind(QualType T)
getEvaluationKind - Return the TypeEvaluationKind of QualType T.
CGObjCRuntime & getObjCRuntime()
Return a reference to the configured Objective-C runtime.
ObjCMethodDecl * getBoxingMethod() const
Definition: ExprObjC.h:138
static bool shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message)
Decide whether to extend the lifetime of the receiver of a returns-inner-pointer message.
Definition: CGObjC.cpp:283
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:636
Expr - This represents one expression.
Definition: Expr.h:106
bool hasAtomicCopyHelper() const
Definition: ObjCRuntime.h:298
llvm::Constant * objc_autoreleasePoolPop
void objc_autoreleasePoolPop(void*);
void EmitARCMoveWeak(Address dst, Address src)
void @objc_moveWeak(i8** dest, i8** src) Disregards the current value in dest.
Definition: CGObjC.cpp:2295
virtual llvm::Constant * GetSetStructFunction()=0
void EmitAutoVarInit(const AutoVarEmission &emission)
Definition: CGDecl.cpp:1267
static Address invalid()
Definition: Address.h:35
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1030
Enters a new scope for capturing cleanups, all of which will be executed once the scope is exited...
void GenerateObjCMethod(const ObjCMethodDecl *OMD)
Generate an Objective-C method.
Definition: CGObjC.cpp:572
void EmitCallArgs(CallArgList &Args, const T *CallArgTypeInfo, llvm::iterator_range< CallExpr::const_arg_iterator > ArgRange, AbstractCallee AC=AbstractCallee(), unsigned ParamsToSkip=0, EvaluationOrder Order=EvaluationOrder::Default)
EmitCallArgs - Emit call arguments for a function.
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:1055
void SetInternalFunctionAttributes(const Decl *D, llvm::Function *F, const CGFunctionInfo &FI)
Set the attributes on the LLVM function for the given decl and function info.
static CGCallee forDirect(llvm::Constant *functionPtr, const CGCalleeInfo &abstractInfo=CGCalleeInfo())
Definition: CGCall.h:134
bool isObjCRetainableType() const
Definition: Type.cpp:3825
virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtThrowStmt &S, bool ClearInsertionPoint=true)=0
llvm::Constant * objc_retain
id objc_retain(id);
const Expr * getCallee() const
Definition: Expr.h:2258
llvm::PointerType * getType() const
Return the type of the pointer value.
Definition: Address.h:44
ObjCLifetime getObjCLifetime() const
Definition: Type.h:341
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
ObjCDictionaryLiteral - AST node to represent objective-c dictionary literals; as in:"name" : NSUserN...
Definition: ExprObjC.h:288
DeclContext * getDeclContext()
Definition: DeclBase.h:425
Represents Objective-C&#39;s @synchronized statement.
Definition: StmtObjC.h:262
ObjCSelectorExpr used for @selector in Objective-C.
Definition: ExprObjC.h:429
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:63
void generateObjCSetterBody(const ObjCImplementationDecl *classImpl, const ObjCPropertyImplDecl *propImpl, llvm::Constant *AtomicHelperFn)
Definition: CGObjC.cpp:1164
void add(RValue rvalue, QualType type, bool needscopy=false)
Definition: CGCall.h:251
virtual void EmitTryStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtTryStmt &S)=0
llvm::Value * EmitARCAutorelease(llvm::Value *value)
Autorelease the given object.
Definition: CGObjC.cpp:2177
llvm::LLVMContext & getLLVMContext()
const CGFunctionInfo & arrangeBuiltinFunctionCall(QualType resultType, const CallArgList &args)
Definition: CGCall.cpp:627
QualType getType() const
Definition: Expr.h:128
virtual llvm::Value * GetSelector(CodeGenFunction &CGF, Selector Sel)=0
Get a selector for the specified name and type values.
Expr * getElement(unsigned Index)
getElement - Return the Element at the specified index.
Definition: ExprObjC.h:213
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:134
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type...
virtual llvm::Constant * GetPropertyGetFunction()=0
Return the runtime function for getting properties.
ReturnStmt - This represents a return, optionally of an expression: return; return 4;...
Definition: Stmt.h:1417
LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T)
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:903
SourceLocation getEnd() const
UnaryOperator - This represents the unary-expression&#39;s (except sizeof and alignof), the postinc/postdec operators from postfix-expression, and various extensions.
Definition: Expr.h:1717
bool isInstanceMethod() const
Definition: DeclObjC.h:452
ReceiverKind getReceiverKind() const
Determine the kind of receiver that this message is being sent to.
Definition: ExprObjC.h:1187
const TargetInfo & getTarget() const
ValueDecl * getDecl()
Definition: Expr.h:1041
const Qualifiers & getQuals() const
Definition: CGValue.h:308
Selector getSelector() const
Definition: DeclObjC.h:359
const LangOptions & getLangOpts() const
ASTContext & getContext() const
ImplicitParamDecl * getSelfDecl() const
Definition: DeclObjC.h:444
bool hasEmptyCollections() const
Are the empty collection symbols available?
Definition: ObjCRuntime.h:330
static AggValueSlot forAddr(Address addr, Qualifiers quals, IsDestructed_t isDestructed, NeedsGCBarriers_t needsGC, IsAliased_t isAliased, IsZeroed_t isZeroed=IsNotZeroed)
forAddr - Make a slot for an aggregate value.
Definition: CGValue.h:495
QualType getType() const
Definition: DeclObjC.h:846
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:35
static llvm::Value * emitARCStoreOperation(CodeGenFunction &CGF, Address addr, llvm::Value *value, llvm::Constant *&fn, StringRef fnName, bool ignored)
Perform an operation having the following signature: i8* (i8**, i8*)
Definition: CGObjC.cpp:1898
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:5783
virtual void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtSynchronizedStmt &S)=0
The l-value was considered opaque, so the alignment was determined from a type.
llvm::Constant * objc_retainBlock
id objc_retainBlock(id);
There is no lifetime qualification on this type.
Definition: Type.h:169
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class...
Definition: Expr.h:868
Address CreateBitCast(Address Addr, llvm::Type *Ty, const llvm::Twine &Name="")
Definition: CGBuilder.h:142
SelectorTable & Selectors
Definition: ASTContext.h:538
Assigning into this object requires the old value to be released and the new value to be retained...
Definition: Type.h:180
Kind
QualType getCanonicalType() const
Definition: Type.h:5763
llvm::Constant * objc_storeWeak
id objc_storeWeak(id*, id);
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:4982
IdentifierInfo * getIdentifierInfoForSlot(unsigned argIndex) const
Retrieve the identifier at a given position in the selector.
static llvm::Value * emitARCUnsafeUnretainedScalarExpr(CodeGenFunction &CGF, const Expr *e)
Definition: CGObjC.cpp:3067
Encodes a location in the source.
void EnsureInsertPoint()
EnsureInsertPoint - Ensure that an insertion point is defined so that emitted IR has a place to go...
llvm::Value * EmitObjCArrayLiteral(const ObjCArrayLiteral *E)
Definition: CGObjC.cpp:239
body_range body()
Definition: Stmt.h:626
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF, llvm::Value *returnAddr, ObjCIvarDecl *ivar, llvm::Constant *AtomicHelperFn)
emitCPPObjectAtomicGetterCall - Call the runtime function to copy the ivar into the resturn slot...
Definition: CGObjC.cpp:849
void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise)
Release the given object.
Definition: CGObjC.cpp:2070
LValue EmitDeclRefLValue(const DeclRefExpr *E)
Definition: CGExpr.cpp:2350
std::pair< LValue, llvm::Value * > EmitARCStoreUnsafeUnretained(const BinaryOperator *e, bool ignored)
Definition: CGObjC.cpp:3088
virtual ConstantAddress GenerateConstantString(const StringLiteral *)=0
Generate a constant string object.
LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK)
Same as EmitLValue but additionally we generate checking code to guard against undefined behavior...
Definition: CGExpr.cpp:1138
CastKind getCastKind() const
Definition: Expr.h:2770
llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee, ArrayRef< llvm::Value *> args, const Twine &name="")
Emits a call or invoke instruction to the given runtime function.
Definition: CGCall.cpp:3632
unsigned getNumElements() const
getNumElements - Return number of elements of objective-c dictionary literal.
Definition: ExprObjC.h:342
void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S)
Definition: CGObjC.cpp:1473
llvm::Value * EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value)
Claim a possibly-autoreleased return value at +0.
Definition: CGObjC.cpp:2061
DeclStmt - Adaptor class for mixing declarations with statements and expressions. ...
Definition: Stmt.h:487
void EmitAggregateCopy(LValue Dest, LValue Src, QualType EltTy, bool isVolatile=false, bool isAssignment=false)
EmitAggregateCopy - Emit an aggregate copy.
Definition: CGExprAgg.cpp:1546
Stmt * getBody() const override
Retrieve the body of this method, if it has one.
Definition: DeclObjC.cpp:806
llvm::Constant * objc_autoreleasePoolPush
void *objc_autoreleasePoolPush(void);
static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF, LValue lvalue, QualType type)
Definition: CGObjC.cpp:2432
const CGFunctionInfo & arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD)
Objective-C methods are C functions with some implicit parameters.
Definition: CGCall.cpp:442
void EmitStmt(const Stmt *S, ArrayRef< const Attr *> Attrs=None)
EmitStmt - Emit the code for the statement.
Definition: CGStmt.cpp:48
virtual llvm::Value * EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF)
ObjCEntrypoints & getObjCEntrypoints() const
CanQualType VoidTy
Definition: ASTContext.h:996
ObjCProtocolExpr used for protocol expression in Objective-C.
Definition: ExprObjC.h:474
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.
llvm::InlineAsm * retainAutoreleasedReturnValueMarker
A void(void) inline asm to use to mark that the return value of a call will be immediately retain...
An aligned address.
Definition: Address.h:25
void StartFunction(GlobalDecl GD, QualType RetTy, llvm::Function *Fn, const CGFunctionInfo &FnInfo, const FunctionArgList &Args, SourceLocation Loc=SourceLocation(), SourceLocation StartLoc=SourceLocation())
Emit code for the start of a function.
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:746
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:2835
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after...
Definition: Type.h:1101
All available information about a concrete callee.
Definition: CGCall.h:67
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...
Expr * getSubExpr()
Definition: ExprObjC.h:135
const ObjCMethodDecl * getMethodDecl() const
Definition: ExprObjC.h:1302
static void destroyARCStrongWithStore(CodeGenFunction &CGF, Address addr, QualType type)
Like CodeGenFunction::destroyARCStrong, but do it with a call.
Definition: CGObjC.cpp:1380
Assigning into this object requires a lifetime extension.
Definition: Type.h:186
QualType getType() const
Definition: CGValue.h:261
ObjCBoxedExpr - used for generalized expression boxing.
Definition: ExprObjC.h:117
virtual llvm::Constant * GetCppAtomicObjectGetFunction()=0
API for atomic copying of qualified aggregates with non-trivial copy assignment (c++) in getter...
llvm::Value * EmitARCRetain(QualType type, llvm::Value *value)
Produce the code to do a retain.
Definition: CGObjC.cpp:1954
void enterFullExpression(const ExprWithCleanups *E)
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2225
static Destroyer destroyARCStrongImprecise
void FinishFunction(SourceLocation EndLoc=SourceLocation())
FinishFunction - Complete IR generation of the current function.
Expr * Value
The value of the dictionary element.
Definition: ExprObjC.h:244
std::pair< CharUnits, CharUnits > getTypeInfoInChars(const Type *T) const
ConstantAddress GetAddrOfConstantCString(const std::string &Str, const char *GlobalName=nullptr)
Returns a pointer to a character array containing the literal and a terminating &#39;\0&#39; character...
Expr * getLHS() const
Definition: Expr.h:3042
void EmitObjCMRRAutoreleasePoolPop(llvm::Value *Ptr)
Produce the code to do a primitive release.
Definition: CGObjC.cpp:2372
llvm::Value * EmitScalarExpr(const Expr *E, bool IgnoreResultAssign=false)
EmitScalarExpr - Emit the computation of the specified expression of LLVM scalar type, returning the result.
Expr * getInstanceReceiver()
Returns the object expression (receiver) for an instance message, or null for a message that is not a...
Definition: ExprObjC.h:1206
FunctionArgList - Type for representing both the decl and type of parameters to a function...
Definition: CGCall.h:320
ObjCIvarDecl * getNextIvar()
Definition: DeclObjC.h:1997
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
Definition: CGValue.h:59
Expr * getResultExpr()
Return the result-bearing expression, or null if there is none.
Definition: Expr.h:5037
void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S)
Definition: CGObjC.cpp:1770
void ErrorUnsupported(const Stmt *S, const char *Type)
Print out an error that codegen doesn&#39;t support the specified stmt yet.
CGFunctionInfo - Class to encapsulate the information about a function definition.
This class organizes the cross-function state that is used while generating LLVM code.
llvm::Constant * objc_unsafeClaimAutoreleasedReturnValue
id objc_unsafeClaimAutoreleasedReturnValue(id);
const ObjCInterfaceDecl * getClassInterface() const
Definition: DeclObjC.h:2459
Dataflow Directional Tag Classes.
static llvm::Value * emitARCValueOperation(CodeGenFunction &CGF, llvm::Value *value, llvm::Constant *&fn, StringRef fnName, bool isTailCall=false)
Perform an operation having the signature i8* (i8*) where a null input causes a no-op and returns nul...
Definition: CGObjC.cpp:1843
void GenerateObjCGetter(ObjCImplementationDecl *IMP, const ObjCPropertyImplDecl *PID)
GenerateObjCGetter - Synthesize an Objective-C property getter function.
Definition: CGObjC.cpp:810
void EmitObjCAutoreleasePoolPop(llvm::Value *Ptr)
Produce the code to do a primitive release.
Definition: CGObjC.cpp:2325
The basic abstraction for the target Objective-C runtime.
Definition: ObjCRuntime.h:25
llvm::Value * EmitARCLoadWeakRetained(Address addr)
i8* @objc_loadWeakRetained(i8** addr)
Definition: CGObjC.cpp:2240
Address CreateStructGEP(Address Addr, unsigned Index, CharUnits Offset, const llvm::Twine &Name="")
Definition: CGBuilder.h:172
QualType getSuperType() const
Retrieve the type referred to by &#39;super&#39;.
Definition: ExprObjC.h:1282
llvm::LoadInst * CreateAlignedLoad(llvm::Value *Addr, CharUnits Align, const llvm::Twine &Name="")
Definition: CGBuilder.h:91
void EmitARCIntrinsicUse(ArrayRef< llvm::Value *> values)
Given a number of pointers, inform the optimizer that they&#39;re being intrinsically used up until this ...
Definition: CGObjC.cpp:1804
llvm::Constant * getPointer() const
Definition: Address.h:84
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
Definition: CGBuilder.h:70
llvm::Constant * objc_destroyWeak
void objc_destroyWeak(id*);
U cast(CodeGen::Address addr)
Definition: Address.h:109
llvm::Constant * clang_arc_use
void clang.arc.use(...);
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:5487
QualType TypeOfSelfObject()
TypeOfSelfObject - Return type of object that this self represents.
Definition: CGObjC.cpp:1465
Checking the destination of a store. Must be suitably sized and aligned.
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
Definition: CGBuilder.h:108
semantics_iterator semantics_begin()
Definition: Expr.h:5050
llvm::Constant * GenerateObjCAtomicGetterCopyHelperFunction(const ObjCPropertyImplDecl *PID)
Definition: CGObjC.cpp:3275
llvm::Module & getModule() const
static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID)
Definition: CGObjC.cpp:1133
void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S)
Definition: CGObjC.cpp:1766
LValue MakeAddrLValue(Address Addr, QualType T, AlignmentSource Source=AlignmentSource::Type)
static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM, llvm::Triple::ArchType arch)
Return the maximum size that permits atomic accesses for the given architecture.
Definition: CGObjC.cpp:623
void EmitAggExpr(const Expr *E, AggValueSlot AS)
EmitAggExpr - Emit the computation of the specified expression of aggregate type. ...
Definition: CGExprAgg.cpp:1524
QualType getClassReceiver() const
Returns the type of a class message send, or NULL if the message is not a class message.
Definition: ExprObjC.h:1225
Represents a pointer to an Objective C object.
Definition: Type.h:5446
void EmitAutoVarCleanups(const AutoVarEmission &emission)
Definition: CGDecl.cpp:1478
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2571
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:3982
static llvm::Value * emitARCOperationAfterCall(CodeGenFunction &CGF, llvm::Value *value, ValueTransform doAfterCall, ValueTransform doFallback)
Insert code immediately after a call.
Definition: CGObjC.cpp:2494
virtual llvm::Constant * EnumerationMutationFunction()=0
EnumerationMutationFunction - Return the function that&#39;s called by the compiler when a mutation is de...
unsigned getNumElements() const
getNumElements - Return number of elements of objective-c array literal.
Definition: ExprObjC.h:210
Represents Objective-C&#39;s collection statement.
Definition: StmtObjC.h:24
CodeGenTypes & getTypes() const
Address CreateConstArrayGEP(Address Addr, uint64_t Index, CharUnits EltSize, const llvm::Twine &Name="")
Given addr = [n x T]* ...
Definition: CGBuilder.h:195
void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit)
EmitStoreOfComplex - Store a complex number into the specified l-value.
static void emitARCCopyOperation(CodeGenFunction &CGF, Address dst, Address src, llvm::Constant *&fn, StringRef fnName)
Perform an operation having the following signature: void (i8**, i8**)
Definition: CGObjC.cpp:1929
bool hasNonTrivialObjCLifetime() const
Definition: Type.h:1079
Selector getSelector(unsigned NumArgs, IdentifierInfo **IIV)
Can create any sort of selector.
llvm::Type * getElementType() const
Return the type of the values stored in this address.
Definition: Address.h:52
This class organizes the cross-module state that is used while lowering AST types to LLVM types...
Definition: CodeGenTypes.h:120
void getObjCEncodingForType(QualType T, std::string &S, const FieldDecl *Field=nullptr, QualType *NotEncodedT=nullptr) const
Emit the Objective-CC type encoding for the given type T into S.
bool isDelegateInitCall() const
isDelegateInitCall - Answers whether this message send has been tagged as a "delegate init call"...
Definition: ExprObjC.h:1359
LValue EmitLValueForIvar(QualType ObjectTy, llvm::Value *Base, const ObjCIvarDecl *Ivar, unsigned CVRQualifiers)
Definition: CGExpr.cpp:4424
llvm::Constant * objc_retainAutorelease
id objc_retainAutorelease(id);
param_const_iterator param_begin() const
Definition: DeclObjC.h:386
llvm::Value * EmitIvarOffset(const ObjCInterfaceDecl *Interface, const ObjCIvarDecl *Ivar)
Definition: CGExpr.cpp:4419
llvm::Value * EmitARCRetainAutorelease(QualType type, llvm::Value *value)
Do a fused retain/autorelease of the given object.
Definition: CGObjC.cpp:2208
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition: Linkage.h:33
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition: CGStmt.cpp:445
void setAtomicSetterHelperFnMap(QualType Ty, llvm::Constant *Fn)
void EmitARCInitWeak(Address addr, llvm::Value *value)
i8* @objc_initWeak(i8** addr, i8* value) Returns value.
Definition: CGObjC.cpp:2260
ARCPreciseLifetime_t
Does an ARC strong l-value have precise lifetime?
Definition: CGValue.h:120
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2018
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition: ExprObjC.h:513
llvm::Constant * objc_moveWeak
void objc_moveWeak(id *dest, id *src);
llvm::ConstantInt * getSize(CharUnits numChars)
Emit the given number of characters as a value of type size_t.
const Decl * CurFuncDecl
CurFuncDecl - Holds the Decl for the current outermost non-closure context.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2185
virtual llvm::Value * GetClass(CodeGenFunction &CGF, const ObjCInterfaceDecl *OID)=0
GetClass - Return a reference to the class for the given interface decl.
Reading or writing from this object requires a barrier call.
Definition: Type.h:183
void EmitLexicalBlockStart(CGBuilderTy &Builder, SourceLocation Loc)
Emit metadata to indicate the beginning of a new lexical block and push the block onto the stack...
int64_t toBits(CharUnits CharSize) const
Convert a size in characters to a size in bits.
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:989
llvm::iterator_range< arg_iterator > arguments()
Definition: ExprObjC.h:1407
A non-RAII class containing all the information about a bound opaque value.
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:5804
llvm::Value * EmitObjCCollectionLiteral(const Expr *E, const ObjCMethodDecl *MethodWithObjects)
Definition: CGObjC.cpp:113
void EmitReturnStmt(const ReturnStmt &S)
EmitReturnStmt - Note that due to GCC extensions, this can have an operand if the function returns vo...
Definition: CGStmt.cpp:1021
llvm::Type * ConvertType(QualType T)
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1964
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:40
LValue EmitLValue(const Expr *E)
EmitLValue - Emit code to compute a designator that specifies the location of the expression...
Definition: CGExpr.cpp:1174
Address ReturnValue
ReturnValue - The temporary alloca to hold the return value.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
ImplicitParamDecl * getCmdDecl() const
Definition: DeclObjC.h:446
The receiver is a class.
Definition: ExprObjC.h:1051
Represents Objective-C&#39;s @try ... @catch ... @finally statement.
Definition: StmtObjC.h:154
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:265
bool AutoreleaseResult
In ARC, whether we should autorelease the return value.
RValue EmitLoadOfLValue(LValue V, SourceLocation Loc)
EmitLoadOfLValue - Given an expression that represents a value lvalue, this method emits the address ...
Definition: CGExpr.cpp:1686
llvm::Value * EmitARCRetainBlock(llvm::Value *value, bool mandatory)
Retain the given block, with _Block_copy semantics.
Definition: CGObjC.cpp:1975
void generateObjCGetterBody(const ObjCImplementationDecl *classImpl, const ObjCPropertyImplDecl *propImpl, const ObjCMethodDecl *GetterMothodDecl, llvm::Constant *AtomicHelperFn)
Definition: CGObjC.cpp:879
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2218
void StartObjCMethod(const ObjCMethodDecl *MD, const ObjCContainerDecl *CD)
StartObjCMethod - Begin emission of an ObjCMethod.
Definition: CGObjC.cpp:532
llvm::Constant * IsOSVersionAtLeastFn
bool hasARCUnsafeClaimAutoreleasedReturnValue() const
Is objc_unsafeClaimAutoreleasedReturnValue available?
Definition: ObjCRuntime.h:312
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:930
virtual llvm::Constant * GetCppAtomicObjectSetFunction()=0
API for atomic copying of qualified aggregates with non-trivial copy assignment (c++) in setter...
QualType getObjCFastEnumerationStateType()
Retrieve the record type that describes the state of an Objective-C fast enumeration loop (for...
void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr)
Definition: CGObjC.cpp:2425
bool hasNativeARC() const
Does this runtime natively provide the ARC entrypoints?
Definition: ObjCRuntime.h:160
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:956
static RValue get(llvm::Value *V)
Definition: CGValue.h:86
Expr * getRHS() const
Definition: Expr.h:3044
ObjCPropertyDecl * getPropertyDecl() const
Definition: DeclObjC.h:2837
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:342
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
static void emitAutoreleasedReturnValueMarker(CodeGenFunction &CGF)
Definition: CGObjC.cpp:1998
Address EmitCompoundStmtWithoutScope(const CompoundStmt &S, bool GetLast=false, AggValueSlot AVS=AggValueSlot::ignored())
Definition: CGStmt.cpp:384
llvm::Value * LoadObjCSelf()
LoadObjCSelf - Load the value of self.
Definition: CGObjC.cpp:1458
QualType getType() const
Definition: Decl.h:647
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:111
A trivial tuple used to represent a source range.
void EmitObjCAtTryStmt(const ObjCAtTryStmt &S)
Definition: CGObjC.cpp:1762
LValue - This represents an lvalue references.
Definition: CGValue.h:167
An abstract representation of regular/ObjC call/message targets.
ObjCMethodDecl * getGetterMethodDecl() const
Definition: DeclObjC.h:939
Information for lazily generating a cleanup.
Definition: EHScopeStack.h:147
ObjCIvarDecl * all_declared_ivar_begin()
all_declared_ivar_begin - return first ivar declared in this class, its extensions and its implementa...
Definition: DeclObjC.cpp:1556
llvm::Value * EmitObjCConsumeObject(QualType T, llvm::Value *Ptr)
Produce the code for a CK_ARCConsumeObject.
Definition: CGObjC.cpp:1789
CanQualType BoolTy
Definition: ASTContext.h:997
static llvm::Value * emitARCLoadOperation(CodeGenFunction &CGF, Address addr, llvm::Constant *&fn, StringRef fnName)
Perform an operation having the following signature: i8* (i8**)
Definition: CGObjC.cpp:1872
llvm::PointerIntPair< llvm::Value *, 1, bool > TryEmitResult
Definition: CGObjC.cpp:31
const LangOptions & getLangOpts() const
The receiver is a superclass.
Definition: ExprObjC.h:1057
llvm::Constant * objc_retainAutoreleaseReturnValue
id objc_retainAutoreleaseReturnValue(id);
void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S)
Definition: CGObjC.cpp:3147
SourceLocation getLocStart() const LLVM_READONLY
Definition: Stmt.cpp:277
SourceLocation getBegin() const
CallArgList - Type for representing both the value and type of arguments in a call.
Definition: CGCall.h:226
Address CreateMemTemp(QualType T, const Twine &Name="tmp", bool CastToDefaultAddrSpace=true)
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignment...
Definition: CGExpr.cpp:127
Represents Objective-C&#39;s @autoreleasepool Statement.
Definition: StmtObjC.h:345
llvm::Value * getPointer() const
Definition: CGValue.h:320
SourceLocation getBodyRBrace() const
getBodyRBrace - Gets the right brace of the body, if a body exists.
Definition: DeclBase.cpp:882
SourceLocation getLocation() const
Definition: DeclBase.h:416
void EmitNullInitialization(Address DestPtr, QualType Ty)
EmitNullInitialization - Generate code to set a value of the given type to null, If the type contains...
llvm::Value * EmitBuiltinAvailable(ArrayRef< llvm::Value *> Args)
Definition: CGObjC.cpp:3403
ArrayRef< ParmVarDecl * > parameters() const
Definition: DeclObjC.h:405
Expr * IgnoreParens() LLVM_READONLY
IgnoreParens - Ignore parentheses.
Definition: Expr.cpp:2434
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:1098
static OMPLinearClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, OpenMPLinearClauseKind Modifier, SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef< Expr *> VL, ArrayRef< Expr *> PL, ArrayRef< Expr *> IL, Expr *Step, Expr *CalcStep, Stmt *PreInit, Expr *PostUpdate)
Creates clause with a list of variables VL and a linear step Step.
llvm::Value * EmitObjCSelectorExpr(const ObjCSelectorExpr *E)
Emit a selector.
Definition: CGObjC.cpp:249
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
void Destroyer(CodeGenFunction &CGF, Address addr, QualType ty)
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1075
static void emitCXXDestructMethod(CodeGenFunction &CGF, ObjCImplementationDecl *impl)
Definition: CGObjC.cpp:1387
llvm::Value * EmitObjCProtocolExpr(const ObjCProtocolExpr *E)
Definition: CGObjC.cpp:257
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
Definition: CGCall.cpp:1524
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:5462
const llvm::Triple & getTriple() const