]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/CodeGen/CGObjCRuntime.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r303571, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / CodeGen / CGObjCRuntime.cpp
1 //==- CGObjCRuntime.cpp - Interface to Shared Objective-C Runtime Features ==//
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 abstract class defines the interface for Objective-C runtime-specific
11 // code generation.  It provides some concrete helper methods for functionality
12 // shared between all (or most) of the Objective-C runtimes supported by clang.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "CGObjCRuntime.h"
17 #include "CGCleanup.h"
18 #include "CGRecordLayout.h"
19 #include "CodeGenFunction.h"
20 #include "CodeGenModule.h"
21 #include "clang/AST/RecordLayout.h"
22 #include "clang/AST/StmtObjC.h"
23 #include "clang/CodeGen/CGFunctionInfo.h"
24 #include "llvm/IR/CallSite.h"
25
26 using namespace clang;
27 using namespace CodeGen;
28
29 static uint64_t LookupFieldBitOffset(CodeGen::CodeGenModule &CGM,
30                                      const ObjCInterfaceDecl *OID,
31                                      const ObjCImplementationDecl *ID,
32                                      const ObjCIvarDecl *Ivar) {
33   const ObjCInterfaceDecl *Container = Ivar->getContainingInterface();
34
35   // FIXME: We should eliminate the need to have ObjCImplementationDecl passed
36   // in here; it should never be necessary because that should be the lexical
37   // decl context for the ivar.
38
39   // If we know have an implementation (and the ivar is in it) then
40   // look up in the implementation layout.
41   const ASTRecordLayout *RL;
42   if (ID && declaresSameEntity(ID->getClassInterface(), Container))
43     RL = &CGM.getContext().getASTObjCImplementationLayout(ID);
44   else
45     RL = &CGM.getContext().getASTObjCInterfaceLayout(Container);
46
47   // Compute field index.
48   //
49   // FIXME: The index here is closely tied to how ASTContext::getObjCLayout is
50   // implemented. This should be fixed to get the information from the layout
51   // directly.
52   unsigned Index = 0;
53
54   for (const ObjCIvarDecl *IVD = Container->all_declared_ivar_begin(); 
55        IVD; IVD = IVD->getNextIvar()) {
56     if (Ivar == IVD)
57       break;
58     ++Index;
59   }
60   assert(Index < RL->getFieldCount() && "Ivar is not inside record layout!");
61
62   return RL->getFieldOffset(Index);
63 }
64
65 uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
66                                               const ObjCInterfaceDecl *OID,
67                                               const ObjCIvarDecl *Ivar) {
68   return LookupFieldBitOffset(CGM, OID, nullptr, Ivar) /
69     CGM.getContext().getCharWidth();
70 }
71
72 uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
73                                               const ObjCImplementationDecl *OID,
74                                               const ObjCIvarDecl *Ivar) {
75   return LookupFieldBitOffset(CGM, OID->getClassInterface(), OID, Ivar) / 
76     CGM.getContext().getCharWidth();
77 }
78
79 unsigned CGObjCRuntime::ComputeBitfieldBitOffset(
80     CodeGen::CodeGenModule &CGM,
81     const ObjCInterfaceDecl *ID,
82     const ObjCIvarDecl *Ivar) {
83   return LookupFieldBitOffset(CGM, ID, ID->getImplementation(), Ivar);
84 }
85
86 LValue CGObjCRuntime::EmitValueForIvarAtOffset(CodeGen::CodeGenFunction &CGF,
87                                                const ObjCInterfaceDecl *OID,
88                                                llvm::Value *BaseValue,
89                                                const ObjCIvarDecl *Ivar,
90                                                unsigned CVRQualifiers,
91                                                llvm::Value *Offset) {
92   // Compute (type*) ( (char *) BaseValue + Offset)
93   QualType IvarTy = Ivar->getType().withCVRQualifiers(CVRQualifiers);
94   llvm::Type *LTy = CGF.CGM.getTypes().ConvertTypeForMem(IvarTy);
95   llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, CGF.Int8PtrTy);
96   V = CGF.Builder.CreateInBoundsGEP(V, Offset, "add.ptr");
97
98   if (!Ivar->isBitField()) {
99     V = CGF.Builder.CreateBitCast(V, llvm::PointerType::getUnqual(LTy));
100     LValue LV = CGF.MakeNaturalAlignAddrLValue(V, IvarTy);
101     return LV;
102   }
103
104   // We need to compute an access strategy for this bit-field. We are given the
105   // offset to the first byte in the bit-field, the sub-byte offset is taken
106   // from the original layout. We reuse the normal bit-field access strategy by
107   // treating this as an access to a struct where the bit-field is in byte 0,
108   // and adjust the containing type size as appropriate.
109   //
110   // FIXME: Note that currently we make a very conservative estimate of the
111   // alignment of the bit-field, because (a) it is not clear what guarantees the
112   // runtime makes us, and (b) we don't have a way to specify that the struct is
113   // at an alignment plus offset.
114   //
115   // Note, there is a subtle invariant here: we can only call this routine on
116   // non-synthesized ivars but we may be called for synthesized ivars.  However,
117   // a synthesized ivar can never be a bit-field, so this is safe.
118   uint64_t FieldBitOffset = LookupFieldBitOffset(CGF.CGM, OID, nullptr, Ivar);
119   uint64_t BitOffset = FieldBitOffset % CGF.CGM.getContext().getCharWidth();
120   uint64_t AlignmentBits = CGF.CGM.getTarget().getCharAlign();
121   uint64_t BitFieldSize = Ivar->getBitWidthValue(CGF.getContext());
122   CharUnits StorageSize = CGF.CGM.getContext().toCharUnitsFromBits(
123       llvm::alignTo(BitOffset + BitFieldSize, AlignmentBits));
124   CharUnits Alignment = CGF.CGM.getContext().toCharUnitsFromBits(AlignmentBits);
125
126   // Allocate a new CGBitFieldInfo object to describe this access.
127   //
128   // FIXME: This is incredibly wasteful, these should be uniqued or part of some
129   // layout object. However, this is blocked on other cleanups to the
130   // Objective-C code, so for now we just live with allocating a bunch of these
131   // objects.
132   CGBitFieldInfo *Info = new (CGF.CGM.getContext()) CGBitFieldInfo(
133     CGBitFieldInfo::MakeInfo(CGF.CGM.getTypes(), Ivar, BitOffset, BitFieldSize,
134                              CGF.CGM.getContext().toBits(StorageSize),
135                              CharUnits::fromQuantity(0)));
136
137   Address Addr(V, Alignment);
138   Addr = CGF.Builder.CreateElementBitCast(Addr,
139                                    llvm::Type::getIntNTy(CGF.getLLVMContext(),
140                                                          Info->StorageSize));
141   return LValue::MakeBitfield(Addr, *Info, IvarTy,
142                               LValueBaseInfo(AlignmentSource::Decl, false));
143 }
144
145 namespace {
146   struct CatchHandler {
147     const VarDecl *Variable;
148     const Stmt *Body;
149     llvm::BasicBlock *Block;
150     llvm::Constant *TypeInfo;
151   };
152
153   struct CallObjCEndCatch final : EHScopeStack::Cleanup {
154     CallObjCEndCatch(bool MightThrow, llvm::Value *Fn)
155         : MightThrow(MightThrow), Fn(Fn) {}
156     bool MightThrow;
157     llvm::Value *Fn;
158
159     void Emit(CodeGenFunction &CGF, Flags flags) override {
160       if (MightThrow)
161         CGF.EmitRuntimeCallOrInvoke(Fn);
162       else
163         CGF.EmitNounwindRuntimeCall(Fn);
164     }
165   };
166 }
167
168
169 void CGObjCRuntime::EmitTryCatchStmt(CodeGenFunction &CGF,
170                                      const ObjCAtTryStmt &S,
171                                      llvm::Constant *beginCatchFn,
172                                      llvm::Constant *endCatchFn,
173                                      llvm::Constant *exceptionRethrowFn) {
174   // Jump destination for falling out of catch bodies.
175   CodeGenFunction::JumpDest Cont;
176   if (S.getNumCatchStmts())
177     Cont = CGF.getJumpDestInCurrentScope("eh.cont");
178
179   CodeGenFunction::FinallyInfo FinallyInfo;
180   if (const ObjCAtFinallyStmt *Finally = S.getFinallyStmt())
181     FinallyInfo.enter(CGF, Finally->getFinallyBody(),
182                       beginCatchFn, endCatchFn, exceptionRethrowFn);
183
184   SmallVector<CatchHandler, 8> Handlers;
185
186   // Enter the catch, if there is one.
187   if (S.getNumCatchStmts()) {
188     for (unsigned I = 0, N = S.getNumCatchStmts(); I != N; ++I) {
189       const ObjCAtCatchStmt *CatchStmt = S.getCatchStmt(I);
190       const VarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
191
192       Handlers.push_back(CatchHandler());
193       CatchHandler &Handler = Handlers.back();
194       Handler.Variable = CatchDecl;
195       Handler.Body = CatchStmt->getCatchBody();
196       Handler.Block = CGF.createBasicBlock("catch");
197
198       // @catch(...) always matches.
199       if (!CatchDecl) {
200         Handler.TypeInfo = nullptr; // catch-all
201         // Don't consider any other catches.
202         break;
203       }
204
205       Handler.TypeInfo = GetEHType(CatchDecl->getType());
206     }
207
208     EHCatchScope *Catch = CGF.EHStack.pushCatch(Handlers.size());
209     for (unsigned I = 0, E = Handlers.size(); I != E; ++I)
210       Catch->setHandler(I, Handlers[I].TypeInfo, Handlers[I].Block);
211   }
212   
213   // Emit the try body.
214   CGF.EmitStmt(S.getTryBody());
215
216   // Leave the try.
217   if (S.getNumCatchStmts())
218     CGF.popCatchScope();
219
220   // Remember where we were.
221   CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
222
223   // Emit the handlers.
224   for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {
225     CatchHandler &Handler = Handlers[I];
226
227     CGF.EmitBlock(Handler.Block);
228     llvm::Value *RawExn = CGF.getExceptionFromSlot();
229
230     // Enter the catch.
231     llvm::Value *Exn = RawExn;
232     if (beginCatchFn)
233       Exn = CGF.EmitNounwindRuntimeCall(beginCatchFn, RawExn, "exn.adjusted");
234
235     CodeGenFunction::LexicalScope cleanups(CGF, Handler.Body->getSourceRange());
236
237     if (endCatchFn) {
238       // Add a cleanup to leave the catch.
239       bool EndCatchMightThrow = (Handler.Variable == nullptr);
240
241       CGF.EHStack.pushCleanup<CallObjCEndCatch>(NormalAndEHCleanup,
242                                                 EndCatchMightThrow,
243                                                 endCatchFn);
244     }
245
246     // Bind the catch parameter if it exists.
247     if (const VarDecl *CatchParam = Handler.Variable) {
248       llvm::Type *CatchType = CGF.ConvertType(CatchParam->getType());
249       llvm::Value *CastExn = CGF.Builder.CreateBitCast(Exn, CatchType);
250
251       CGF.EmitAutoVarDecl(*CatchParam);
252       EmitInitOfCatchParam(CGF, CastExn, CatchParam);
253     }
254
255     CGF.ObjCEHValueStack.push_back(Exn);
256     CGF.EmitStmt(Handler.Body);
257     CGF.ObjCEHValueStack.pop_back();
258
259     // Leave any cleanups associated with the catch.
260     cleanups.ForceCleanup();
261
262     CGF.EmitBranchThroughCleanup(Cont);
263   }  
264
265   // Go back to the try-statement fallthrough.
266   CGF.Builder.restoreIP(SavedIP);
267
268   // Pop out of the finally.
269   if (S.getFinallyStmt())
270     FinallyInfo.exit(CGF);
271
272   if (Cont.isValid())
273     CGF.EmitBlock(Cont.getBlock());
274 }
275
276 void CGObjCRuntime::EmitInitOfCatchParam(CodeGenFunction &CGF,
277                                          llvm::Value *exn,
278                                          const VarDecl *paramDecl) {
279
280   Address paramAddr = CGF.GetAddrOfLocalVar(paramDecl);
281
282   switch (paramDecl->getType().getQualifiers().getObjCLifetime()) {
283   case Qualifiers::OCL_Strong:
284     exn = CGF.EmitARCRetainNonBlock(exn);
285     // fallthrough
286
287   case Qualifiers::OCL_None:
288   case Qualifiers::OCL_ExplicitNone:
289   case Qualifiers::OCL_Autoreleasing:
290     CGF.Builder.CreateStore(exn, paramAddr);
291     return;
292
293   case Qualifiers::OCL_Weak:
294     CGF.EmitARCInitWeak(paramAddr, exn);
295     return;
296   }
297   llvm_unreachable("invalid ownership qualifier");
298 }
299
300 namespace {
301   struct CallSyncExit final : EHScopeStack::Cleanup {
302     llvm::Value *SyncExitFn;
303     llvm::Value *SyncArg;
304     CallSyncExit(llvm::Value *SyncExitFn, llvm::Value *SyncArg)
305       : SyncExitFn(SyncExitFn), SyncArg(SyncArg) {}
306
307     void Emit(CodeGenFunction &CGF, Flags flags) override {
308       CGF.Builder.CreateCall(SyncExitFn, SyncArg)->setDoesNotThrow();
309     }
310   };
311 }
312
313 void CGObjCRuntime::EmitAtSynchronizedStmt(CodeGenFunction &CGF,
314                                            const ObjCAtSynchronizedStmt &S,
315                                            llvm::Function *syncEnterFn,
316                                            llvm::Function *syncExitFn) {
317   CodeGenFunction::RunCleanupsScope cleanups(CGF);
318
319   // Evaluate the lock operand.  This is guaranteed to dominate the
320   // ARC release and lock-release cleanups.
321   const Expr *lockExpr = S.getSynchExpr();
322   llvm::Value *lock;
323   if (CGF.getLangOpts().ObjCAutoRefCount) {
324     lock = CGF.EmitARCRetainScalarExpr(lockExpr);
325     lock = CGF.EmitObjCConsumeObject(lockExpr->getType(), lock);
326   } else {
327     lock = CGF.EmitScalarExpr(lockExpr);
328   }
329   lock = CGF.Builder.CreateBitCast(lock, CGF.VoidPtrTy);
330
331   // Acquire the lock.
332   CGF.Builder.CreateCall(syncEnterFn, lock)->setDoesNotThrow();
333
334   // Register an all-paths cleanup to release the lock.
335   CGF.EHStack.pushCleanup<CallSyncExit>(NormalAndEHCleanup, syncExitFn, lock);
336
337   // Emit the body of the statement.
338   CGF.EmitStmt(S.getSynchBody());
339 }
340
341 /// Compute the pointer-to-function type to which a message send
342 /// should be casted in order to correctly call the given method
343 /// with the given arguments.
344 ///
345 /// \param method - may be null
346 /// \param resultType - the result type to use if there's no method
347 /// \param callArgs - the actual arguments, including implicit ones
348 CGObjCRuntime::MessageSendInfo
349 CGObjCRuntime::getMessageSendInfo(const ObjCMethodDecl *method,
350                                   QualType resultType,
351                                   CallArgList &callArgs) {
352   // If there's a method, use information from that.
353   if (method) {
354     const CGFunctionInfo &signature =
355       CGM.getTypes().arrangeObjCMessageSendSignature(method, callArgs[0].Ty);
356
357     llvm::PointerType *signatureType =
358       CGM.getTypes().GetFunctionType(signature)->getPointerTo();
359
360     const CGFunctionInfo &signatureForCall =
361       CGM.getTypes().arrangeCall(signature, callArgs);
362
363     return MessageSendInfo(signatureForCall, signatureType);
364   }
365
366   // There's no method;  just use a default CC.
367   const CGFunctionInfo &argsInfo =
368     CGM.getTypes().arrangeUnprototypedObjCMessageSend(resultType, callArgs);
369
370   // Derive the signature to call from that.
371   llvm::PointerType *signatureType =
372     CGM.getTypes().GetFunctionType(argsInfo)->getPointerTo();
373   return MessageSendInfo(argsInfo, signatureType);
374 }