clang API Documentation

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