clang API Documentation
00001 //==- CGObjCRuntime.cpp - Interface to Shared Objective-C Runtime Features ==// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This abstract class defines the interface for Objective-C runtime-specific 00011 // code generation. It provides some concrete helper methods for functionality 00012 // shared between all (or most) of the Objective-C runtimes supported by clang. 00013 // 00014 //===----------------------------------------------------------------------===// 00015 00016 #include "CGObjCRuntime.h" 00017 00018 #include "CGRecordLayout.h" 00019 #include "CodeGenModule.h" 00020 #include "CodeGenFunction.h" 00021 #include "CGCleanup.h" 00022 00023 #include "clang/AST/RecordLayout.h" 00024 #include "clang/AST/StmtObjC.h" 00025 00026 #include "llvm/Support/CallSite.h" 00027 00028 using namespace clang; 00029 using namespace CodeGen; 00030 00031 static uint64_t LookupFieldBitOffset(CodeGen::CodeGenModule &CGM, 00032 const ObjCInterfaceDecl *OID, 00033 const ObjCImplementationDecl *ID, 00034 const ObjCIvarDecl *Ivar) { 00035 const ObjCInterfaceDecl *Container = Ivar->getContainingInterface(); 00036 00037 // FIXME: We should eliminate the need to have ObjCImplementationDecl passed 00038 // in here; it should never be necessary because that should be the lexical 00039 // decl context for the ivar. 00040 00041 // If we know have an implementation (and the ivar is in it) then 00042 // look up in the implementation layout. 00043 const ASTRecordLayout *RL; 00044 if (ID && declaresSameEntity(ID->getClassInterface(), Container)) 00045 RL = &CGM.getContext().getASTObjCImplementationLayout(ID); 00046 else 00047 RL = &CGM.getContext().getASTObjCInterfaceLayout(Container); 00048 00049 // Compute field index. 00050 // 00051 // FIXME: The index here is closely tied to how ASTContext::getObjCLayout is 00052 // implemented. This should be fixed to get the information from the layout 00053 // directly. 00054 unsigned Index = 0; 00055 00056 for (const ObjCIvarDecl *IVD = Container->all_declared_ivar_begin(); 00057 IVD; IVD = IVD->getNextIvar()) { 00058 if (Ivar == IVD) 00059 break; 00060 ++Index; 00061 } 00062 assert(Index < RL->getFieldCount() && "Ivar is not inside record layout!"); 00063 00064 return RL->getFieldOffset(Index); 00065 } 00066 00067 uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM, 00068 const ObjCInterfaceDecl *OID, 00069 const ObjCIvarDecl *Ivar) { 00070 return LookupFieldBitOffset(CGM, OID, 0, Ivar) / 00071 CGM.getContext().getCharWidth(); 00072 } 00073 00074 uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM, 00075 const ObjCImplementationDecl *OID, 00076 const ObjCIvarDecl *Ivar) { 00077 return LookupFieldBitOffset(CGM, OID->getClassInterface(), OID, Ivar) / 00078 CGM.getContext().getCharWidth(); 00079 } 00080 00081 LValue CGObjCRuntime::EmitValueForIvarAtOffset(CodeGen::CodeGenFunction &CGF, 00082 const ObjCInterfaceDecl *OID, 00083 llvm::Value *BaseValue, 00084 const ObjCIvarDecl *Ivar, 00085 unsigned CVRQualifiers, 00086 llvm::Value *Offset) { 00087 // Compute (type*) ( (char *) BaseValue + Offset) 00088 llvm::Type *I8Ptr = CGF.Int8PtrTy; 00089 QualType IvarTy = Ivar->getType(); 00090 llvm::Type *LTy = CGF.CGM.getTypes().ConvertTypeForMem(IvarTy); 00091 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, I8Ptr); 00092 V = CGF.Builder.CreateInBoundsGEP(V, Offset, "add.ptr"); 00093 V = CGF.Builder.CreateBitCast(V, llvm::PointerType::getUnqual(LTy)); 00094 00095 if (!Ivar->isBitField()) { 00096 LValue LV = CGF.MakeNaturalAlignAddrLValue(V, IvarTy); 00097 LV.getQuals().addCVRQualifiers(CVRQualifiers); 00098 return LV; 00099 } 00100 00101 // We need to compute an access strategy for this bit-field. We are given the 00102 // offset to the first byte in the bit-field, the sub-byte offset is taken 00103 // from the original layout. We reuse the normal bit-field access strategy by 00104 // treating this as an access to a struct where the bit-field is in byte 0, 00105 // and adjust the containing type size as appropriate. 00106 // 00107 // FIXME: Note that currently we make a very conservative estimate of the 00108 // alignment of the bit-field, because (a) it is not clear what guarantees the 00109 // runtime makes us, and (b) we don't have a way to specify that the struct is 00110 // at an alignment plus offset. 00111 // 00112 // Note, there is a subtle invariant here: we can only call this routine on 00113 // non-synthesized ivars but we may be called for synthesized ivars. However, 00114 // a synthesized ivar can never be a bit-field, so this is safe. 00115 const ASTRecordLayout &RL = 00116 CGF.CGM.getContext().getASTObjCInterfaceLayout(OID); 00117 uint64_t TypeSizeInBits = CGF.CGM.getContext().toBits(RL.getSize()); 00118 uint64_t FieldBitOffset = LookupFieldBitOffset(CGF.CGM, OID, 0, Ivar); 00119 uint64_t BitOffset = FieldBitOffset % CGF.CGM.getContext().getCharWidth(); 00120 uint64_t ContainingTypeAlign = CGF.CGM.getContext().getTargetInfo().getCharAlign(); 00121 uint64_t ContainingTypeSize = TypeSizeInBits - (FieldBitOffset - BitOffset); 00122 uint64_t BitFieldSize = Ivar->getBitWidthValue(CGF.getContext()); 00123 00124 // Allocate a new CGBitFieldInfo object to describe this access. 00125 // 00126 // FIXME: This is incredibly wasteful, these should be uniqued or part of some 00127 // layout object. However, this is blocked on other cleanups to the 00128 // Objective-C code, so for now we just live with allocating a bunch of these 00129 // objects. 00130 CGBitFieldInfo *Info = new (CGF.CGM.getContext()) CGBitFieldInfo( 00131 CGBitFieldInfo::MakeInfo(CGF.CGM.getTypes(), Ivar, BitOffset, BitFieldSize, 00132 ContainingTypeSize, ContainingTypeAlign)); 00133 00134 return LValue::MakeBitfield(V, *Info, 00135 IvarTy.withCVRQualifiers(CVRQualifiers)); 00136 } 00137 00138 namespace { 00139 struct CatchHandler { 00140 const VarDecl *Variable; 00141 const Stmt *Body; 00142 llvm::BasicBlock *Block; 00143 llvm::Value *TypeInfo; 00144 }; 00145 00146 struct CallObjCEndCatch : EHScopeStack::Cleanup { 00147 CallObjCEndCatch(bool MightThrow, llvm::Value *Fn) : 00148 MightThrow(MightThrow), Fn(Fn) {} 00149 bool MightThrow; 00150 llvm::Value *Fn; 00151 00152 void Emit(CodeGenFunction &CGF, Flags flags) { 00153 if (!MightThrow) { 00154 CGF.Builder.CreateCall(Fn)->setDoesNotThrow(); 00155 return; 00156 } 00157 00158 CGF.EmitCallOrInvoke(Fn); 00159 } 00160 }; 00161 } 00162 00163 00164 void CGObjCRuntime::EmitTryCatchStmt(CodeGenFunction &CGF, 00165 const ObjCAtTryStmt &S, 00166 llvm::Constant *beginCatchFn, 00167 llvm::Constant *endCatchFn, 00168 llvm::Constant *exceptionRethrowFn) { 00169 // Jump destination for falling out of catch bodies. 00170 CodeGenFunction::JumpDest Cont; 00171 if (S.getNumCatchStmts()) 00172 Cont = CGF.getJumpDestInCurrentScope("eh.cont"); 00173 00174 CodeGenFunction::FinallyInfo FinallyInfo; 00175 if (const ObjCAtFinallyStmt *Finally = S.getFinallyStmt()) 00176 FinallyInfo.enter(CGF, Finally->getFinallyBody(), 00177 beginCatchFn, endCatchFn, exceptionRethrowFn); 00178 00179 SmallVector<CatchHandler, 8> Handlers; 00180 00181 // Enter the catch, if there is one. 00182 if (S.getNumCatchStmts()) { 00183 for (unsigned I = 0, N = S.getNumCatchStmts(); I != N; ++I) { 00184 const ObjCAtCatchStmt *CatchStmt = S.getCatchStmt(I); 00185 const VarDecl *CatchDecl = CatchStmt->getCatchParamDecl(); 00186 00187 Handlers.push_back(CatchHandler()); 00188 CatchHandler &Handler = Handlers.back(); 00189 Handler.Variable = CatchDecl; 00190 Handler.Body = CatchStmt->getCatchBody(); 00191 Handler.Block = CGF.createBasicBlock("catch"); 00192 00193 // @catch(...) always matches. 00194 if (!CatchDecl) { 00195 Handler.TypeInfo = 0; // catch-all 00196 // Don't consider any other catches. 00197 break; 00198 } 00199 00200 Handler.TypeInfo = GetEHType(CatchDecl->getType()); 00201 } 00202 00203 EHCatchScope *Catch = CGF.EHStack.pushCatch(Handlers.size()); 00204 for (unsigned I = 0, E = Handlers.size(); I != E; ++I) 00205 Catch->setHandler(I, Handlers[I].TypeInfo, Handlers[I].Block); 00206 } 00207 00208 // Emit the try body. 00209 CGF.EmitStmt(S.getTryBody()); 00210 00211 // Leave the try. 00212 if (S.getNumCatchStmts()) 00213 CGF.popCatchScope(); 00214 00215 // Remember where we were. 00216 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP(); 00217 00218 // Emit the handlers. 00219 for (unsigned I = 0, E = Handlers.size(); I != E; ++I) { 00220 CatchHandler &Handler = Handlers[I]; 00221 00222 CGF.EmitBlock(Handler.Block); 00223 llvm::Value *RawExn = CGF.getExceptionFromSlot(); 00224 00225 // Enter the catch. 00226 llvm::Value *Exn = RawExn; 00227 if (beginCatchFn) { 00228 Exn = CGF.Builder.CreateCall(beginCatchFn, RawExn, "exn.adjusted"); 00229 cast<llvm::CallInst>(Exn)->setDoesNotThrow(); 00230 } 00231 00232 CodeGenFunction::LexicalScope cleanups(CGF, Handler.Body->getSourceRange()); 00233 00234 if (endCatchFn) { 00235 // Add a cleanup to leave the catch. 00236 bool EndCatchMightThrow = (Handler.Variable == 0); 00237 00238 CGF.EHStack.pushCleanup<CallObjCEndCatch>(NormalAndEHCleanup, 00239 EndCatchMightThrow, 00240 endCatchFn); 00241 } 00242 00243 // Bind the catch parameter if it exists. 00244 if (const VarDecl *CatchParam = Handler.Variable) { 00245 llvm::Type *CatchType = CGF.ConvertType(CatchParam->getType()); 00246 llvm::Value *CastExn = CGF.Builder.CreateBitCast(Exn, CatchType); 00247 00248 CGF.EmitAutoVarDecl(*CatchParam); 00249 00250 llvm::Value *CatchParamAddr = CGF.GetAddrOfLocalVar(CatchParam); 00251 00252 switch (CatchParam->getType().getQualifiers().getObjCLifetime()) { 00253 case Qualifiers::OCL_Strong: 00254 CastExn = CGF.EmitARCRetainNonBlock(CastExn); 00255 // fallthrough 00256 00257 case Qualifiers::OCL_None: 00258 case Qualifiers::OCL_ExplicitNone: 00259 case Qualifiers::OCL_Autoreleasing: 00260 CGF.Builder.CreateStore(CastExn, CatchParamAddr); 00261 break; 00262 00263 case Qualifiers::OCL_Weak: 00264 CGF.EmitARCInitWeak(CatchParamAddr, CastExn); 00265 break; 00266 } 00267 } 00268 00269 CGF.ObjCEHValueStack.push_back(Exn); 00270 CGF.EmitStmt(Handler.Body); 00271 CGF.ObjCEHValueStack.pop_back(); 00272 00273 // Leave any cleanups associated with the catch. 00274 cleanups.ForceCleanup(); 00275 00276 CGF.EmitBranchThroughCleanup(Cont); 00277 } 00278 00279 // Go back to the try-statement fallthrough. 00280 CGF.Builder.restoreIP(SavedIP); 00281 00282 // Pop out of the finally. 00283 if (S.getFinallyStmt()) 00284 FinallyInfo.exit(CGF); 00285 00286 if (Cont.isValid()) 00287 CGF.EmitBlock(Cont.getBlock()); 00288 } 00289 00290 namespace { 00291 struct CallSyncExit : EHScopeStack::Cleanup { 00292 llvm::Value *SyncExitFn; 00293 llvm::Value *SyncArg; 00294 CallSyncExit(llvm::Value *SyncExitFn, llvm::Value *SyncArg) 00295 : SyncExitFn(SyncExitFn), SyncArg(SyncArg) {} 00296 00297 void Emit(CodeGenFunction &CGF, Flags flags) { 00298 CGF.Builder.CreateCall(SyncExitFn, SyncArg)->setDoesNotThrow(); 00299 } 00300 }; 00301 } 00302 00303 void CGObjCRuntime::EmitAtSynchronizedStmt(CodeGenFunction &CGF, 00304 const ObjCAtSynchronizedStmt &S, 00305 llvm::Function *syncEnterFn, 00306 llvm::Function *syncExitFn) { 00307 CodeGenFunction::RunCleanupsScope cleanups(CGF); 00308 00309 // Evaluate the lock operand. This is guaranteed to dominate the 00310 // ARC release and lock-release cleanups. 00311 const Expr *lockExpr = S.getSynchExpr(); 00312 llvm::Value *lock; 00313 if (CGF.getLangOpts().ObjCAutoRefCount) { 00314 lock = CGF.EmitARCRetainScalarExpr(lockExpr); 00315 lock = CGF.EmitObjCConsumeObject(lockExpr->getType(), lock); 00316 } else { 00317 lock = CGF.EmitScalarExpr(lockExpr); 00318 } 00319 lock = CGF.Builder.CreateBitCast(lock, CGF.VoidPtrTy); 00320 00321 // Acquire the lock. 00322 CGF.Builder.CreateCall(syncEnterFn, lock)->setDoesNotThrow(); 00323 00324 // Register an all-paths cleanup to release the lock. 00325 CGF.EHStack.pushCleanup<CallSyncExit>(NormalAndEHCleanup, syncExitFn, lock); 00326 00327 // Emit the body of the statement. 00328 CGF.EmitStmt(S.getSynchBody()); 00329 } 00330 00331 /// Compute the pointer-to-function type to which a message send 00332 /// should be casted in order to correctly call the given method 00333 /// with the given arguments. 00334 /// 00335 /// \param method - may be null 00336 /// \param resultType - the result type to use if there's no method 00337 /// \param argInfo - the actual arguments, including implicit ones 00338 CGObjCRuntime::MessageSendInfo 00339 CGObjCRuntime::getMessageSendInfo(const ObjCMethodDecl *method, 00340 QualType resultType, 00341 CallArgList &callArgs) { 00342 // If there's a method, use information from that. 00343 if (method) { 00344 const CGFunctionInfo &signature = 00345 CGM.getTypes().arrangeObjCMessageSendSignature(method, callArgs[0].Ty); 00346 00347 llvm::PointerType *signatureType = 00348 CGM.getTypes().GetFunctionType(signature)->getPointerTo(); 00349 00350 // If that's not variadic, there's no need to recompute the ABI 00351 // arrangement. 00352 if (!signature.isVariadic()) 00353 return MessageSendInfo(signature, signatureType); 00354 00355 // Otherwise, there is. 00356 FunctionType::ExtInfo einfo = signature.getExtInfo(); 00357 const CGFunctionInfo &argsInfo = 00358 CGM.getTypes().arrangeFunctionCall(resultType, callArgs, einfo, 00359 signature.getRequiredArgs()); 00360 00361 return MessageSendInfo(argsInfo, signatureType); 00362 } 00363 00364 // There's no method; just use a default CC. 00365 const CGFunctionInfo &argsInfo = 00366 CGM.getTypes().arrangeFunctionCall(resultType, callArgs, 00367 FunctionType::ExtInfo(), 00368 RequiredArgs::All); 00369 00370 // Derive the signature to call from that. 00371 llvm::PointerType *signatureType = 00372 CGM.getTypes().GetFunctionType(argsInfo)->getPointerTo(); 00373 return MessageSendInfo(argsInfo, signatureType); 00374 }