CGObjCRuntime.cpp 14 KB

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