xref: /openbsd-src/gnu/llvm/clang/lib/CodeGen/CGObjCRuntime.cpp (revision 12c855180aad702bbcca06e0398d774beeafb155)
1e5dd7070Spatrick //==- CGObjCRuntime.cpp - Interface to Shared Objective-C Runtime Features ==//
2e5dd7070Spatrick //
3e5dd7070Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e5dd7070Spatrick // See https://llvm.org/LICENSE.txt for license information.
5e5dd7070Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e5dd7070Spatrick //
7e5dd7070Spatrick //===----------------------------------------------------------------------===//
8e5dd7070Spatrick //
9e5dd7070Spatrick // This abstract class defines the interface for Objective-C runtime-specific
10e5dd7070Spatrick // code generation.  It provides some concrete helper methods for functionality
11e5dd7070Spatrick // shared between all (or most) of the Objective-C runtimes supported by clang.
12e5dd7070Spatrick //
13e5dd7070Spatrick //===----------------------------------------------------------------------===//
14e5dd7070Spatrick 
15e5dd7070Spatrick #include "CGObjCRuntime.h"
16e5dd7070Spatrick #include "CGCXXABI.h"
17ec727ea7Spatrick #include "CGCleanup.h"
18e5dd7070Spatrick #include "CGRecordLayout.h"
19e5dd7070Spatrick #include "CodeGenFunction.h"
20e5dd7070Spatrick #include "CodeGenModule.h"
21e5dd7070Spatrick #include "clang/AST/RecordLayout.h"
22e5dd7070Spatrick #include "clang/AST/StmtObjC.h"
23e5dd7070Spatrick #include "clang/CodeGen/CGFunctionInfo.h"
24ec727ea7Spatrick #include "clang/CodeGen/CodeGenABITypes.h"
25*12c85518Srobert #include "llvm/IR/Instruction.h"
26e5dd7070Spatrick #include "llvm/Support/SaveAndRestore.h"
27e5dd7070Spatrick 
28e5dd7070Spatrick using namespace clang;
29e5dd7070Spatrick using namespace CodeGen;
30e5dd7070Spatrick 
ComputeIvarBaseOffset(CodeGen::CodeGenModule & CGM,const ObjCInterfaceDecl * OID,const ObjCIvarDecl * Ivar)31e5dd7070Spatrick uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
32e5dd7070Spatrick                                               const ObjCInterfaceDecl *OID,
33e5dd7070Spatrick                                               const ObjCIvarDecl *Ivar) {
34e5dd7070Spatrick   return CGM.getContext().lookupFieldBitOffset(OID, nullptr, Ivar) /
35e5dd7070Spatrick          CGM.getContext().getCharWidth();
36e5dd7070Spatrick }
37e5dd7070Spatrick 
ComputeIvarBaseOffset(CodeGen::CodeGenModule & CGM,const ObjCImplementationDecl * OID,const ObjCIvarDecl * Ivar)38e5dd7070Spatrick uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
39e5dd7070Spatrick                                               const ObjCImplementationDecl *OID,
40e5dd7070Spatrick                                               const ObjCIvarDecl *Ivar) {
41e5dd7070Spatrick   return CGM.getContext().lookupFieldBitOffset(OID->getClassInterface(), OID,
42e5dd7070Spatrick                                                Ivar) /
43e5dd7070Spatrick          CGM.getContext().getCharWidth();
44e5dd7070Spatrick }
45e5dd7070Spatrick 
ComputeBitfieldBitOffset(CodeGen::CodeGenModule & CGM,const ObjCInterfaceDecl * ID,const ObjCIvarDecl * Ivar)46e5dd7070Spatrick unsigned CGObjCRuntime::ComputeBitfieldBitOffset(
47e5dd7070Spatrick     CodeGen::CodeGenModule &CGM,
48e5dd7070Spatrick     const ObjCInterfaceDecl *ID,
49e5dd7070Spatrick     const ObjCIvarDecl *Ivar) {
50e5dd7070Spatrick   return CGM.getContext().lookupFieldBitOffset(ID, ID->getImplementation(),
51e5dd7070Spatrick                                                Ivar);
52e5dd7070Spatrick }
53e5dd7070Spatrick 
EmitValueForIvarAtOffset(CodeGen::CodeGenFunction & CGF,const ObjCInterfaceDecl * OID,llvm::Value * BaseValue,const ObjCIvarDecl * Ivar,unsigned CVRQualifiers,llvm::Value * Offset)54e5dd7070Spatrick LValue CGObjCRuntime::EmitValueForIvarAtOffset(CodeGen::CodeGenFunction &CGF,
55e5dd7070Spatrick                                                const ObjCInterfaceDecl *OID,
56e5dd7070Spatrick                                                llvm::Value *BaseValue,
57e5dd7070Spatrick                                                const ObjCIvarDecl *Ivar,
58e5dd7070Spatrick                                                unsigned CVRQualifiers,
59e5dd7070Spatrick                                                llvm::Value *Offset) {
60e5dd7070Spatrick   // Compute (type*) ( (char *) BaseValue + Offset)
61e5dd7070Spatrick   QualType InterfaceTy{OID->getTypeForDecl(), 0};
62e5dd7070Spatrick   QualType ObjectPtrTy =
63e5dd7070Spatrick       CGF.CGM.getContext().getObjCObjectPointerType(InterfaceTy);
64e5dd7070Spatrick   QualType IvarTy =
65e5dd7070Spatrick       Ivar->getUsageType(ObjectPtrTy).withCVRQualifiers(CVRQualifiers);
66e5dd7070Spatrick   llvm::Type *LTy = CGF.CGM.getTypes().ConvertTypeForMem(IvarTy);
67e5dd7070Spatrick   llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, CGF.Int8PtrTy);
68a9ac8606Spatrick   V = CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, V, Offset, "add.ptr");
69e5dd7070Spatrick 
70e5dd7070Spatrick   if (!Ivar->isBitField()) {
71e5dd7070Spatrick     V = CGF.Builder.CreateBitCast(V, llvm::PointerType::getUnqual(LTy));
72e5dd7070Spatrick     LValue LV = CGF.MakeNaturalAlignAddrLValue(V, IvarTy);
73e5dd7070Spatrick     return LV;
74e5dd7070Spatrick   }
75e5dd7070Spatrick 
76e5dd7070Spatrick   // We need to compute an access strategy for this bit-field. We are given the
77e5dd7070Spatrick   // offset to the first byte in the bit-field, the sub-byte offset is taken
78e5dd7070Spatrick   // from the original layout. We reuse the normal bit-field access strategy by
79e5dd7070Spatrick   // treating this as an access to a struct where the bit-field is in byte 0,
80e5dd7070Spatrick   // and adjust the containing type size as appropriate.
81e5dd7070Spatrick   //
82e5dd7070Spatrick   // FIXME: Note that currently we make a very conservative estimate of the
83e5dd7070Spatrick   // alignment of the bit-field, because (a) it is not clear what guarantees the
84e5dd7070Spatrick   // runtime makes us, and (b) we don't have a way to specify that the struct is
85e5dd7070Spatrick   // at an alignment plus offset.
86e5dd7070Spatrick   //
87e5dd7070Spatrick   // Note, there is a subtle invariant here: we can only call this routine on
88e5dd7070Spatrick   // non-synthesized ivars but we may be called for synthesized ivars.  However,
89e5dd7070Spatrick   // a synthesized ivar can never be a bit-field, so this is safe.
90e5dd7070Spatrick   uint64_t FieldBitOffset =
91e5dd7070Spatrick       CGF.CGM.getContext().lookupFieldBitOffset(OID, nullptr, Ivar);
92e5dd7070Spatrick   uint64_t BitOffset = FieldBitOffset % CGF.CGM.getContext().getCharWidth();
93e5dd7070Spatrick   uint64_t AlignmentBits = CGF.CGM.getTarget().getCharAlign();
94e5dd7070Spatrick   uint64_t BitFieldSize = Ivar->getBitWidthValue(CGF.getContext());
95e5dd7070Spatrick   CharUnits StorageSize = CGF.CGM.getContext().toCharUnitsFromBits(
96e5dd7070Spatrick       llvm::alignTo(BitOffset + BitFieldSize, AlignmentBits));
97e5dd7070Spatrick   CharUnits Alignment = CGF.CGM.getContext().toCharUnitsFromBits(AlignmentBits);
98e5dd7070Spatrick 
99e5dd7070Spatrick   // Allocate a new CGBitFieldInfo object to describe this access.
100e5dd7070Spatrick   //
101e5dd7070Spatrick   // FIXME: This is incredibly wasteful, these should be uniqued or part of some
102e5dd7070Spatrick   // layout object. However, this is blocked on other cleanups to the
103e5dd7070Spatrick   // Objective-C code, so for now we just live with allocating a bunch of these
104e5dd7070Spatrick   // objects.
105e5dd7070Spatrick   CGBitFieldInfo *Info = new (CGF.CGM.getContext()) CGBitFieldInfo(
106e5dd7070Spatrick     CGBitFieldInfo::MakeInfo(CGF.CGM.getTypes(), Ivar, BitOffset, BitFieldSize,
107e5dd7070Spatrick                              CGF.CGM.getContext().toBits(StorageSize),
108e5dd7070Spatrick                              CharUnits::fromQuantity(0)));
109e5dd7070Spatrick 
110*12c85518Srobert   Address Addr = Address(V, CGF.Int8Ty, Alignment);
111e5dd7070Spatrick   Addr = CGF.Builder.CreateElementBitCast(Addr,
112e5dd7070Spatrick                                    llvm::Type::getIntNTy(CGF.getLLVMContext(),
113e5dd7070Spatrick                                                          Info->StorageSize));
114e5dd7070Spatrick   return LValue::MakeBitfield(Addr, *Info, IvarTy,
115e5dd7070Spatrick                               LValueBaseInfo(AlignmentSource::Decl),
116e5dd7070Spatrick                               TBAAAccessInfo());
117e5dd7070Spatrick }
118e5dd7070Spatrick 
119e5dd7070Spatrick namespace {
120e5dd7070Spatrick   struct CatchHandler {
121e5dd7070Spatrick     const VarDecl *Variable;
122e5dd7070Spatrick     const Stmt *Body;
123e5dd7070Spatrick     llvm::BasicBlock *Block;
124e5dd7070Spatrick     llvm::Constant *TypeInfo;
125e5dd7070Spatrick     /// Flags used to differentiate cleanups and catchalls in Windows SEH
126e5dd7070Spatrick     unsigned Flags;
127e5dd7070Spatrick   };
128e5dd7070Spatrick 
129e5dd7070Spatrick   struct CallObjCEndCatch final : EHScopeStack::Cleanup {
CallObjCEndCatch__anon2c7d2e610111::CallObjCEndCatch130e5dd7070Spatrick     CallObjCEndCatch(bool MightThrow, llvm::FunctionCallee Fn)
131e5dd7070Spatrick         : MightThrow(MightThrow), Fn(Fn) {}
132e5dd7070Spatrick     bool MightThrow;
133e5dd7070Spatrick     llvm::FunctionCallee Fn;
134e5dd7070Spatrick 
Emit__anon2c7d2e610111::CallObjCEndCatch135e5dd7070Spatrick     void Emit(CodeGenFunction &CGF, Flags flags) override {
136e5dd7070Spatrick       if (MightThrow)
137e5dd7070Spatrick         CGF.EmitRuntimeCallOrInvoke(Fn);
138e5dd7070Spatrick       else
139e5dd7070Spatrick         CGF.EmitNounwindRuntimeCall(Fn);
140e5dd7070Spatrick     }
141e5dd7070Spatrick   };
142e5dd7070Spatrick }
143e5dd7070Spatrick 
EmitTryCatchStmt(CodeGenFunction & CGF,const ObjCAtTryStmt & S,llvm::FunctionCallee beginCatchFn,llvm::FunctionCallee endCatchFn,llvm::FunctionCallee exceptionRethrowFn)144e5dd7070Spatrick void CGObjCRuntime::EmitTryCatchStmt(CodeGenFunction &CGF,
145e5dd7070Spatrick                                      const ObjCAtTryStmt &S,
146e5dd7070Spatrick                                      llvm::FunctionCallee beginCatchFn,
147e5dd7070Spatrick                                      llvm::FunctionCallee endCatchFn,
148e5dd7070Spatrick                                      llvm::FunctionCallee exceptionRethrowFn) {
149e5dd7070Spatrick   // Jump destination for falling out of catch bodies.
150e5dd7070Spatrick   CodeGenFunction::JumpDest Cont;
151e5dd7070Spatrick   if (S.getNumCatchStmts())
152e5dd7070Spatrick     Cont = CGF.getJumpDestInCurrentScope("eh.cont");
153e5dd7070Spatrick 
154e5dd7070Spatrick   bool useFunclets = EHPersonality::get(CGF).usesFuncletPads();
155e5dd7070Spatrick 
156e5dd7070Spatrick   CodeGenFunction::FinallyInfo FinallyInfo;
157e5dd7070Spatrick   if (!useFunclets)
158e5dd7070Spatrick     if (const ObjCAtFinallyStmt *Finally = S.getFinallyStmt())
159e5dd7070Spatrick       FinallyInfo.enter(CGF, Finally->getFinallyBody(),
160e5dd7070Spatrick                         beginCatchFn, endCatchFn, exceptionRethrowFn);
161e5dd7070Spatrick 
162e5dd7070Spatrick   SmallVector<CatchHandler, 8> Handlers;
163e5dd7070Spatrick 
164e5dd7070Spatrick 
165e5dd7070Spatrick   // Enter the catch, if there is one.
166e5dd7070Spatrick   if (S.getNumCatchStmts()) {
167*12c85518Srobert     for (const ObjCAtCatchStmt *CatchStmt : S.catch_stmts()) {
168e5dd7070Spatrick       const VarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
169e5dd7070Spatrick 
170e5dd7070Spatrick       Handlers.push_back(CatchHandler());
171e5dd7070Spatrick       CatchHandler &Handler = Handlers.back();
172e5dd7070Spatrick       Handler.Variable = CatchDecl;
173e5dd7070Spatrick       Handler.Body = CatchStmt->getCatchBody();
174e5dd7070Spatrick       Handler.Block = CGF.createBasicBlock("catch");
175e5dd7070Spatrick       Handler.Flags = 0;
176e5dd7070Spatrick 
177e5dd7070Spatrick       // @catch(...) always matches.
178e5dd7070Spatrick       if (!CatchDecl) {
179e5dd7070Spatrick         auto catchAll = getCatchAllTypeInfo();
180e5dd7070Spatrick         Handler.TypeInfo = catchAll.RTTI;
181e5dd7070Spatrick         Handler.Flags = catchAll.Flags;
182e5dd7070Spatrick         // Don't consider any other catches.
183e5dd7070Spatrick         break;
184e5dd7070Spatrick       }
185e5dd7070Spatrick 
186e5dd7070Spatrick       Handler.TypeInfo = GetEHType(CatchDecl->getType());
187e5dd7070Spatrick     }
188e5dd7070Spatrick 
189e5dd7070Spatrick     EHCatchScope *Catch = CGF.EHStack.pushCatch(Handlers.size());
190e5dd7070Spatrick     for (unsigned I = 0, E = Handlers.size(); I != E; ++I)
191e5dd7070Spatrick       Catch->setHandler(I, { Handlers[I].TypeInfo, Handlers[I].Flags }, Handlers[I].Block);
192e5dd7070Spatrick   }
193e5dd7070Spatrick 
194e5dd7070Spatrick   if (useFunclets)
195e5dd7070Spatrick     if (const ObjCAtFinallyStmt *Finally = S.getFinallyStmt()) {
196e5dd7070Spatrick         CodeGenFunction HelperCGF(CGM, /*suppressNewContext=*/true);
197e5dd7070Spatrick         if (!CGF.CurSEHParent)
198e5dd7070Spatrick             CGF.CurSEHParent = cast<NamedDecl>(CGF.CurFuncDecl);
199e5dd7070Spatrick         // Outline the finally block.
200e5dd7070Spatrick         const Stmt *FinallyBlock = Finally->getFinallyBody();
201e5dd7070Spatrick         HelperCGF.startOutlinedSEHHelper(CGF, /*isFilter*/false, FinallyBlock);
202e5dd7070Spatrick 
203e5dd7070Spatrick         // Emit the original filter expression, convert to i32, and return.
204e5dd7070Spatrick         HelperCGF.EmitStmt(FinallyBlock);
205e5dd7070Spatrick 
206e5dd7070Spatrick         HelperCGF.FinishFunction(FinallyBlock->getEndLoc());
207e5dd7070Spatrick 
208e5dd7070Spatrick         llvm::Function *FinallyFunc = HelperCGF.CurFn;
209e5dd7070Spatrick 
210e5dd7070Spatrick 
211e5dd7070Spatrick         // Push a cleanup for __finally blocks.
212e5dd7070Spatrick         CGF.pushSEHCleanup(NormalAndEHCleanup, FinallyFunc);
213e5dd7070Spatrick     }
214e5dd7070Spatrick 
215e5dd7070Spatrick 
216e5dd7070Spatrick   // Emit the try body.
217e5dd7070Spatrick   CGF.EmitStmt(S.getTryBody());
218e5dd7070Spatrick 
219e5dd7070Spatrick   // Leave the try.
220e5dd7070Spatrick   if (S.getNumCatchStmts())
221e5dd7070Spatrick     CGF.popCatchScope();
222e5dd7070Spatrick 
223e5dd7070Spatrick   // Remember where we were.
224e5dd7070Spatrick   CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
225e5dd7070Spatrick 
226e5dd7070Spatrick   // Emit the handlers.
227e5dd7070Spatrick   for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {
228e5dd7070Spatrick     CatchHandler &Handler = Handlers[I];
229e5dd7070Spatrick 
230e5dd7070Spatrick     CGF.EmitBlock(Handler.Block);
231*12c85518Srobert 
232*12c85518Srobert     CodeGenFunction::LexicalScope Cleanups(CGF, Handler.Body->getSourceRange());
233*12c85518Srobert     SaveAndRestore RevertAfterScope(CGF.CurrentFuncletPad);
234*12c85518Srobert     if (useFunclets) {
235*12c85518Srobert       llvm::Instruction *CPICandidate = Handler.Block->getFirstNonPHI();
236*12c85518Srobert       if (auto *CPI = dyn_cast_or_null<llvm::CatchPadInst>(CPICandidate)) {
237e5dd7070Spatrick         CGF.CurrentFuncletPad = CPI;
238e5dd7070Spatrick         CPI->setOperand(2, CGF.getExceptionSlot().getPointer());
239*12c85518Srobert         CGF.EHStack.pushCleanup<CatchRetScope>(NormalCleanup, CPI);
240e5dd7070Spatrick       }
241*12c85518Srobert     }
242*12c85518Srobert 
243e5dd7070Spatrick     llvm::Value *RawExn = CGF.getExceptionFromSlot();
244e5dd7070Spatrick 
245e5dd7070Spatrick     // Enter the catch.
246e5dd7070Spatrick     llvm::Value *Exn = RawExn;
247e5dd7070Spatrick     if (beginCatchFn)
248e5dd7070Spatrick       Exn = CGF.EmitNounwindRuntimeCall(beginCatchFn, RawExn, "exn.adjusted");
249e5dd7070Spatrick 
250e5dd7070Spatrick     if (endCatchFn) {
251e5dd7070Spatrick       // Add a cleanup to leave the catch.
252e5dd7070Spatrick       bool EndCatchMightThrow = (Handler.Variable == nullptr);
253e5dd7070Spatrick 
254e5dd7070Spatrick       CGF.EHStack.pushCleanup<CallObjCEndCatch>(NormalAndEHCleanup,
255e5dd7070Spatrick                                                 EndCatchMightThrow,
256e5dd7070Spatrick                                                 endCatchFn);
257e5dd7070Spatrick     }
258e5dd7070Spatrick 
259e5dd7070Spatrick     // Bind the catch parameter if it exists.
260e5dd7070Spatrick     if (const VarDecl *CatchParam = Handler.Variable) {
261e5dd7070Spatrick       llvm::Type *CatchType = CGF.ConvertType(CatchParam->getType());
262e5dd7070Spatrick       llvm::Value *CastExn = CGF.Builder.CreateBitCast(Exn, CatchType);
263e5dd7070Spatrick 
264e5dd7070Spatrick       CGF.EmitAutoVarDecl(*CatchParam);
265e5dd7070Spatrick       EmitInitOfCatchParam(CGF, CastExn, CatchParam);
266e5dd7070Spatrick     }
267e5dd7070Spatrick 
268e5dd7070Spatrick     CGF.ObjCEHValueStack.push_back(Exn);
269e5dd7070Spatrick     CGF.EmitStmt(Handler.Body);
270e5dd7070Spatrick     CGF.ObjCEHValueStack.pop_back();
271e5dd7070Spatrick 
272e5dd7070Spatrick     // Leave any cleanups associated with the catch.
273*12c85518Srobert     Cleanups.ForceCleanup();
274e5dd7070Spatrick 
275e5dd7070Spatrick     CGF.EmitBranchThroughCleanup(Cont);
276e5dd7070Spatrick   }
277e5dd7070Spatrick 
278e5dd7070Spatrick   // Go back to the try-statement fallthrough.
279e5dd7070Spatrick   CGF.Builder.restoreIP(SavedIP);
280e5dd7070Spatrick 
281e5dd7070Spatrick   // Pop out of the finally.
282e5dd7070Spatrick   if (!useFunclets && S.getFinallyStmt())
283e5dd7070Spatrick     FinallyInfo.exit(CGF);
284e5dd7070Spatrick 
285e5dd7070Spatrick   if (Cont.isValid())
286e5dd7070Spatrick     CGF.EmitBlock(Cont.getBlock());
287e5dd7070Spatrick }
288e5dd7070Spatrick 
EmitInitOfCatchParam(CodeGenFunction & CGF,llvm::Value * exn,const VarDecl * paramDecl)289e5dd7070Spatrick void CGObjCRuntime::EmitInitOfCatchParam(CodeGenFunction &CGF,
290e5dd7070Spatrick                                          llvm::Value *exn,
291e5dd7070Spatrick                                          const VarDecl *paramDecl) {
292e5dd7070Spatrick 
293e5dd7070Spatrick   Address paramAddr = CGF.GetAddrOfLocalVar(paramDecl);
294e5dd7070Spatrick 
295e5dd7070Spatrick   switch (paramDecl->getType().getQualifiers().getObjCLifetime()) {
296e5dd7070Spatrick   case Qualifiers::OCL_Strong:
297e5dd7070Spatrick     exn = CGF.EmitARCRetainNonBlock(exn);
298*12c85518Srobert     [[fallthrough]];
299e5dd7070Spatrick 
300e5dd7070Spatrick   case Qualifiers::OCL_None:
301e5dd7070Spatrick   case Qualifiers::OCL_ExplicitNone:
302e5dd7070Spatrick   case Qualifiers::OCL_Autoreleasing:
303e5dd7070Spatrick     CGF.Builder.CreateStore(exn, paramAddr);
304e5dd7070Spatrick     return;
305e5dd7070Spatrick 
306e5dd7070Spatrick   case Qualifiers::OCL_Weak:
307e5dd7070Spatrick     CGF.EmitARCInitWeak(paramAddr, exn);
308e5dd7070Spatrick     return;
309e5dd7070Spatrick   }
310e5dd7070Spatrick   llvm_unreachable("invalid ownership qualifier");
311e5dd7070Spatrick }
312e5dd7070Spatrick 
313e5dd7070Spatrick namespace {
314e5dd7070Spatrick   struct CallSyncExit final : EHScopeStack::Cleanup {
315e5dd7070Spatrick     llvm::FunctionCallee SyncExitFn;
316e5dd7070Spatrick     llvm::Value *SyncArg;
CallSyncExit__anon2c7d2e610211::CallSyncExit317e5dd7070Spatrick     CallSyncExit(llvm::FunctionCallee SyncExitFn, llvm::Value *SyncArg)
318e5dd7070Spatrick         : SyncExitFn(SyncExitFn), SyncArg(SyncArg) {}
319e5dd7070Spatrick 
Emit__anon2c7d2e610211::CallSyncExit320e5dd7070Spatrick     void Emit(CodeGenFunction &CGF, Flags flags) override {
321e5dd7070Spatrick       CGF.EmitNounwindRuntimeCall(SyncExitFn, SyncArg);
322e5dd7070Spatrick     }
323e5dd7070Spatrick   };
324e5dd7070Spatrick }
325e5dd7070Spatrick 
EmitAtSynchronizedStmt(CodeGenFunction & CGF,const ObjCAtSynchronizedStmt & S,llvm::FunctionCallee syncEnterFn,llvm::FunctionCallee syncExitFn)326e5dd7070Spatrick void CGObjCRuntime::EmitAtSynchronizedStmt(CodeGenFunction &CGF,
327e5dd7070Spatrick                                            const ObjCAtSynchronizedStmt &S,
328e5dd7070Spatrick                                            llvm::FunctionCallee syncEnterFn,
329e5dd7070Spatrick                                            llvm::FunctionCallee syncExitFn) {
330e5dd7070Spatrick   CodeGenFunction::RunCleanupsScope cleanups(CGF);
331e5dd7070Spatrick 
332e5dd7070Spatrick   // Evaluate the lock operand.  This is guaranteed to dominate the
333e5dd7070Spatrick   // ARC release and lock-release cleanups.
334e5dd7070Spatrick   const Expr *lockExpr = S.getSynchExpr();
335e5dd7070Spatrick   llvm::Value *lock;
336e5dd7070Spatrick   if (CGF.getLangOpts().ObjCAutoRefCount) {
337e5dd7070Spatrick     lock = CGF.EmitARCRetainScalarExpr(lockExpr);
338e5dd7070Spatrick     lock = CGF.EmitObjCConsumeObject(lockExpr->getType(), lock);
339e5dd7070Spatrick   } else {
340e5dd7070Spatrick     lock = CGF.EmitScalarExpr(lockExpr);
341e5dd7070Spatrick   }
342e5dd7070Spatrick   lock = CGF.Builder.CreateBitCast(lock, CGF.VoidPtrTy);
343e5dd7070Spatrick 
344e5dd7070Spatrick   // Acquire the lock.
345e5dd7070Spatrick   CGF.Builder.CreateCall(syncEnterFn, lock)->setDoesNotThrow();
346e5dd7070Spatrick 
347e5dd7070Spatrick   // Register an all-paths cleanup to release the lock.
348e5dd7070Spatrick   CGF.EHStack.pushCleanup<CallSyncExit>(NormalAndEHCleanup, syncExitFn, lock);
349e5dd7070Spatrick 
350e5dd7070Spatrick   // Emit the body of the statement.
351e5dd7070Spatrick   CGF.EmitStmt(S.getSynchBody());
352e5dd7070Spatrick }
353e5dd7070Spatrick 
354e5dd7070Spatrick /// Compute the pointer-to-function type to which a message send
355e5dd7070Spatrick /// should be casted in order to correctly call the given method
356e5dd7070Spatrick /// with the given arguments.
357e5dd7070Spatrick ///
358e5dd7070Spatrick /// \param method - may be null
359e5dd7070Spatrick /// \param resultType - the result type to use if there's no method
360e5dd7070Spatrick /// \param callArgs - the actual arguments, including implicit ones
361e5dd7070Spatrick CGObjCRuntime::MessageSendInfo
getMessageSendInfo(const ObjCMethodDecl * method,QualType resultType,CallArgList & callArgs)362e5dd7070Spatrick CGObjCRuntime::getMessageSendInfo(const ObjCMethodDecl *method,
363e5dd7070Spatrick                                   QualType resultType,
364e5dd7070Spatrick                                   CallArgList &callArgs) {
365*12c85518Srobert   unsigned ProgramAS = CGM.getDataLayout().getProgramAddressSpace();
366*12c85518Srobert 
367e5dd7070Spatrick   // If there's a method, use information from that.
368e5dd7070Spatrick   if (method) {
369e5dd7070Spatrick     const CGFunctionInfo &signature =
370e5dd7070Spatrick       CGM.getTypes().arrangeObjCMessageSendSignature(method, callArgs[0].Ty);
371e5dd7070Spatrick 
372e5dd7070Spatrick     llvm::PointerType *signatureType =
373*12c85518Srobert       CGM.getTypes().GetFunctionType(signature)->getPointerTo(ProgramAS);
374e5dd7070Spatrick 
375e5dd7070Spatrick     const CGFunctionInfo &signatureForCall =
376e5dd7070Spatrick       CGM.getTypes().arrangeCall(signature, callArgs);
377e5dd7070Spatrick 
378e5dd7070Spatrick     return MessageSendInfo(signatureForCall, signatureType);
379e5dd7070Spatrick   }
380e5dd7070Spatrick 
381e5dd7070Spatrick   // There's no method;  just use a default CC.
382e5dd7070Spatrick   const CGFunctionInfo &argsInfo =
383e5dd7070Spatrick     CGM.getTypes().arrangeUnprototypedObjCMessageSend(resultType, callArgs);
384e5dd7070Spatrick 
385e5dd7070Spatrick   // Derive the signature to call from that.
386e5dd7070Spatrick   llvm::PointerType *signatureType =
387*12c85518Srobert     CGM.getTypes().GetFunctionType(argsInfo)->getPointerTo(ProgramAS);
388e5dd7070Spatrick   return MessageSendInfo(argsInfo, signatureType);
389e5dd7070Spatrick }
390ec727ea7Spatrick 
canMessageReceiverBeNull(CodeGenFunction & CGF,const ObjCMethodDecl * method,bool isSuper,const ObjCInterfaceDecl * classReceiver,llvm::Value * receiver)391*12c85518Srobert bool CGObjCRuntime::canMessageReceiverBeNull(CodeGenFunction &CGF,
392*12c85518Srobert                                              const ObjCMethodDecl *method,
393*12c85518Srobert                                              bool isSuper,
394*12c85518Srobert                                        const ObjCInterfaceDecl *classReceiver,
395*12c85518Srobert                                              llvm::Value *receiver) {
396*12c85518Srobert   // Super dispatch assumes that self is non-null; even the messenger
397*12c85518Srobert   // doesn't have a null check internally.
398*12c85518Srobert   if (isSuper)
399*12c85518Srobert     return false;
400*12c85518Srobert 
401*12c85518Srobert   // If this is a direct dispatch of a class method, check whether the class,
402*12c85518Srobert   // or anything in its hierarchy, was weak-linked.
403*12c85518Srobert   if (classReceiver && method && method->isClassMethod())
404*12c85518Srobert     return isWeakLinkedClass(classReceiver);
405*12c85518Srobert 
406*12c85518Srobert   // If we're emitting a method, and self is const (meaning just ARC, for now),
407*12c85518Srobert   // and the receiver is a load of self, then self is a valid object.
408*12c85518Srobert   if (auto curMethod =
409*12c85518Srobert                dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl)) {
410*12c85518Srobert     auto self = curMethod->getSelfDecl();
411*12c85518Srobert     if (self->getType().isConstQualified()) {
412*12c85518Srobert       if (auto LI = dyn_cast<llvm::LoadInst>(receiver->stripPointerCasts())) {
413*12c85518Srobert         llvm::Value *selfAddr = CGF.GetAddrOfLocalVar(self).getPointer();
414*12c85518Srobert         if (selfAddr == LI->getPointerOperand()) {
415*12c85518Srobert           return false;
416*12c85518Srobert         }
417*12c85518Srobert       }
418*12c85518Srobert     }
419*12c85518Srobert   }
420*12c85518Srobert 
421*12c85518Srobert   // Otherwise, assume it can be null.
422*12c85518Srobert   return true;
423*12c85518Srobert }
424*12c85518Srobert 
isWeakLinkedClass(const ObjCInterfaceDecl * ID)425*12c85518Srobert bool CGObjCRuntime::isWeakLinkedClass(const ObjCInterfaceDecl *ID) {
426*12c85518Srobert   do {
427*12c85518Srobert     if (ID->isWeakImported())
428*12c85518Srobert       return true;
429*12c85518Srobert   } while ((ID = ID->getSuperClass()));
430*12c85518Srobert 
431*12c85518Srobert   return false;
432*12c85518Srobert }
433*12c85518Srobert 
destroyCalleeDestroyedArguments(CodeGenFunction & CGF,const ObjCMethodDecl * method,const CallArgList & callArgs)434*12c85518Srobert void CGObjCRuntime::destroyCalleeDestroyedArguments(CodeGenFunction &CGF,
435*12c85518Srobert                                               const ObjCMethodDecl *method,
436*12c85518Srobert                                               const CallArgList &callArgs) {
437*12c85518Srobert   CallArgList::const_iterator I = callArgs.begin();
438*12c85518Srobert   for (auto i = method->param_begin(), e = method->param_end();
439*12c85518Srobert          i != e; ++i, ++I) {
440*12c85518Srobert     const ParmVarDecl *param = (*i);
441*12c85518Srobert     if (param->hasAttr<NSConsumedAttr>()) {
442*12c85518Srobert       RValue RV = I->getRValue(CGF);
443*12c85518Srobert       assert(RV.isScalar() &&
444*12c85518Srobert              "NullReturnState::complete - arg not on object");
445*12c85518Srobert       CGF.EmitARCRelease(RV.getScalarVal(), ARCImpreciseLifetime);
446*12c85518Srobert     } else {
447*12c85518Srobert       QualType QT = param->getType();
448*12c85518Srobert       auto *RT = QT->getAs<RecordType>();
449*12c85518Srobert       if (RT && RT->getDecl()->isParamDestroyedInCallee()) {
450*12c85518Srobert         RValue RV = I->getRValue(CGF);
451*12c85518Srobert         QualType::DestructionKind DtorKind = QT.isDestructedType();
452*12c85518Srobert         switch (DtorKind) {
453*12c85518Srobert         case QualType::DK_cxx_destructor:
454*12c85518Srobert           CGF.destroyCXXObject(CGF, RV.getAggregateAddress(), QT);
455*12c85518Srobert           break;
456*12c85518Srobert         case QualType::DK_nontrivial_c_struct:
457*12c85518Srobert           CGF.destroyNonTrivialCStruct(CGF, RV.getAggregateAddress(), QT);
458*12c85518Srobert           break;
459*12c85518Srobert         default:
460*12c85518Srobert           llvm_unreachable("unexpected dtor kind");
461*12c85518Srobert           break;
462*12c85518Srobert         }
463*12c85518Srobert       }
464*12c85518Srobert     }
465*12c85518Srobert   }
466*12c85518Srobert }
467*12c85518Srobert 
468ec727ea7Spatrick llvm::Constant *
emitObjCProtocolObject(CodeGenModule & CGM,const ObjCProtocolDecl * protocol)469ec727ea7Spatrick clang::CodeGen::emitObjCProtocolObject(CodeGenModule &CGM,
470ec727ea7Spatrick                                        const ObjCProtocolDecl *protocol) {
471ec727ea7Spatrick   return CGM.getObjCRuntime().GetOrEmitProtocol(protocol);
472ec727ea7Spatrick }
473a9ac8606Spatrick 
getSymbolNameForMethod(const ObjCMethodDecl * OMD,bool includeCategoryName)474a9ac8606Spatrick std::string CGObjCRuntime::getSymbolNameForMethod(const ObjCMethodDecl *OMD,
475a9ac8606Spatrick                                                   bool includeCategoryName) {
476a9ac8606Spatrick   std::string buffer;
477a9ac8606Spatrick   llvm::raw_string_ostream out(buffer);
478a9ac8606Spatrick   CGM.getCXXABI().getMangleContext().mangleObjCMethodName(OMD, out,
479a9ac8606Spatrick                                        /*includePrefixByte=*/true,
480a9ac8606Spatrick                                        includeCategoryName);
481a9ac8606Spatrick   return buffer;
482a9ac8606Spatrick }
483