1 //==- CGObjCRuntime.cpp - Interface to Shared Objective-C Runtime Features ==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
14 //===----------------------------------------------------------------------===//
16 #include "CGObjCRuntime.h"
18 #include "CGRecordLayout.h"
19 #include "CodeGenModule.h"
20 #include "CodeGenFunction.h"
21 #include "CGCleanup.h"
23 #include "clang/AST/RecordLayout.h"
24 #include "clang/AST/StmtObjC.h"
26 #include "llvm/Support/CallSite.h"
28 using namespace clang;
29 using namespace CodeGen;
31 static uint64_t LookupFieldBitOffset(CodeGen::CodeGenModule &CGM,
32 const ObjCInterfaceDecl *OID,
33 const ObjCImplementationDecl *ID,
34 const ObjCIvarDecl *Ivar) {
35 const ObjCInterfaceDecl *Container = Ivar->getContainingInterface();
37 // FIXME: We should eliminate the need to have ObjCImplementationDecl passed
38 // in here; it should never be necessary because that should be the lexical
39 // decl context for the ivar.
41 // If we know have an implementation (and the ivar is in it) then
42 // look up in the implementation layout.
43 const ASTRecordLayout *RL;
44 if (ID && ID->getClassInterface() == Container)
45 RL = &CGM.getContext().getASTObjCImplementationLayout(ID);
47 RL = &CGM.getContext().getASTObjCInterfaceLayout(Container);
49 // Compute field index.
51 // FIXME: The index here is closely tied to how ASTContext::getObjCLayout is
52 // implemented. This should be fixed to get the information from the layout
55 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl*>(Container);
57 for (ObjCIvarDecl *IVD = IDecl->all_declared_ivar_begin();
58 IVD; IVD = IVD->getNextIvar()) {
63 assert(Index < RL->getFieldCount() && "Ivar is not inside record layout!");
65 return RL->getFieldOffset(Index);
68 uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
69 const ObjCInterfaceDecl *OID,
70 const ObjCIvarDecl *Ivar) {
71 return LookupFieldBitOffset(CGM, OID, 0, Ivar) /
72 CGM.getContext().getCharWidth();
75 uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
76 const ObjCImplementationDecl *OID,
77 const ObjCIvarDecl *Ivar) {
78 return LookupFieldBitOffset(CGM, OID->getClassInterface(), OID, Ivar) /
79 CGM.getContext().getCharWidth();
82 LValue CGObjCRuntime::EmitValueForIvarAtOffset(CodeGen::CodeGenFunction &CGF,
83 const ObjCInterfaceDecl *OID,
84 llvm::Value *BaseValue,
85 const ObjCIvarDecl *Ivar,
86 unsigned CVRQualifiers,
87 llvm::Value *Offset) {
88 // Compute (type*) ( (char *) BaseValue + Offset)
89 const llvm::Type *I8Ptr = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
90 QualType IvarTy = Ivar->getType();
91 const llvm::Type *LTy = CGF.CGM.getTypes().ConvertTypeForMem(IvarTy);
92 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, I8Ptr);
93 V = CGF.Builder.CreateInBoundsGEP(V, Offset, "add.ptr");
94 V = CGF.Builder.CreateBitCast(V, llvm::PointerType::getUnqual(LTy));
96 if (!Ivar->isBitField()) {
97 LValue LV = CGF.MakeAddrLValue(V, IvarTy);
98 LV.getQuals().addCVRQualifiers(CVRQualifiers);
102 // We need to compute an access strategy for this bit-field. We are given the
103 // offset to the first byte in the bit-field, the sub-byte offset is taken
104 // from the original layout. We reuse the normal bit-field access strategy by
105 // treating this as an access to a struct where the bit-field is in byte 0,
106 // and adjust the containing type size as appropriate.
108 // FIXME: Note that currently we make a very conservative estimate of the
109 // alignment of the bit-field, because (a) it is not clear what guarantees the
110 // runtime makes us, and (b) we don't have a way to specify that the struct is
111 // at an alignment plus offset.
113 // Note, there is a subtle invariant here: we can only call this routine on
114 // non-synthesized ivars but we may be called for synthesized ivars. However,
115 // a synthesized ivar can never be a bit-field, so this is safe.
116 const ASTRecordLayout &RL =
117 CGF.CGM.getContext().getASTObjCInterfaceLayout(OID);
118 uint64_t TypeSizeInBits = CGF.CGM.getContext().toBits(RL.getSize());
119 uint64_t FieldBitOffset = LookupFieldBitOffset(CGF.CGM, OID, 0, Ivar);
120 uint64_t BitOffset = FieldBitOffset % CGF.CGM.getContext().getCharWidth();
121 uint64_t ContainingTypeAlign = CGF.CGM.getContext().Target.getCharAlign();
122 uint64_t ContainingTypeSize = TypeSizeInBits - (FieldBitOffset - BitOffset);
123 uint64_t BitFieldSize =
124 Ivar->getBitWidth()->EvaluateAsInt(CGF.getContext()).getZExtValue();
126 // Allocate a new CGBitFieldInfo object to describe this access.
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
132 CGBitFieldInfo *Info = new (CGF.CGM.getContext()) CGBitFieldInfo(
133 CGBitFieldInfo::MakeInfo(CGF.CGM.getTypes(), Ivar, BitOffset, BitFieldSize,
134 ContainingTypeSize, ContainingTypeAlign));
136 return LValue::MakeBitfield(V, *Info,
137 IvarTy.withCVRQualifiers(CVRQualifiers));
141 struct CatchHandler {
142 const VarDecl *Variable;
144 llvm::BasicBlock *Block;
145 llvm::Value *TypeInfo;
148 struct CallObjCEndCatch : EHScopeStack::Cleanup {
149 CallObjCEndCatch(bool MightThrow, llvm::Value *Fn) :
150 MightThrow(MightThrow), Fn(Fn) {}
154 void Emit(CodeGenFunction &CGF, Flags flags) {
156 CGF.Builder.CreateCall(Fn)->setDoesNotThrow();
160 CGF.EmitCallOrInvoke(Fn);
166 void CGObjCRuntime::EmitTryCatchStmt(CodeGenFunction &CGF,
167 const ObjCAtTryStmt &S,
168 llvm::Constant *beginCatchFn,
169 llvm::Constant *endCatchFn,
170 llvm::Constant *exceptionRethrowFn) {
171 // Jump destination for falling out of catch bodies.
172 CodeGenFunction::JumpDest Cont;
173 if (S.getNumCatchStmts())
174 Cont = CGF.getJumpDestInCurrentScope("eh.cont");
176 CodeGenFunction::FinallyInfo FinallyInfo;
177 if (const ObjCAtFinallyStmt *Finally = S.getFinallyStmt())
178 FinallyInfo.enter(CGF, Finally->getFinallyBody(),
179 beginCatchFn, endCatchFn, exceptionRethrowFn);
181 llvm::SmallVector<CatchHandler, 8> Handlers;
183 // Enter the catch, if there is one.
184 if (S.getNumCatchStmts()) {
185 for (unsigned I = 0, N = S.getNumCatchStmts(); I != N; ++I) {
186 const ObjCAtCatchStmt *CatchStmt = S.getCatchStmt(I);
187 const VarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
189 Handlers.push_back(CatchHandler());
190 CatchHandler &Handler = Handlers.back();
191 Handler.Variable = CatchDecl;
192 Handler.Body = CatchStmt->getCatchBody();
193 Handler.Block = CGF.createBasicBlock("catch");
195 // @catch(...) always matches.
197 Handler.TypeInfo = 0; // catch-all
198 // Don't consider any other catches.
202 Handler.TypeInfo = GetEHType(CatchDecl->getType());
205 EHCatchScope *Catch = CGF.EHStack.pushCatch(Handlers.size());
206 for (unsigned I = 0, E = Handlers.size(); I != E; ++I)
207 Catch->setHandler(I, Handlers[I].TypeInfo, Handlers[I].Block);
210 // Emit the try body.
211 CGF.EmitStmt(S.getTryBody());
214 if (S.getNumCatchStmts())
215 CGF.EHStack.popCatch();
217 // Remember where we were.
218 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
220 // Emit the handlers.
221 for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {
222 CatchHandler &Handler = Handlers[I];
224 CGF.EmitBlock(Handler.Block);
225 llvm::Value *RawExn = CGF.Builder.CreateLoad(CGF.getExceptionSlot());
228 llvm::Value *Exn = RawExn;
230 Exn = CGF.Builder.CreateCall(beginCatchFn, RawExn, "exn.adjusted");
231 cast<llvm::CallInst>(Exn)->setDoesNotThrow();
234 CodeGenFunction::RunCleanupsScope cleanups(CGF);
237 // Add a cleanup to leave the catch.
238 bool EndCatchMightThrow = (Handler.Variable == 0);
240 CGF.EHStack.pushCleanup<CallObjCEndCatch>(NormalAndEHCleanup,
245 // Bind the catch parameter if it exists.
246 if (const VarDecl *CatchParam = Handler.Variable) {
247 const llvm::Type *CatchType = CGF.ConvertType(CatchParam->getType());
248 llvm::Value *CastExn = CGF.Builder.CreateBitCast(Exn, CatchType);
250 CGF.EmitAutoVarDecl(*CatchParam);
251 CGF.Builder.CreateStore(CastExn, CGF.GetAddrOfLocalVar(CatchParam));
254 CGF.ObjCEHValueStack.push_back(Exn);
255 CGF.EmitStmt(Handler.Body);
256 CGF.ObjCEHValueStack.pop_back();
258 // Leave any cleanups associated with the catch.
259 cleanups.ForceCleanup();
261 CGF.EmitBranchThroughCleanup(Cont);
264 // Go back to the try-statement fallthrough.
265 CGF.Builder.restoreIP(SavedIP);
267 // Pop out of the finally.
268 if (S.getFinallyStmt())
269 FinallyInfo.exit(CGF);
272 CGF.EmitBlock(Cont.getBlock());
276 struct CallSyncExit : EHScopeStack::Cleanup {
277 llvm::Value *SyncExitFn;
278 llvm::Value *SyncArg;
279 CallSyncExit(llvm::Value *SyncExitFn, llvm::Value *SyncArg)
280 : SyncExitFn(SyncExitFn), SyncArg(SyncArg) {}
282 void Emit(CodeGenFunction &CGF, Flags flags) {
283 CGF.Builder.CreateCall(SyncExitFn, SyncArg)->setDoesNotThrow();
288 void CGObjCRuntime::EmitAtSynchronizedStmt(CodeGenFunction &CGF,
289 const ObjCAtSynchronizedStmt &S,
290 llvm::Function *syncEnterFn,
291 llvm::Function *syncExitFn) {
292 // Evaluate the lock operand. This should dominate the cleanup.
293 llvm::Value *SyncArg =
294 CGF.EmitScalarExpr(S.getSynchExpr());
297 SyncArg = CGF.Builder.CreateBitCast(SyncArg, syncEnterFn->getFunctionType()->getParamType(0));
298 CGF.Builder.CreateCall(syncEnterFn, SyncArg);
300 // Register an all-paths cleanup to release the lock.
301 CGF.EHStack.pushCleanup<CallSyncExit>(NormalAndEHCleanup, syncExitFn,
304 // Emit the body of the statement.
305 CGF.EmitStmt(S.getSynchBody());
307 // Pop the lock-release cleanup.
308 CGF.PopCleanupBlock();