blob: 65b57d6b7a967c04851e12450e02794745413349 [file] [log] [blame]
Steve Naroffb29b4272008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattner77cd2a02007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner77cd2a02007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Eli Friedman39d7c4d2009-05-18 22:50:54 +000014#include "clang/Frontend/ASTConsumers.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Steve Naroff8599e7a2008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner07506182007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner26de4652007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +000023#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000025#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000026#include "llvm/ADT/SmallPtrSet.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000027#include "llvm/ADT/OwningPtr.h"
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +000028#include "llvm/ADT/DenseSet.h"
Fariborz Jahanian72952fc2010-03-01 23:36:21 +000029
Chris Lattner77cd2a02007-10-11 00:43:27 +000030using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000031using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000032
Chris Lattner77cd2a02007-10-11 00:43:27 +000033namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000034 class RewriteObjC : public ASTConsumer {
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000035 enum {
36 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
37 block, ... */
38 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
39 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
40 __block variable */
41 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
42 helpers */
43 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
44 support routines */
45 BLOCK_BYREF_CURRENT_MAX = 256
46 };
47
48 enum {
49 BLOCK_NEEDS_FREE = (1 << 24),
50 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
51 BLOCK_HAS_CXX_OBJ = (1 << 26),
52 BLOCK_IS_GC = (1 << 27),
53 BLOCK_IS_GLOBAL = (1 << 28),
54 BLOCK_HAS_DESCRIPTOR = (1 << 29)
55 };
56
Chris Lattner2c64b7b2007-10-16 21:07:07 +000057 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000058 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000059 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000060 unsigned RewriteFailedDiag;
Steve Naroff8c565152008-12-05 17:03:39 +000061 unsigned TryFinallyContainsReturnDiag;
Mike Stump1eb44332009-09-09 15:08:12 +000062
Chris Lattner01c57482007-10-17 22:35:30 +000063 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000064 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000065 TranslationUnitDecl *TUDecl;
Chris Lattner2b2453a2009-01-17 06:22:33 +000066 FileID MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000067 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000068 SourceLocation LastIncLoc;
Mike Stump1eb44332009-09-09 15:08:12 +000069
Ted Kremeneka526c5c2008-01-07 19:49:32 +000070 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
71 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
72 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +000073 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000074 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
75 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000076 llvm::SmallVector<Stmt *, 32> Stmts;
77 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroff621edce2009-04-29 16:37:50 +000078 // Remember all the @protocol(<expr>) expressions.
79 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +000080
81 llvm::DenseSet<uint64_t> CopyDestroyCache;
82
Steve Naroffd82a9ab2008-03-15 00:55:56 +000083 unsigned NumObjCStringLiterals;
Mike Stump1eb44332009-09-09 15:08:12 +000084
Steve Naroffebf2b562007-10-23 23:50:29 +000085 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000086 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000087 FunctionDecl *MsgSendStretFunctionDecl;
88 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000089 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000090 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000091 FunctionDecl *GetMetaClassFunctionDecl;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +000092 FunctionDecl *GetSuperClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000093 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000094 FunctionDecl *CFStringFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000095 FunctionDecl *SuperContructorFunctionDecl;
Mike Stump1eb44332009-09-09 15:08:12 +000096
Steve Naroffbeaf2992007-11-03 11:27:19 +000097 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000098 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000099 RecordDecl *NSStringRecord;
Mike Stump1eb44332009-09-09 15:08:12 +0000100
Fariborz Jahanianb586cce2008-01-16 00:09:11 +0000101 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000102 int BcLabelCount;
Mike Stump1eb44332009-09-09 15:08:12 +0000103
Steve Naroff874e2322007-11-15 10:28:18 +0000104 // Needed for super.
Steve Naroff54055232008-10-27 17:20:55 +0000105 ObjCMethodDecl *CurMethodDef;
Steve Naroff874e2322007-11-15 10:28:18 +0000106 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000107 RecordDecl *ConstantStringDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000108
Steve Naroff621edce2009-04-29 16:37:50 +0000109 TypeDecl *ProtocolTypeDecl;
110 QualType getProtocolType();
Mike Stump1eb44332009-09-09 15:08:12 +0000111
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000112 // Needed for header files being rewritten
113 bool IsHeader;
Mike Stump1eb44332009-09-09 15:08:12 +0000114
Steve Naroffa7b402d2008-03-28 22:26:09 +0000115 std::string InFileName;
Eli Friedman66d6f042009-05-18 22:20:00 +0000116 llvm::raw_ostream* OutFile;
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000117
118 bool SilenceRewriteMacroWarning;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000119 bool objc_impl_method;
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000120
Steve Naroffba92b2e2008-03-27 22:29:16 +0000121 std::string Preamble;
Steve Naroff54055232008-10-27 17:20:55 +0000122
123 // Block expressions.
124 llvm::SmallVector<BlockExpr *, 32> Blocks;
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000125 llvm::SmallVector<int, 32> InnerDeclRefsCount;
126 llvm::SmallVector<BlockDeclRefExpr *, 32> InnerDeclRefs;
127
Steve Naroff54055232008-10-27 17:20:55 +0000128 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
Mike Stump1eb44332009-09-09 15:08:12 +0000129
Steve Naroff54055232008-10-27 17:20:55 +0000130 // Block related declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000131 llvm::SmallVector<ValueDecl *, 8> BlockByCopyDecls;
132 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
133 llvm::SmallVector<ValueDecl *, 8> BlockByRefDecls;
134 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000135 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff54055232008-10-27 17:20:55 +0000136 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000137 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
138
Steve Naroff54055232008-10-27 17:20:55 +0000139 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
140
Steve Naroffc77a6362008-12-04 16:24:46 +0000141 // This maps a property to it's assignment statement.
142 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Naroff8599e7a2008-12-08 16:43:47 +0000143 // This maps a property to it's synthesied message expression.
144 // This allows us to rewrite chained getters (e.g. o.a.b.c).
145 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
Mike Stump1eb44332009-09-09 15:08:12 +0000146
Steve Naroff4c3580e2008-12-04 23:50:32 +0000147 // This maps an original source AST to it's rewritten form. This allows
148 // us to avoid rewriting the same node twice (which is very uncommon).
149 // This is needed to support some of the exotic property rewriting.
150 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000151
Steve Naroff54055232008-10-27 17:20:55 +0000152 FunctionDecl *CurFunctionDef;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000153 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000154 VarDecl *GlobalVarDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000155
Steve Naroffb619d952008-12-09 12:56:34 +0000156 bool DisableReplaceStmt;
Mike Stump1eb44332009-09-09 15:08:12 +0000157
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000158 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000159 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000160 virtual void Initialize(ASTContext &context);
161
Chris Lattnerf04da132007-10-24 17:06:59 +0000162 // Top Level Driver code.
Chris Lattner682bf922009-03-29 16:50:03 +0000163 virtual void HandleTopLevelDecl(DeclGroupRef D) {
164 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
165 HandleTopLevelSingleDecl(*I);
166 }
167 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000168 void HandleDeclInMainFile(Decl *D);
Eli Friedman66d6f042009-05-18 22:20:00 +0000169 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000170 Diagnostic &D, const LangOptions &LOpts,
171 bool silenceMacroWarn);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000172
173 ~RewriteObjC() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000174
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000175 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump1eb44332009-09-09 15:08:12 +0000176
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000177 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000178 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump1eb44332009-09-09 15:08:12 +0000179
Steve Naroff4c3580e2008-12-04 23:50:32 +0000180 if (ReplacingStmt)
181 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000182
Steve Naroffb619d952008-12-09 12:56:34 +0000183 if (DisableReplaceStmt)
184 return; // Used when rewriting the assignment of a property setter.
185
Steve Naroff4c3580e2008-12-04 23:50:32 +0000186 // If replacement succeeded or warning disabled return with no warning.
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000187 if (!Rewrite.ReplaceStmt(Old, New)) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000188 ReplacedNodes[Old] = New;
189 return;
190 }
191 if (SilenceRewriteMacroWarning)
192 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000193 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
194 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000195 }
Steve Naroffb619d952008-12-09 12:56:34 +0000196
197 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
198 // Measaure the old text.
199 int Size = Rewrite.getRangeSize(SrcRange);
200 if (Size == -1) {
201 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
202 << Old->getSourceRange();
203 return;
204 }
205 // Get the new text.
206 std::string SStr;
207 llvm::raw_string_ostream S(SStr);
Chris Lattnere4f21422009-06-30 01:26:17 +0000208 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroffb619d952008-12-09 12:56:34 +0000209 const std::string &Str = S.str();
210
211 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000212 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroffb619d952008-12-09 12:56:34 +0000213 ReplacedNodes[Old] = New;
214 return;
215 }
216 if (SilenceRewriteMacroWarning)
217 return;
218 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
219 << Old->getSourceRange();
220 }
221
Benjamin Kramerd999b372010-02-14 14:14:16 +0000222 void InsertText(SourceLocation Loc, llvm::StringRef Str,
Steve Naroffba92b2e2008-03-27 22:29:16 +0000223 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000224 // If insertion succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000225 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000226 SilenceRewriteMacroWarning)
227 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000228
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000229 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
230 }
Mike Stump1eb44332009-09-09 15:08:12 +0000231
Chris Lattneraadaf782008-01-31 19:51:04 +0000232 void RemoveText(SourceLocation Loc, unsigned StrLen) {
233 // If removal succeeded or warning disabled return with no warning.
234 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
235 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000236
Chris Lattneraadaf782008-01-31 19:51:04 +0000237 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
238 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000239
Chris Lattneraadaf782008-01-31 19:51:04 +0000240 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Benjamin Kramerd999b372010-02-14 14:14:16 +0000241 llvm::StringRef Str) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000242 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000243 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattneraadaf782008-01-31 19:51:04 +0000244 SilenceRewriteMacroWarning)
245 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000246
Chris Lattneraadaf782008-01-31 19:51:04 +0000247 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
248 }
Mike Stump1eb44332009-09-09 15:08:12 +0000249
Chris Lattnerf04da132007-10-24 17:06:59 +0000250 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000251 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000252 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000253 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000254 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffa0876e82008-12-02 17:36:43 +0000255 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
256 ObjCImplementationDecl *IMD,
257 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000258 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000259 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000260 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000261 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
262 const FunctionType *&FPRetType);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000263 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
264 ValueDecl *VD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000265 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
266 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
267 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
268 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000269 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000270 void RewriteFunctionDecl(FunctionDecl *FD);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000271 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000272 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +0000273 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff4f95b752008-07-29 18:15:38 +0000274 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000275 bool needToScanForQualifiers(QualType T);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000276 bool isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000277 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000278 QualType getConstantStringStructType();
Steve Naroffbaf58c32008-05-31 14:15:04 +0000279 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump1eb44332009-09-09 15:08:12 +0000280
Chris Lattnerf04da132007-10-24 17:06:59 +0000281 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000282 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroffc77a6362008-12-04 16:24:46 +0000283 void CollectPropertySetters(Stmt *S);
Mike Stump1eb44332009-09-09 15:08:12 +0000284
Steve Naroff8599e7a2008-12-08 16:43:47 +0000285 Stmt *CurrentBody;
286 ParentMap *PropParentMap; // created lazily.
Mike Stump1eb44332009-09-09 15:08:12 +0000287
Chris Lattnere64b7772007-10-24 16:57:36 +0000288 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +0000289 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart,
290 bool &replaced);
291 Stmt *RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced);
Steve Naroffc77a6362008-12-04 16:24:46 +0000292 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Mike Stump1eb44332009-09-09 15:08:12 +0000293 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroffb619d952008-12-09 12:56:34 +0000294 SourceRange SrcRange);
Steve Naroffb42f8412007-11-05 14:50:49 +0000295 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000296 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000297 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000298 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffb85e77a2009-12-05 21:43:12 +0000299 void WarnAboutReturnGotoStmts(Stmt *S);
300 void HasReturnStmts(Stmt *S, bool &hasReturns);
301 void RewriteTryReturnStmts(Stmt *S);
302 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000303 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000304 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000305 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
306 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
307 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000308 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
309 SourceLocation OrigEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000310 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +0000311 Expr **args, unsigned nargs,
312 SourceLocation StartLoc=SourceLocation(),
313 SourceLocation EndLoc=SourceLocation());
314 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
315 SourceLocation StartLoc=SourceLocation(),
316 SourceLocation EndLoc=SourceLocation());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000317 Stmt *RewriteBreakStmt(BreakStmt *S);
318 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000319 void SynthCountByEnumWithState(std::string &buf);
Mike Stump1eb44332009-09-09 15:08:12 +0000320
Steve Naroff09b266e2007-10-30 23:14:51 +0000321 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000322 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000323 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000324 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000325 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000326 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000327 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000328 void SynthGetSuperClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000329 void SynthSelGetUidFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000330 void SynthSuperContructorFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000331
Chris Lattnerf04da132007-10-24 17:06:59 +0000332 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000333 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000334 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000335
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000336 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000337 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Douglas Gregor653f1b12009-04-23 01:02:12 +0000339 template<typename MethodIterator>
340 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
341 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000342 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000343 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000344 const char *ClassName,
345 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000346
Steve Naroff621edce2009-04-29 16:37:50 +0000347 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
348 const char *prefix,
349 const char *ClassName,
350 std::string &Result);
351 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Mike Stump1eb44332009-09-09 15:08:12 +0000352 const char *prefix,
Steve Naroff621edce2009-04-29 16:37:50 +0000353 const char *ClassName,
354 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000355 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000356 std::string &Result);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000357 void SynthesizeIvarOffsetComputation(ObjCContainerDecl *IDecl,
Mike Stump1eb44332009-09-09 15:08:12 +0000358 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000359 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000360 void RewriteImplementations();
361 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000362
Steve Naroff54055232008-10-27 17:20:55 +0000363 // Block rewriting.
Mike Stump1eb44332009-09-09 15:08:12 +0000364 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff54055232008-10-27 17:20:55 +0000365 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump1eb44332009-09-09 15:08:12 +0000366
Steve Naroff54055232008-10-27 17:20:55 +0000367 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
368 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump1eb44332009-09-09 15:08:12 +0000369
370 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000371 void RewriteBlockCall(CallExpr *Exp);
372 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000373 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +0000374 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +0000375 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000376 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
Steve Naroff54055232008-10-27 17:20:55 +0000377 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000378
379 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Steve Naroff54055232008-10-27 17:20:55 +0000380 const char *funcName, std::string Tag);
Mike Stump1eb44332009-09-09 15:08:12 +0000381 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Steve Naroff54055232008-10-27 17:20:55 +0000382 const char *funcName, std::string Tag);
Steve Naroff01aec112009-12-06 21:14:13 +0000383 std::string SynthesizeBlockImpl(BlockExpr *CE,
384 std::string Tag, std::string Desc);
385 std::string SynthesizeBlockDescriptor(std::string DescTag,
386 std::string ImplTag,
387 int i, const char *funcName,
388 unsigned hasCopy);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +0000389 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff54055232008-10-27 17:20:55 +0000390 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000391 const char *FunName);
Steve Naroff3d7e7862009-12-05 15:55:59 +0000392 void RewriteRecordBody(RecordDecl *RD);
Mike Stump1eb44332009-09-09 15:08:12 +0000393
Steve Naroff54055232008-10-27 17:20:55 +0000394 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000395 void GetBlockDeclRefExprs(Stmt *S);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000396 void GetInnerBlockDeclRefExprs(Stmt *S,
397 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +0000398 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
Mike Stump1eb44332009-09-09 15:08:12 +0000399
Steve Naroff54055232008-10-27 17:20:55 +0000400 // We avoid calling Type::isBlockPointerType(), since it operates on the
401 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000402 bool isTopLevelBlockPointerType(QualType T) {
403 return isa<BlockPointerType>(T);
404 }
Mike Stump1eb44332009-09-09 15:08:12 +0000405
Steve Naroff54055232008-10-27 17:20:55 +0000406 // FIXME: This predicate seems like it would be useful to add to ASTContext.
407 bool isObjCType(QualType T) {
408 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
409 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000410
Steve Naroff54055232008-10-27 17:20:55 +0000411 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000412
Steve Naroff54055232008-10-27 17:20:55 +0000413 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
414 OCT == Context->getCanonicalType(Context->getObjCClassType()))
415 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000416
Ted Kremenek6217b802009-07-29 21:53:49 +0000417 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000418 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000419 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000420 return true;
421 }
422 return false;
423 }
424 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000425 void GetExtentOfArgList(const char *Name, const char *&LParen,
426 const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000427 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump1eb44332009-09-09 15:08:12 +0000428
Steve Narofffa15fd92008-10-28 20:29:00 +0000429 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000430 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
431 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
Mike Stump1eb44332009-09-09 15:08:12 +0000432
Steve Naroff621edce2009-04-29 16:37:50 +0000433 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000434 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000435 if (From[i] == '"')
436 To += "\\\"";
437 else
438 To += From[i];
439 }
440 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000441 };
John McCall9d125032010-01-15 18:39:57 +0000442
443 // Helper function: create a CStyleCastExpr with trivial type source info.
444 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
445 CastExpr::CastKind Kind, Expr *E) {
446 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
447 return new (Ctx) CStyleCastExpr(Ty, Kind, E, TInfo,
448 SourceLocation(), SourceLocation());
449 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000450}
451
Mike Stump1eb44332009-09-09 15:08:12 +0000452void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
453 NamedDecl *D) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000454 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000455 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000456 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000457 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000458 // All the args are checked/rewritten. Don't call twice!
459 RewriteBlockPointerDecl(D);
460 break;
461 }
462 }
463}
464
465void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000466 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000467 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000468 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000469}
470
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000471static bool IsHeaderFile(const std::string &Filename) {
472 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000473
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000474 if (DotPos == std::string::npos) {
475 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000476 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000477 }
Mike Stump1eb44332009-09-09 15:08:12 +0000478
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000479 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
480 // C header: .h
481 // C++ header: .hh or .H;
482 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000483}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000484
Eli Friedman66d6f042009-05-18 22:20:00 +0000485RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000486 Diagnostic &D, const LangOptions &LOpts,
487 bool silenceMacroWarn)
488 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
489 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000490 IsHeader = IsHeaderFile(inFile);
Mike Stump1eb44332009-09-09 15:08:12 +0000491 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000492 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump1eb44332009-09-09 15:08:12 +0000493 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000494 "rewriter doesn't support user-specified control flow semantics "
495 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000496}
497
Eli Friedmanbce831b2009-05-18 22:29:17 +0000498ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
499 llvm::raw_ostream* OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000500 Diagnostic &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000501 const LangOptions &LOpts,
502 bool SilenceRewriteMacroWarning) {
503 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000504}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000505
Steve Naroffb29b4272008-04-14 22:03:09 +0000506void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000507 Context = &context;
508 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000509 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000510 MsgSendFunctionDecl = 0;
511 MsgSendSuperFunctionDecl = 0;
512 MsgSendStretFunctionDecl = 0;
513 MsgSendSuperStretFunctionDecl = 0;
514 MsgSendFpretFunctionDecl = 0;
515 GetClassFunctionDecl = 0;
516 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000517 GetSuperClassFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000518 SelGetUidFunctionDecl = 0;
519 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000520 ConstantStringClassReference = 0;
521 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000522 CurMethodDef = 0;
523 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000524 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000525 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000526 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000527 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000528 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000529 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000530 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000531 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000532 PropParentMap = 0;
533 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000534 DisableReplaceStmt = false;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000535 objc_impl_method = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000536
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000537 // Get the ID and start/end of the main file.
538 MainFileID = SM->getMainFileID();
539 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
540 MainFileStart = MainBuf->getBufferStart();
541 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000542
Chris Lattner2c78b872009-04-14 23:22:57 +0000543 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump1eb44332009-09-09 15:08:12 +0000544
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000545 // declaring objc_selector outside the parameter list removes a silly
546 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000547 if (IsHeader)
Steve Naroff62c26322009-02-03 20:39:18 +0000548 Preamble = "#pragma once\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000549 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000550 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000551 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000552 if (LangOpts.Microsoft) {
553 // Add a constructor for creating temporary objects.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000554 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
555 ": ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000556 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000557 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000558 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000559 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
560 Preamble += "typedef struct objc_object Protocol;\n";
561 Preamble += "#define _REWRITER_typedef_Protocol\n";
562 Preamble += "#endif\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000563 if (LangOpts.Microsoft) {
564 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
565 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
566 } else
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000567 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000568 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000569 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000570 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000571 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000572 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000573 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000574 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000575 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000576 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000577 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000578 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000579 Preamble += "(const char *);\n";
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000580 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
581 Preamble += "(struct objc_class *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000582 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000583 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000584 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
585 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
586 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
587 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
588 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000589 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000590 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000591 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
592 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
593 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000594 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
595 Preamble += "struct __objcFastEnumerationState {\n\t";
596 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000597 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000598 Preamble += "unsigned long *mutationsPtr;\n\t";
599 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000600 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000601 Preamble += "#define __FASTENUMERATIONSTATE\n";
602 Preamble += "#endif\n";
603 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
604 Preamble += "struct __NSConstantStringImpl {\n";
605 Preamble += " int *isa;\n";
606 Preamble += " int flags;\n";
607 Preamble += " char *str;\n";
608 Preamble += " long length;\n";
609 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000610 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
611 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
612 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000613 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000614 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000615 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
616 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000617 // Blocks preamble.
618 Preamble += "#ifndef BLOCK_IMPL\n";
619 Preamble += "#define BLOCK_IMPL\n";
620 Preamble += "struct __block_impl {\n";
621 Preamble += " void *isa;\n";
622 Preamble += " int Flags;\n";
Steve Naroff01aec112009-12-06 21:14:13 +0000623 Preamble += " int Reserved;\n";
Steve Naroff54055232008-10-27 17:20:55 +0000624 Preamble += " void *FuncPtr;\n";
625 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000626 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroffc9c1e9c2009-12-06 01:52:22 +0000627 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000628 Preamble += "extern \"C\" __declspec(dllexport) "
629 "void _Block_object_assign(void *, const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000630 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
631 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
632 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
633 Preamble += "#else\n";
Steve Naroffcd826372010-01-05 18:09:31 +0000634 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
635 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000636 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
637 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
638 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000639 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000640 if (LangOpts.Microsoft) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000641 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
642 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000643 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
Steve Naroffa48396e2008-10-27 18:50:14 +0000644 Preamble += "#define __attribute__(X)\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000645 Preamble += "#endif\n";
Fariborz Jahanian34204192010-01-15 22:29:39 +0000646 Preamble += "#define __weak\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000647 }
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000648 else {
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000649 Preamble += "#define __block\n";
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000650 Preamble += "#define __weak\n";
651 }
Fariborz Jahaniandf496522010-03-02 01:19:04 +0000652 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
653 // as this avoids warning in any 64bit/32bit compilation model.
654 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000655}
656
657
Chris Lattnerf04da132007-10-24 17:06:59 +0000658//===----------------------------------------------------------------------===//
659// Top Level Driver Code
660//===----------------------------------------------------------------------===//
661
Chris Lattner682bf922009-03-29 16:50:03 +0000662void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremeneke50187a2010-02-05 21:28:51 +0000663 if (Diags.hasErrorOccurred())
664 return;
665
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000666 // Two cases: either the decl could be in the main file, or it could be in a
667 // #included file. If the former, rewrite it now. If the later, check to see
668 // if we rewrote the #include/#import.
669 SourceLocation Loc = D->getLocation();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000670 Loc = SM->getInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000671
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000672 // If this is for a builtin, ignore it.
673 if (Loc.isInvalid()) return;
674
Steve Naroffebf2b562007-10-23 23:50:29 +0000675 // Look for built-in declarations that we need to refer during the rewrite.
676 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000677 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000678 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000679 // declared in <Foundation/NSString.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +0000680 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000681 ConstantStringClassReference = FVD;
682 return;
683 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000684 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000685 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000686 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000687 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000688 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000689 RewriteProtocolDecl(PD);
Mike Stump1eb44332009-09-09 15:08:12 +0000690 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000691 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000692 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000693 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
694 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000695 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
696 DIEnd = LSD->decls_end();
Douglas Gregord0434102009-01-09 00:49:46 +0000697 DI != DIEnd; ++DI)
Chris Lattner682bf922009-03-29 16:50:03 +0000698 HandleTopLevelSingleDecl(*DI);
Steve Naroffebf2b562007-10-23 23:50:29 +0000699 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000700 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000701 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000702 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000703}
704
Chris Lattnerf04da132007-10-24 17:06:59 +0000705//===----------------------------------------------------------------------===//
706// Syntactic (non-AST) Rewriting Code
707//===----------------------------------------------------------------------===//
708
Steve Naroffb29b4272008-04-14 22:03:09 +0000709void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000710 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000711 llvm::StringRef MainBuf = SM->getBufferData(MainFileID);
712 const char *MainBufStart = MainBuf.begin();
713 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000714 size_t ImportLen = strlen("import");
Mike Stump1eb44332009-09-09 15:08:12 +0000715
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000716 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000717 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
718 if (*BufPtr == '#') {
719 if (++BufPtr == MainBufEnd)
720 return;
721 while (*BufPtr == ' ' || *BufPtr == '\t')
722 if (++BufPtr == MainBufEnd)
723 return;
724 if (!strncmp(BufPtr, "import", ImportLen)) {
725 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000726 SourceLocation ImportLoc =
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000727 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000728 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000729 BufPtr += ImportLen;
730 }
731 }
732 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000733}
734
Steve Naroffb29b4272008-04-14 22:03:09 +0000735void RewriteObjC::RewriteTabs() {
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000736 llvm::StringRef MainBuf = SM->getBufferData(MainFileID);
737 const char *MainBufStart = MainBuf.begin();
738 const char *MainBufEnd = MainBuf.end();
Mike Stump1eb44332009-09-09 15:08:12 +0000739
Chris Lattnerf04da132007-10-24 17:06:59 +0000740 // Loop over the whole file, looking for tabs.
741 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
742 if (*BufPtr != '\t')
743 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000744
Chris Lattnerf04da132007-10-24 17:06:59 +0000745 // Okay, we found a tab. This tab will turn into at least one character,
746 // but it depends on which 'virtual column' it is in. Compute that now.
747 unsigned VCol = 0;
748 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
749 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
750 ++VCol;
Mike Stump1eb44332009-09-09 15:08:12 +0000751
Chris Lattnerf04da132007-10-24 17:06:59 +0000752 // Okay, now that we know the virtual column, we know how many spaces to
753 // insert. We assume 8-character tab-stops.
754 unsigned Spaces = 8-(VCol & 7);
Mike Stump1eb44332009-09-09 15:08:12 +0000755
Chris Lattnerf04da132007-10-24 17:06:59 +0000756 // Get the location of the tab.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000757 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
758 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Mike Stump1eb44332009-09-09 15:08:12 +0000759
Chris Lattnerf04da132007-10-24 17:06:59 +0000760 // Rewrite the single tab character into a sequence of spaces.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000761 ReplaceText(TabLoc, 1, llvm::StringRef(" ", Spaces));
Chris Lattnerf04da132007-10-24 17:06:59 +0000762 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000763}
764
Steve Naroffeb0646c2008-12-02 15:48:25 +0000765static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
766 ObjCIvarDecl *OID) {
767 std::string S;
768 S = "((struct ";
769 S += ClassDecl->getIdentifier()->getName();
770 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000771 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000772 return S;
773}
774
Steve Naroffa0876e82008-12-02 17:36:43 +0000775void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
776 ObjCImplementationDecl *IMD,
777 ObjCCategoryImplDecl *CID) {
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000778 static bool objcGetPropertyDefined = false;
779 static bool objcSetPropertyDefined = false;
Steve Naroffd40910b2008-12-01 20:33:01 +0000780 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000781 InsertText(startLoc, "// ");
Steve Naroffeb0646c2008-12-02 15:48:25 +0000782 const char *startBuf = SM->getCharacterData(startLoc);
783 assert((*startBuf == '@') && "bogus @synthesize location");
784 const char *semiBuf = strchr(startBuf, ';');
785 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000786 SourceLocation onePastSemiLoc =
787 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000788
789 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
790 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000791
Steve Naroffeb0646c2008-12-02 15:48:25 +0000792 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000793 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000794 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000795 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000796
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000797 if (!OID)
798 return;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000799 unsigned Attributes = PD->getPropertyAttributes();
800 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
801 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
802 ObjCPropertyDecl::OBJC_PR_copy));
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000803 std::string Getr;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000804 if (GenGetProperty && !objcGetPropertyDefined) {
805 objcGetPropertyDefined = true;
806 // FIXME. Is this attribute correct in all cases?
807 Getr = "\nextern \"C\" __declspec(dllimport) "
808 "id objc_getProperty(id, SEL, long, bool);\n";
809 }
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000810 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
811 Getr += "{ ";
812 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff3539cdb2008-12-02 17:54:50 +0000813 // See objc-act.c:objc_synthesize_new_getter() for details.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000814 if (GenGetProperty) {
815 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
816 Getr += "typedef ";
817 const FunctionType *FPRetType = 0;
818 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
819 FPRetType);
820 Getr += " _TYPE";
821 if (FPRetType) {
822 Getr += ")"; // close the precedence "scope" for "*".
823
824 // Now, emit the argument types (if any).
825 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
826 Getr += "(";
827 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
828 if (i) Getr += ", ";
829 std::string ParamStr = FT->getArgType(i).getAsString();
830 Getr += ParamStr;
831 }
832 if (FT->isVariadic()) {
833 if (FT->getNumArgs()) Getr += ", ";
834 Getr += "...";
835 }
836 Getr += ")";
837 } else
838 Getr += "()";
839 }
840 Getr += ";\n";
841 Getr += "return (_TYPE)";
842 Getr += "objc_getProperty(self, _cmd, ";
843 SynthesizeIvarOffsetComputation(ClassDecl, OID, Getr);
844 Getr += ", 1)";
845 }
846 else
847 Getr += "return " + getIvarAccessString(ClassDecl, OID);
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000848 Getr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000849 InsertText(onePastSemiLoc, Getr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000850 if (PD->isReadOnly())
851 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000852
Steve Naroffeb0646c2008-12-02 15:48:25 +0000853 // Generate the 'setter' function.
854 std::string Setr;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000855 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
856 ObjCPropertyDecl::OBJC_PR_copy);
857 if (GenSetProperty && !objcSetPropertyDefined) {
858 objcSetPropertyDefined = true;
859 // FIXME. Is this attribute correct in all cases?
860 Setr = "\nextern \"C\" __declspec(dllimport) "
861 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
862 }
863
Steve Naroffeb0646c2008-12-02 15:48:25 +0000864 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000865 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000866 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff15f081d2008-12-03 00:56:33 +0000867 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000868 if (GenSetProperty) {
869 Setr += "objc_setProperty (self, _cmd, ";
870 SynthesizeIvarOffsetComputation(ClassDecl, OID, Setr);
871 Setr += ", (id)";
872 Setr += PD->getNameAsCString();
873 Setr += ", ";
874 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
875 Setr += "0, ";
876 else
877 Setr += "1, ";
878 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
879 Setr += "1)";
880 else
881 Setr += "0)";
882 }
883 else {
884 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
885 Setr += PD->getNameAsCString();
886 }
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000887 Setr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000888 InsertText(onePastSemiLoc, Setr);
Steve Naroffd40910b2008-12-01 20:33:01 +0000889}
Chris Lattner8a12c272007-10-11 18:38:32 +0000890
Steve Naroffb29b4272008-04-14 22:03:09 +0000891void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000892 // Get the start location and compute the semi location.
893 SourceLocation startLoc = ClassDecl->getLocation();
894 const char *startBuf = SM->getCharacterData(startLoc);
895 const char *semiPtr = strchr(startBuf, ';');
Mike Stump1eb44332009-09-09 15:08:12 +0000896
Chris Lattnerf04da132007-10-24 17:06:59 +0000897 // Translate to typedef's that forward reference structs with the same name
898 // as the class. As a convenience, we include the original declaration
899 // as a comment.
900 std::string typedefString;
Fariborz Jahanian91fbd122010-01-11 22:48:40 +0000901 typedefString += "// @class ";
902 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
903 I != E; ++I) {
904 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
905 typedefString += ForwardDecl->getNameAsString();
906 if (I+1 != E)
907 typedefString += ", ";
908 else
909 typedefString += ";\n";
910 }
911
Chris Lattner67956052009-02-20 18:04:31 +0000912 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
913 I != E; ++I) {
Ted Kremenek321c22f2009-11-18 00:28:11 +0000914 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff32174822007-11-09 12:50:28 +0000915 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000916 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000917 typedefString += "\n";
918 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000919 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000920 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000921 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000922 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000923 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000924 }
Mike Stump1eb44332009-09-09 15:08:12 +0000925
Steve Naroff934f2762007-10-24 22:48:43 +0000926 // Replace the @class with typedefs corresponding to the classes.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000927 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
Chris Lattnerf04da132007-10-24 17:06:59 +0000928}
929
Steve Naroffb29b4272008-04-14 22:03:09 +0000930void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000931 // When method is a synthesized one, such as a getter/setter there is
932 // nothing to rewrite.
933 if (Method->isSynthesized())
934 return;
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000935 SourceLocation LocStart = Method->getLocStart();
936 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000937
Chris Lattner30fc9332009-02-04 01:06:56 +0000938 if (SM->getInstantiationLineNumber(LocEnd) >
939 SM->getInstantiationLineNumber(LocStart)) {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000940 InsertText(LocStart, "#if 0\n");
941 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000942 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000943 InsertText(LocStart, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +0000944 }
945}
946
Mike Stump1eb44332009-09-09 15:08:12 +0000947void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000948 SourceLocation Loc = prop->getAtLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000949
Benjamin Kramerd999b372010-02-14 14:14:16 +0000950 ReplaceText(Loc, 0, "// ");
Steve Naroff6327e0d2009-01-11 01:06:09 +0000951 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000952}
953
Steve Naroffb29b4272008-04-14 22:03:09 +0000954void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000955 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000956
Steve Naroff423cb562007-10-30 13:30:57 +0000957 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000958 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000959
Fariborz Jahanian13751e32010-02-10 01:15:09 +0000960 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
961 E = CatDecl->prop_end(); I != E; ++I)
962 RewriteProperty(*I);
963
Mike Stump1eb44332009-09-09 15:08:12 +0000964 for (ObjCCategoryDecl::instmeth_iterator
965 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000966 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000967 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +0000968 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000969 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000970 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000971 RewriteMethodDeclaration(*I);
972
Steve Naroff423cb562007-10-30 13:30:57 +0000973 // Lastly, comment out the @end.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000974 ReplaceText(CatDecl->getAtEndRange().getBegin(), 0, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +0000975}
976
Steve Naroffb29b4272008-04-14 22:03:09 +0000977void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000978 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000979
Steve Naroff752d6ef2007-10-30 16:42:30 +0000980 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000981 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000982
983 for (ObjCProtocolDecl::instmeth_iterator
984 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000985 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000986 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000987 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000988 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000989 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000990 RewriteMethodDeclaration(*I);
991
Steve Naroff752d6ef2007-10-30 16:42:30 +0000992 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +0000993 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000994 ReplaceText(LocEnd, 0, "// ");
Steve Naroff8cc764c2007-11-14 15:03:57 +0000995
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000996 // Must comment out @optional/@required
997 const char *startBuf = SM->getCharacterData(LocStart);
998 const char *endBuf = SM->getCharacterData(LocEnd);
999 for (const char *p = startBuf; p < endBuf; p++) {
1000 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Steve Naroff8cc764c2007-11-14 15:03:57 +00001001 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001002 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump1eb44332009-09-09 15:08:12 +00001003
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001004 }
1005 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Steve Naroff8cc764c2007-11-14 15:03:57 +00001006 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001007 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump1eb44332009-09-09 15:08:12 +00001008
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001009 }
1010 }
Steve Naroff752d6ef2007-10-30 16:42:30 +00001011}
1012
Steve Naroffb29b4272008-04-14 22:03:09 +00001013void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001014 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +00001015 if (LocStart.isInvalid())
1016 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001017 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001018 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001019}
1020
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001021void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1022 const FunctionType *&FPRetType) {
1023 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001024 ResultStr += "id";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001025 else if (T->isFunctionPointerType() ||
1026 T->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001027 // needs special handling, since pointer-to-functions have special
1028 // syntax (where a decaration models use).
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001029 QualType retType = T;
Steve Narofff4312dc2008-12-11 19:29:16 +00001030 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001031 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001032 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001033 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001034 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001035 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Steve Narofff4312dc2008-12-11 19:29:16 +00001036 ResultStr += FPRetType->getResultType().getAsString();
1037 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +00001038 }
1039 } else
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001040 ResultStr += T.getAsString();
1041}
1042
1043void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
1044 std::string &ResultStr) {
1045 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1046 const FunctionType *FPRetType = 0;
1047 ResultStr += "\nstatic ";
1048 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001049 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +00001050
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001051 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001052 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001053
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001054 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001055 NameStr += "_I_";
1056 else
1057 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +00001058
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001059 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001060 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +00001061
1062 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +00001063 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001064 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001065 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001066 }
Mike Stump1eb44332009-09-09 15:08:12 +00001067 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +00001068 {
1069 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001070 int len = selString.size();
1071 for (int i = 0; i < len; i++)
1072 if (selString[i] == ':')
1073 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001074 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001075 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001076 // Remember this name for metadata emission
1077 MethodInternalNames[OMD] = NameStr;
1078 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001079
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001080 // Rewrite arguments
1081 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +00001082
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001083 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001084 if (OMD->isInstanceMethod()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001085 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001086 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +00001087 if (!LangOpts.Microsoft) {
1088 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
1089 ResultStr += "struct ";
1090 }
1091 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001092 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001093 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001094 }
1095 else
Steve Naroff621edce2009-04-29 16:37:50 +00001096 ResultStr += Context->getObjCClassType().getAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00001097
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001098 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001099 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001100 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +00001101
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001102 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +00001103 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1104 E = OMD->param_end(); PI != E; ++PI) {
1105 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001106 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +00001107 if (PDecl->getType()->isObjCQualifiedIdType()) {
1108 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001109 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +00001110 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001111 std::string Name = PDecl->getNameAsString();
Steve Naroff01f2ffa2008-12-11 21:05:33 +00001112 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroffc8ad87b2008-10-30 14:45:29 +00001113 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Ted Kremenek6217b802009-07-29 21:53:49 +00001114 const BlockPointerType *BPT = PDecl->getType()->getAs<BlockPointerType>();
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001115 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name,
1116 Context->PrintingPolicy);
Steve Naroffc8ad87b2008-10-30 14:45:29 +00001117 } else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001118 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroff543409e2008-04-18 21:13:19 +00001119 ResultStr += Name;
1120 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001121 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001122 if (OMD->isVariadic())
1123 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001124 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001125
Steve Naroff76e429d2008-07-16 14:40:40 +00001126 if (FPRetType) {
1127 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001128
Steve Naroff76e429d2008-07-16 14:40:40 +00001129 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001130 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001131 ResultStr += "(";
1132 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1133 if (i) ResultStr += ", ";
1134 std::string ParamStr = FT->getArgType(i).getAsString();
1135 ResultStr += ParamStr;
1136 }
1137 if (FT->isVariadic()) {
1138 if (FT->getNumArgs()) ResultStr += ", ";
1139 ResultStr += "...";
1140 }
1141 ResultStr += ")";
1142 } else {
1143 ResultStr += "()";
1144 }
1145 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001146}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001147void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001148 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1149 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001150
Fariborz Jahaniana1352162010-02-15 21:11:41 +00001151 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001152
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001153 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001154 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1155 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001156 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001157 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001158 ObjCMethodDecl *OMD = *I;
1159 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001160 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001161 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001162
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001163 const char *startBuf = SM->getCharacterData(LocStart);
1164 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001165 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001166 }
Mike Stump1eb44332009-09-09 15:08:12 +00001167
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001168 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001169 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1170 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001171 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001172 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001173 ObjCMethodDecl *OMD = *I;
1174 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001175 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001176 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001177
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001178 const char *startBuf = SM->getCharacterData(LocStart);
1179 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001180 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001181 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001182 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001183 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001184 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001185 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001186 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001187 }
1188
Benjamin Kramerd999b372010-02-14 14:14:16 +00001189 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001190}
1191
Steve Naroffb29b4272008-04-14 22:03:09 +00001192void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001193 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001194 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001195 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001196 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001197 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001198 ResultStr += "\n";
1199 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001200 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001201 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001202 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001203 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001204 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001205 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001206 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001207 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001208 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001209
1210 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001211 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001212 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001213 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001214 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001215 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001216 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001217 for (ObjCInterfaceDecl::classmeth_iterator
1218 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001219 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001220 RewriteMethodDeclaration(*I);
1221
Steve Naroff2feac5e2007-10-30 03:43:13 +00001222 // Lastly, comment out the @end.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001223 ReplaceText(ClassDecl->getAtEndRange().getBegin(), 0, "// ");
Steve Naroffbef11852007-10-26 20:53:56 +00001224}
1225
Steve Naroffb619d952008-12-09 12:56:34 +00001226Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1227 SourceRange SrcRange) {
Steve Naroffc77a6362008-12-04 16:24:46 +00001228 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1229 // This allows us to reuse all the fun and games in SynthMessageExpr().
1230 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1231 ObjCMessageExpr *MsgExpr;
1232 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1233 llvm::SmallVector<Expr *, 1> ExprVec;
1234 ExprVec.push_back(newStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001235
Steve Naroff8599e7a2008-12-08 16:43:47 +00001236 Stmt *Receiver = PropRefExpr->getBase();
1237 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1238 if (PRE && PropGetters[PRE]) {
1239 // This allows us to handle chain/nested property getters.
1240 Receiver = PropGetters[PRE];
1241 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001242 if (isa<ObjCSuperExpr>(Receiver))
1243 MsgExpr = ObjCMessageExpr::Create(*Context,
1244 PDecl->getType().getNonReferenceType(),
1245 /*FIXME?*/SourceLocation(),
1246 Receiver->getLocStart(),
1247 /*IsInstanceSuper=*/true,
1248 cast<Expr>(Receiver)->getType(),
1249 PDecl->getSetterName(),
1250 PDecl->getSetterMethodDecl(),
1251 &ExprVec[0], 1,
1252 /*FIXME:*/SourceLocation());
1253 else
1254 MsgExpr = ObjCMessageExpr::Create(*Context,
1255 PDecl->getType().getNonReferenceType(),
1256 /*FIXME: */SourceLocation(),
1257 cast<Expr>(Receiver),
1258 PDecl->getSetterName(),
1259 PDecl->getSetterMethodDecl(),
1260 &ExprVec[0], 1,
1261 /*FIXME:*/SourceLocation());
Steve Naroffc77a6362008-12-04 16:24:46 +00001262 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001263
Steve Naroffc77a6362008-12-04 16:24:46 +00001264 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001265 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001266 //delete BinOp;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001267 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1268 // to things that stay around.
1269 Context->Deallocate(MsgExpr);
Steve Naroffc77a6362008-12-04 16:24:46 +00001270 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001271}
1272
Steve Naroffc77a6362008-12-04 16:24:46 +00001273Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Naroff15f081d2008-12-03 00:56:33 +00001274 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1275 // This allows us to reuse all the fun and games in SynthMessageExpr().
1276 ObjCMessageExpr *MsgExpr;
1277 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
Mike Stump1eb44332009-09-09 15:08:12 +00001278
Steve Naroff8599e7a2008-12-08 16:43:47 +00001279 Stmt *Receiver = PropRefExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00001280
Steve Naroff8599e7a2008-12-08 16:43:47 +00001281 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1282 if (PRE && PropGetters[PRE]) {
1283 // This allows us to handle chain/nested property getters.
1284 Receiver = PropGetters[PRE];
1285 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001286
1287 if (isa<ObjCSuperExpr>(Receiver))
1288 MsgExpr = ObjCMessageExpr::Create(*Context,
1289 PDecl->getType().getNonReferenceType(),
1290 /*FIXME:*/SourceLocation(),
1291 Receiver->getLocStart(),
1292 /*IsInstanceSuper=*/true,
1293 cast<Expr>(Receiver)->getType(),
1294 PDecl->getGetterName(),
1295 PDecl->getGetterMethodDecl(),
1296 0, 0,
1297 /*FIXME:*/SourceLocation());
1298 else
1299 MsgExpr = ObjCMessageExpr::Create(*Context,
1300 PDecl->getType().getNonReferenceType(),
1301 /*FIXME:*/SourceLocation(),
1302 cast<Expr>(Receiver),
1303 PDecl->getGetterName(),
1304 PDecl->getGetterMethodDecl(),
1305 0, 0,
1306 /*FIXME:*/SourceLocation());
Steve Naroff15f081d2008-12-03 00:56:33 +00001307
Steve Naroff4c3580e2008-12-04 23:50:32 +00001308 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001309
1310 if (!PropParentMap)
1311 PropParentMap = new ParentMap(CurrentBody);
1312
1313 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1314 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1315 // We stash away the ReplacingStmt since actually doing the
1316 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1317 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001318 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1319 // to things that stay around.
1320 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001321 return PropRefExpr; // return the original...
1322 } else {
1323 ReplaceStmt(PropRefExpr, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001324 // delete PropRefExpr; elsewhere...
Ted Kremenek8189cde2009-02-07 01:47:29 +00001325 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1326 // to things that stay around.
1327 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001328 return ReplacingStmt;
1329 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001330}
1331
Mike Stump1eb44332009-09-09 15:08:12 +00001332Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001333 SourceLocation OrigStart,
1334 bool &replaced) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001335 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001336 const Expr *BaseExpr = IV->getBase();
Steve Naroff54055232008-10-27 17:20:55 +00001337 if (CurMethodDef) {
Fariborz Jahanian8f095432010-01-26 18:28:51 +00001338 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001339 ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001340 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianffbdead2010-01-26 20:37:44 +00001341 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Narofff0757612008-05-08 17:52:16 +00001342 // lookup which class implements the instance variable.
1343 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001344 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001345 clsDeclared);
Steve Narofff0757612008-05-08 17:52:16 +00001346 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001347
Steve Narofff0757612008-05-08 17:52:16 +00001348 // Synthesize an explicit cast to gain access to the ivar.
1349 std::string RecName = clsDeclared->getIdentifier()->getName();
1350 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001351 IdentifierInfo *II = &Context->Idents.get(RecName);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001352 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001353 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001354 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1355 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001356 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1357 CastExpr::CK_Unknown,
1358 IV->getBase());
Steve Narofff0757612008-05-08 17:52:16 +00001359 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001360 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1361 IV->getBase()->getLocEnd(),
1362 castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001363 replaced = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001364 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001365 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001366 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1367 IV->getLocation(),
1368 D->getType());
Steve Naroff4c3580e2008-12-04 23:50:32 +00001369 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001370 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001371 }
Fariborz Jahanian7e20ffe2010-01-28 01:41:20 +00001372 // Get the new text
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001373 // Cannot delete IV->getBase(), since PE points to it.
1374 // Replace the old base with the cast. This is important when doing
1375 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001376 IV->setBase(PE);
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001377 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001378 }
Steve Naroff84472a82008-04-18 21:55:08 +00001379 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001380 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump1eb44332009-09-09 15:08:12 +00001381
Steve Naroff9f525972008-05-06 23:20:07 +00001382 // Explicit ivar refs need to have a cast inserted.
1383 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian26337b22010-01-12 17:31:23 +00001384 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Fariborz Jahanianc374cd92010-01-11 17:50:35 +00001385 ObjCInterfaceType *iFaceDecl =
1386 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001387 // lookup which class implements the instance variable.
1388 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001389 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001390 clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001391 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001392
Steve Naroff9f525972008-05-06 23:20:07 +00001393 // Synthesize an explicit cast to gain access to the ivar.
1394 std::string RecName = clsDeclared->getIdentifier()->getName();
1395 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001396 IdentifierInfo *II = &Context->Idents.get(RecName);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001397 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001398 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001399 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1400 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001401 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1402 CastExpr::CK_Unknown,
1403 IV->getBase());
Steve Naroff9f525972008-05-06 23:20:07 +00001404 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001405 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner8d366162008-05-28 16:38:23 +00001406 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001407 replaced = true;
Steve Naroff9f525972008-05-06 23:20:07 +00001408 // Cannot delete IV->getBase(), since PE points to it.
1409 // Replace the old base with the cast. This is important when doing
1410 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001411 IV->setBase(PE);
Steve Naroff9f525972008-05-06 23:20:07 +00001412 return IV;
1413 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001414 }
Steve Naroff84472a82008-04-18 21:55:08 +00001415 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001416}
1417
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001418Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
1419 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1420 CI != E; ++CI) {
1421 if (*CI) {
1422 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1423 if (newStmt)
1424 *CI = newStmt;
1425 }
1426 }
1427 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1428 SourceRange OrigStmtRange = S->getSourceRange();
1429 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1430 replaced);
1431 return newStmt;
Fariborz Jahanian376338a2010-02-05 17:48:10 +00001432 }
1433 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1434 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1435 return newStmt;
1436 }
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001437 return S;
1438}
1439
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001440/// SynthCountByEnumWithState - To print:
1441/// ((unsigned int (*)
1442/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001443/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001444/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001445/// "countByEnumeratingWithState:objects:count:"),
1446/// &enumState,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001447/// (id *)items, (unsigned int)16)
1448///
Steve Naroffb29b4272008-04-14 22:03:09 +00001449void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001450 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1451 "id *, unsigned int))(void *)objc_msgSend)";
1452 buf += "\n\t\t";
1453 buf += "((id)l_collection,\n\t\t";
1454 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1455 buf += "\n\t\t";
1456 buf += "&enumState, "
1457 "(id *)items, (unsigned int)16)";
1458}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001459
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001460/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1461/// statement to exit to its outer synthesized loop.
1462///
Steve Naroffb29b4272008-04-14 22:03:09 +00001463Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001464 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1465 return S;
1466 // replace break with goto __break_label
1467 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001468
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001469 SourceLocation startLoc = S->getLocStart();
1470 buf = "goto __break_label_";
1471 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001472 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001473
1474 return 0;
1475}
1476
1477/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1478/// statement to continue with its inner synthesized loop.
1479///
Steve Naroffb29b4272008-04-14 22:03:09 +00001480Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001481 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1482 return S;
1483 // replace continue with goto __continue_label
1484 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001485
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001486 SourceLocation startLoc = S->getLocStart();
1487 buf = "goto __continue_label_";
1488 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001489 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001490
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001491 return 0;
1492}
1493
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001494/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001495/// It rewrites:
1496/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001497
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001498/// Into:
1499/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001500/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001501/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001502/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001503/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001504/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001505/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001506/// if (limit) {
1507/// unsigned long startMutations = *enumState.mutationsPtr;
1508/// do {
1509/// unsigned long counter = 0;
1510/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001511/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001512/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001513/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001514/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001515/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001516/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001517/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001518/// objects:items count:16]);
1519/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001520/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001521/// }
1522/// else
1523/// elem = nil;
1524/// }
1525///
Steve Naroffb29b4272008-04-14 22:03:09 +00001526Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001527 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001528 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001529 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001530 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001531 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001532 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001533
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001534 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001535 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001536 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001537 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001538 std::string buf;
1539 buf = "\n{\n\t";
1540 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1541 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001542 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001543 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001544 if (ElementType->isObjCQualifiedIdType() ||
1545 ElementType->isObjCQualifiedInterfaceType())
1546 // Simply use 'id' for all qualified types.
1547 elementTypeAsString = "id";
1548 else
1549 elementTypeAsString = ElementType.getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001550 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001551 buf += " ";
Chris Lattner8ec03f52008-11-24 03:54:41 +00001552 elementName = D->getNameAsCString();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001553 buf += elementName;
1554 buf += ";\n\t";
1555 }
Chris Lattner06767512008-04-08 05:52:18 +00001556 else {
1557 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001558 elementName = DR->getDecl()->getNameAsCString();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001559 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1560 if (VD->getType()->isObjCQualifiedIdType() ||
1561 VD->getType()->isObjCQualifiedInterfaceType())
1562 // Simply use 'id' for all qualified types.
1563 elementTypeAsString = "id";
1564 else
1565 elementTypeAsString = VD->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001566 }
Mike Stump1eb44332009-09-09 15:08:12 +00001567
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001568 // struct __objcFastEnumerationState enumState = { 0 };
1569 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1570 // id items[16];
1571 buf += "id items[16];\n\t";
1572 // id l_collection = (id)
1573 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001574 // Find start location of 'collection' the hard way!
1575 const char *startCollectionBuf = startBuf;
1576 startCollectionBuf += 3; // skip 'for'
1577 startCollectionBuf = strchr(startCollectionBuf, '(');
1578 startCollectionBuf++; // skip '('
1579 // find 'in' and skip it.
1580 while (*startCollectionBuf != ' ' ||
1581 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1582 (*(startCollectionBuf+3) != ' ' &&
1583 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1584 startCollectionBuf++;
1585 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001586
1587 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001588 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001589 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001590 SourceLocation rightParenLoc = S->getRParenLoc();
1591 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1592 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001593 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001594
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001595 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1596 // objects:items count:16];
1597 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001598 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001599 // ((unsigned int (*)
1600 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001601 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001602 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001603 // "countByEnumeratingWithState:objects:count:"),
1604 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001605 // (id *)items, (unsigned int)16);
1606 buf += "unsigned long limit =\n\t\t";
1607 SynthCountByEnumWithState(buf);
1608 buf += ";\n\t";
1609 /// if (limit) {
1610 /// unsigned long startMutations = *enumState.mutationsPtr;
1611 /// do {
1612 /// unsigned long counter = 0;
1613 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001614 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001615 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001616 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001617 buf += "if (limit) {\n\t";
1618 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1619 buf += "do {\n\t\t";
1620 buf += "unsigned long counter = 0;\n\t\t";
1621 buf += "do {\n\t\t\t";
1622 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1623 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1624 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001625 buf += " = (";
1626 buf += elementTypeAsString;
1627 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001628 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001629 ReplaceText(lparenLoc, 1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001630
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001631 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001632 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001633 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001634 /// objects:items count:16]);
1635 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001636 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001637 /// }
1638 /// else
1639 /// elem = nil;
1640 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001641 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001642 buf = ";\n\t";
1643 buf += "__continue_label_";
1644 buf += utostr(ObjCBcLabelNo.back());
1645 buf += ": ;";
1646 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001647 buf += "} while (counter < limit);\n\t";
1648 buf += "} while (limit = ";
1649 SynthCountByEnumWithState(buf);
1650 buf += ");\n\t";
1651 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001652 buf += " = ((";
1653 buf += elementTypeAsString;
1654 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001655 buf += "__break_label_";
1656 buf += utostr(ObjCBcLabelNo.back());
1657 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001658 buf += "}\n\t";
1659 buf += "else\n\t\t";
1660 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001661 buf += " = ((";
1662 buf += elementTypeAsString;
1663 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001664 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001665
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001666 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001667 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001668 if (isa<CompoundStmt>(S->getBody())) {
1669 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001670 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001671 } else {
1672 /* Need to treat single statements specially. For example:
1673 *
1674 * for (A *a in b) if (stuff()) break;
1675 * for (A *a in b) xxxyy;
1676 *
1677 * The following code simply scans ahead to the semi to find the actual end.
1678 */
1679 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1680 const char *semiBuf = strchr(stmtBuf, ';');
1681 assert(semiBuf && "Can't find ';'");
1682 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001683 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001684 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001685 Stmts.pop_back();
1686 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001687 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001688}
1689
Mike Stump1eb44332009-09-09 15:08:12 +00001690/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001691/// This routine rewrites @synchronized(expr) stmt;
1692/// into:
1693/// objc_sync_enter(expr);
1694/// @try stmt @finally { objc_sync_exit(expr); }
1695///
Steve Naroffb29b4272008-04-14 22:03:09 +00001696Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001697 // Get the start location and compute the semi location.
1698 SourceLocation startLoc = S->getLocStart();
1699 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001700
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001701 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001702
1703 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001704 buf = "objc_sync_enter((id)";
1705 const char *lparenBuf = startBuf;
1706 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramerd999b372010-02-14 14:14:16 +00001707 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001708 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1709 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001710 // been rewritten! (which implies the SourceLocation's are invalid).
1711 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001712 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001713 while (*endBuf != ')') endBuf--;
1714 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001715 buf = ");\n";
1716 // declare a new scope with two variables, _stack and _rethrow.
1717 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1718 buf += "int buf[18/*32-bit i386*/];\n";
1719 buf += "char *pointers[4];} _stack;\n";
1720 buf += "id volatile _rethrow = 0;\n";
1721 buf += "objc_exception_try_enter(&_stack);\n";
1722 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001723 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001724 startLoc = S->getSynchBody()->getLocEnd();
1725 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001726
Steve Naroffc7089f12008-08-19 13:04:19 +00001727 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001728 SourceLocation lastCurlyLoc = startLoc;
1729 buf = "}\nelse {\n";
1730 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001731 buf += "}\n";
1732 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001733 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001734
1735 std::string syncBuf;
1736 syncBuf += " objc_sync_exit(";
John McCall9d125032010-01-15 18:39:57 +00001737 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1738 CastExpr::CK_Unknown,
1739 S->getSynchExpr());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001740 std::string syncExprBufS;
1741 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001742 syncExpr->printPretty(syncExprBuf, *Context, 0,
1743 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001744 syncBuf += syncExprBuf.str();
1745 syncBuf += ");";
1746
1747 buf += syncBuf;
1748 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001749 buf += "}\n";
1750 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001751
Benjamin Kramerd999b372010-02-14 14:14:16 +00001752 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001753
1754 bool hasReturns = false;
1755 HasReturnStmts(S->getSynchBody(), hasReturns);
1756 if (hasReturns)
1757 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1758
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001759 return 0;
1760}
1761
Steve Naroffb85e77a2009-12-05 21:43:12 +00001762void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1763{
Steve Naroff8c565152008-12-05 17:03:39 +00001764 // Perform a bottom up traversal of all children.
1765 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1766 CI != E; ++CI)
1767 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001768 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001769
Steve Naroffb85e77a2009-12-05 21:43:12 +00001770 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001771 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001772 TryFinallyContainsReturnDiag);
1773 }
1774 return;
1775}
1776
Steve Naroffb85e77a2009-12-05 21:43:12 +00001777void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1778{
1779 // Perform a bottom up traversal of all children.
1780 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1781 CI != E; ++CI)
1782 if (*CI)
1783 HasReturnStmts(*CI, hasReturns);
1784
1785 if (isa<ReturnStmt>(S))
1786 hasReturns = true;
1787 return;
1788}
1789
1790void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1791 // Perform a bottom up traversal of all children.
1792 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1793 CI != E; ++CI)
1794 if (*CI) {
1795 RewriteTryReturnStmts(*CI);
1796 }
1797 if (isa<ReturnStmt>(S)) {
1798 SourceLocation startLoc = S->getLocStart();
1799 const char *startBuf = SM->getCharacterData(startLoc);
1800
1801 const char *semiBuf = strchr(startBuf, ';');
1802 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1803 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1804
1805 std::string buf;
1806 buf = "{ objc_exception_try_exit(&_stack); return";
1807
Benjamin Kramerd999b372010-02-14 14:14:16 +00001808 ReplaceText(startLoc, 6, buf);
1809 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001810 }
1811 return;
1812}
1813
1814void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1815 // Perform a bottom up traversal of all children.
1816 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1817 CI != E; ++CI)
1818 if (*CI) {
1819 RewriteSyncReturnStmts(*CI, syncExitBuf);
1820 }
1821 if (isa<ReturnStmt>(S)) {
1822 SourceLocation startLoc = S->getLocStart();
1823 const char *startBuf = SM->getCharacterData(startLoc);
1824
1825 const char *semiBuf = strchr(startBuf, ';');
1826 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1827 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1828
1829 std::string buf;
1830 buf = "{ objc_exception_try_exit(&_stack);";
1831 buf += syncExitBuf;
1832 buf += " return";
1833
Benjamin Kramerd999b372010-02-14 14:14:16 +00001834 ReplaceText(startLoc, 6, buf);
1835 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001836 }
1837 return;
1838}
1839
Steve Naroffb29b4272008-04-14 22:03:09 +00001840Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001841 // Get the start location and compute the semi location.
1842 SourceLocation startLoc = S->getLocStart();
1843 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001844
Steve Naroff75730982007-11-07 04:08:17 +00001845 assert((*startBuf == '@') && "bogus @try location");
1846
1847 std::string buf;
1848 // declare a new scope with two variables, _stack and _rethrow.
1849 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1850 buf += "int buf[18/*32-bit i386*/];\n";
1851 buf += "char *pointers[4];} _stack;\n";
1852 buf += "id volatile _rethrow = 0;\n";
1853 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001854 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001855
Benjamin Kramerd999b372010-02-14 14:14:16 +00001856 ReplaceText(startLoc, 4, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001857
Steve Naroff75730982007-11-07 04:08:17 +00001858 startLoc = S->getTryBody()->getLocEnd();
1859 startBuf = SM->getCharacterData(startLoc);
1860
1861 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001862
Steve Naroff75730982007-11-07 04:08:17 +00001863 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001864 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1865 if (catchList) {
1866 startLoc = startLoc.getFileLocWithOffset(1);
1867 buf = " /* @catch begin */ else {\n";
1868 buf += " id _caught = objc_exception_extract(&_stack);\n";
1869 buf += " objc_exception_try_enter (&_stack);\n";
1870 buf += " if (_setjmp(_stack.buf))\n";
1871 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1872 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001873
Benjamin Kramerd999b372010-02-14 14:14:16 +00001874 InsertText(startLoc, buf);
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001875 } else { /* no catch list */
1876 buf = "}\nelse {\n";
1877 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1878 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001879 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001880 }
Steve Naroff75730982007-11-07 04:08:17 +00001881 bool sawIdTypedCatch = false;
1882 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001883 while (catchList) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00001884 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001885
Mike Stump1eb44332009-09-09 15:08:12 +00001886 if (catchList == S->getCatchStmts())
Steve Naroff75730982007-11-07 04:08:17 +00001887 buf = "if ("; // we are generating code for the first catch clause
1888 else
1889 buf = "else if (";
1890 startLoc = catchList->getLocStart();
1891 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001892
Steve Naroff75730982007-11-07 04:08:17 +00001893 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001894
Steve Naroff75730982007-11-07 04:08:17 +00001895 const char *lParenLoc = strchr(startBuf, '(');
1896
Steve Naroffbe4b3332008-02-01 22:08:12 +00001897 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001898 // Now rewrite the body...
1899 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001900 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1901 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001902 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1903 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001904 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001905
Steve Naroffe12e6922008-02-01 20:02:07 +00001906 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00001907 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00001908 } else if (catchDecl) {
1909 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001910 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001911 buf += "1) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001912 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001913 sawIdTypedCatch = true;
Fariborz Jahanian66867c52010-01-12 01:22:23 +00001914 } else if (t->isObjCObjectPointerType()) {
1915 QualType InterfaceTy = t->getPointeeType();
1916 const ObjCInterfaceType *cls = // Should be a pointer to a class.
1917 InterfaceTy->getAs<ObjCInterfaceType>();
Steve Naroff75730982007-11-07 04:08:17 +00001918 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001919 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001920 buf += cls->getDecl()->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001921 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001922 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001923 }
1924 }
1925 // Now rewrite the body...
1926 lastCatchBody = catchList->getCatchBody();
1927 SourceLocation rParenLoc = catchList->getRParenLoc();
1928 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1929 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1930 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1931 assert((*rParenBuf == ')') && "bogus @catch paren location");
1932 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001933
Mike Stump1eb44332009-09-09 15:08:12 +00001934 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00001935 // declares the @catch parameter).
Benjamin Kramerd999b372010-02-14 14:14:16 +00001936 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff7ba138a2009-03-03 19:52:17 +00001937 } else {
Steve Naroff75730982007-11-07 04:08:17 +00001938 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001939 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001940 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001941 catchList = catchList->getNextCatchStmt();
1942 }
1943 // Complete the catch list...
1944 if (lastCatchBody) {
1945 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001946 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1947 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001948
Steve Naroff378f47a2008-09-11 15:29:03 +00001949 // Insert the last (implicit) else clause *before* the right curly brace.
1950 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1951 buf = "} /* last catch end */\n";
1952 buf += "else {\n";
1953 buf += " _rethrow = _caught;\n";
1954 buf += " objc_exception_try_exit(&_stack);\n";
1955 buf += "} } /* @catch end */\n";
1956 if (!S->getFinallyStmt())
1957 buf += "}\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001958 InsertText(bodyLoc, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001959
Steve Naroff75730982007-11-07 04:08:17 +00001960 // Set lastCurlyLoc
1961 lastCurlyLoc = lastCatchBody->getLocEnd();
1962 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001963 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001964 startLoc = finalStmt->getLocStart();
1965 startBuf = SM->getCharacterData(startLoc);
1966 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00001967
Benjamin Kramerd999b372010-02-14 14:14:16 +00001968 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump1eb44332009-09-09 15:08:12 +00001969
Steve Naroff75730982007-11-07 04:08:17 +00001970 Stmt *body = finalStmt->getFinallyBody();
1971 SourceLocation startLoc = body->getLocStart();
1972 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001973 assert(*SM->getCharacterData(startLoc) == '{' &&
1974 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001975 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00001976 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001977
Steve Naroff75730982007-11-07 04:08:17 +00001978 startLoc = startLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001979 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Steve Naroff75730982007-11-07 04:08:17 +00001980 endLoc = endLoc.getFileLocWithOffset(-1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001981 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump1eb44332009-09-09 15:08:12 +00001982
Steve Naroff75730982007-11-07 04:08:17 +00001983 // Set lastCurlyLoc
1984 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00001985
Steve Naroff8c565152008-12-05 17:03:39 +00001986 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00001987 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001988 } else { /* no finally clause - make sure we synthesize an implicit one */
1989 buf = "{ /* implicit finally clause */\n";
1990 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1991 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1992 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001993 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001994
1995 // Now check for any return/continue/go statements within the @try.
1996 // The implicit finally clause won't called if the @try contains any
1997 // jump statements.
1998 bool hasReturns = false;
1999 HasReturnStmts(S->getTryBody(), hasReturns);
2000 if (hasReturns)
2001 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00002002 }
2003 // Now emit the final closing curly brace...
2004 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002005 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002006 return 0;
2007}
2008
Steve Naroffb29b4272008-04-14 22:03:09 +00002009Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002010 return 0;
2011}
2012
Steve Naroffb29b4272008-04-14 22:03:09 +00002013Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002014 return 0;
2015}
2016
Mike Stump1eb44332009-09-09 15:08:12 +00002017// This can't be done with ReplaceStmt(S, ThrowExpr), since
2018// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00002019// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00002020Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00002021 // Get the start location and compute the semi location.
2022 SourceLocation startLoc = S->getLocStart();
2023 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00002024
Steve Naroff2bd03922007-11-07 15:32:26 +00002025 assert((*startBuf == '@') && "bogus @throw location");
2026
2027 std::string buf;
2028 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00002029 if (S->getThrowExpr())
2030 buf = "objc_exception_throw(";
2031 else // add an implicit argument
2032 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00002033
Steve Naroff4ba0acb2008-07-25 15:41:30 +00002034 // handle "@ throw" correctly.
2035 const char *wBuf = strchr(startBuf, 'w');
2036 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramerd999b372010-02-14 14:14:16 +00002037 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002038
Steve Naroff2bd03922007-11-07 15:32:26 +00002039 const char *semiBuf = strchr(startBuf, ';');
2040 assert((*semiBuf == ';') && "@throw: can't find ';'");
2041 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002042 ReplaceText(semiLoc, 1, ");");
Steve Naroff2bd03922007-11-07 15:32:26 +00002043 return 0;
2044}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002045
Steve Naroffb29b4272008-04-14 22:03:09 +00002046Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00002047 // Create a new string expression.
2048 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002049 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002050 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattner2085fd62009-02-18 06:40:38 +00002051 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
2052 StrEncoding.length(), false,StrType,
2053 SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002054 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00002055
Chris Lattner07506182007-11-30 22:53:43 +00002056 // Replace this subexpr in the parent.
Steve Naroff4c3580e2008-12-04 23:50:32 +00002057 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00002058 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00002059}
2060
Steve Naroffb29b4272008-04-14 22:03:09 +00002061Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00002062 if (!SelGetUidFunctionDecl)
2063 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00002064 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2065 // Create a call to sel_registerName("selName").
2066 llvm::SmallVector<Expr*, 8> SelExprs;
2067 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002068 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002069 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002070 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002071 false, argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00002072 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2073 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002074 ReplaceStmt(Exp, SelExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002075 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00002076 return SelExp;
2077}
2078
Steve Naroffb29b4272008-04-14 22:03:09 +00002079CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002080 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2081 SourceLocation EndLoc) {
Steve Naroffebf2b562007-10-23 23:50:29 +00002082 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00002083 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002084
Steve Naroffebf2b562007-10-23 23:50:29 +00002085 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002086 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002087
Steve Naroffebf2b562007-10-23 23:50:29 +00002088 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00002089 QualType pToFunc = Context->getPointerType(msgSendType);
Mike Stump1eb44332009-09-09 15:08:12 +00002090 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc,
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002091 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002092 DRE,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002093 /*isLvalue=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002094
John McCall183700f2009-09-21 23:43:11 +00002095 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002096
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002097 CallExpr *Exp =
2098 new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
2099 EndLoc);
2100 return Exp;
Steve Naroff934f2762007-10-24 22:48:43 +00002101}
2102
Steve Naroffd5255f52007-11-01 13:24:47 +00002103static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2104 const char *&startRef, const char *&endRef) {
2105 while (startBuf < endBuf) {
2106 if (*startBuf == '<')
2107 startRef = startBuf; // mark the start.
2108 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00002109 if (startRef && *startRef == '<') {
2110 endRef = startBuf; // mark the end.
2111 return true;
2112 }
2113 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002114 }
2115 startBuf++;
2116 }
2117 return false;
2118}
2119
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002120static void scanToNextArgument(const char *&argRef) {
2121 int angle = 0;
2122 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2123 if (*argRef == '<')
2124 angle++;
2125 else if (*argRef == '>')
2126 angle--;
2127 argRef++;
2128 }
2129 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2130}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002131
Steve Naroffb29b4272008-04-14 22:03:09 +00002132bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002133 if (T->isObjCQualifiedIdType())
2134 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002135 if (const PointerType *PT = T->getAs<PointerType>()) {
2136 if (PT->getPointeeType()->isObjCQualifiedIdType())
2137 return true;
2138 }
2139 if (T->isObjCObjectPointerType()) {
2140 T = T->getPointeeType();
2141 return T->isObjCQualifiedInterfaceType();
2142 }
2143 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002144}
2145
Steve Naroff4f95b752008-07-29 18:15:38 +00002146void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2147 QualType Type = E->getType();
2148 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002149 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002150
Steve Naroffcda658e2008-11-19 21:15:47 +00002151 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2152 Loc = ECE->getLParenLoc();
2153 EndLoc = ECE->getRParenLoc();
2154 } else {
2155 Loc = E->getLocStart();
2156 EndLoc = E->getLocEnd();
2157 }
2158 // This will defend against trying to rewrite synthesized expressions.
2159 if (Loc.isInvalid() || EndLoc.isInvalid())
2160 return;
2161
Steve Naroff4f95b752008-07-29 18:15:38 +00002162 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002163 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002164 const char *startRef = 0, *endRef = 0;
2165 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2166 // Get the locations of the startRef, endRef.
2167 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2168 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2169 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002170 InsertText(LessLoc, "/*");
2171 InsertText(GreaterLoc, "*/");
Steve Naroff4f95b752008-07-29 18:15:38 +00002172 }
2173 }
2174}
2175
Steve Naroffb29b4272008-04-14 22:03:09 +00002176void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002177 SourceLocation Loc;
2178 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002179 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002180 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2181 Loc = VD->getLocation();
2182 Type = VD->getType();
2183 }
2184 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2185 Loc = FD->getLocation();
2186 // Check for ObjC 'id' and class types that have been adorned with protocol
2187 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002188 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002189 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002190 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002191 if (!proto)
2192 return;
2193 Type = proto->getResultType();
2194 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002195 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2196 Loc = FD->getLocation();
2197 Type = FD->getType();
2198 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002199 else
2200 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002201
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002202 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002203 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002204
Steve Naroffd5255f52007-11-01 13:24:47 +00002205 const char *endBuf = SM->getCharacterData(Loc);
2206 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002207 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002208 startBuf--; // scan backward (from the decl location) for return type.
2209 const char *startRef = 0, *endRef = 0;
2210 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2211 // Get the locations of the startRef, endRef.
2212 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2213 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2214 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002215 InsertText(LessLoc, "/*");
2216 InsertText(GreaterLoc, "*/");
Steve Naroff9165ad32007-10-31 04:38:33 +00002217 }
2218 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002219 if (!proto)
2220 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002221 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002222 const char *startBuf = SM->getCharacterData(Loc);
2223 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002224 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2225 if (needToScanForQualifiers(proto->getArgType(i))) {
2226 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002227
Steve Naroffd5255f52007-11-01 13:24:47 +00002228 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002229 // scan forward (from the decl location) for argument types.
2230 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002231 const char *startRef = 0, *endRef = 0;
2232 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2233 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002234 SourceLocation LessLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002235 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002236 SourceLocation GreaterLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002237 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002238 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002239 InsertText(LessLoc, "/*");
2240 InsertText(GreaterLoc, "*/");
Steve Naroffd5255f52007-11-01 13:24:47 +00002241 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002242 startBuf = ++endBuf;
2243 }
2244 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002245 // If the function name is derived from a macro expansion, then the
2246 // argument buffer will not follow the name. Need to speak with Chris.
2247 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002248 startBuf++; // scan forward (from the decl location) for argument types.
2249 startBuf++;
2250 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002251 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002252}
2253
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002254void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2255 QualType QT = ND->getType();
2256 const Type* TypePtr = QT->getAs<Type>();
2257 if (!isa<TypeOfExprType>(TypePtr))
2258 return;
2259 while (isa<TypeOfExprType>(TypePtr)) {
2260 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2261 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2262 TypePtr = QT->getAs<Type>();
2263 }
2264 // FIXME. This will not work for multiple declarators; as in:
2265 // __typeof__(a) b,c,d;
2266 std::string TypeAsString(QT.getAsString());
2267 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2268 const char *startBuf = SM->getCharacterData(DeclLoc);
2269 if (ND->getInit()) {
2270 std::string Name(ND->getNameAsString());
2271 TypeAsString += " " + Name + " = ";
2272 Expr *E = ND->getInit();
2273 SourceLocation startLoc;
2274 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2275 startLoc = ECE->getLParenLoc();
2276 else
2277 startLoc = E->getLocStart();
2278 startLoc = SM->getInstantiationLoc(startLoc);
2279 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002280 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002281 }
2282 else {
2283 SourceLocation X = ND->getLocEnd();
2284 X = SM->getInstantiationLoc(X);
2285 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002286 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002287 }
2288}
2289
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002290// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002291void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002292 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2293 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002294 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002295 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002296 &ArgTys[0], ArgTys.size(),
2297 false /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002298 false, false, 0, 0,
2299 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002300 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002301 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002302 SelGetUidIdent, getFuncType, 0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002303 FunctionDecl::Extern,
2304 FunctionDecl::None, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002305}
2306
Steve Naroffb29b4272008-04-14 22:03:09 +00002307void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002308 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002309 if (FD->getIdentifier() &&
2310 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002311 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002312 return;
2313 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002314 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002315}
2316
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002317static void RewriteBlockPointerType(std::string& Str, QualType Type) {
2318 std::string TypeString(Type.getAsString());
2319 const char *argPtr = TypeString.c_str();
2320 if (!strchr(argPtr, '^')) {
2321 Str += TypeString;
2322 return;
2323 }
2324 while (*argPtr) {
2325 Str += (*argPtr == '^' ? '*' : *argPtr);
2326 argPtr++;
2327 }
2328}
2329
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002330// FIXME. Consolidate this routine with RewriteBlockPointerType.
2331static void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD) {
2332 QualType Type = VD->getType();
2333 std::string TypeString(Type.getAsString());
2334 const char *argPtr = TypeString.c_str();
2335 int paren = 0;
2336 while (*argPtr) {
2337 switch (*argPtr) {
2338 case '(':
2339 Str += *argPtr;
2340 paren++;
2341 break;
2342 case ')':
2343 Str += *argPtr;
2344 paren--;
2345 break;
2346 case '^':
2347 Str += '*';
2348 if (paren == 1)
2349 Str += VD->getNameAsString();
2350 break;
2351 default:
2352 Str += *argPtr;
2353 break;
2354 }
2355 argPtr++;
2356 }
2357}
2358
2359
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002360void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2361 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2362 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2363 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2364 if (!proto)
2365 return;
2366 QualType Type = proto->getResultType();
2367 std::string FdStr = Type.getAsString();
2368 FdStr += " ";
2369 FdStr += FD->getNameAsCString();
2370 FdStr += "(";
2371 unsigned numArgs = proto->getNumArgs();
2372 for (unsigned i = 0; i < numArgs; i++) {
2373 QualType ArgType = proto->getArgType(i);
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002374 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002375 if (i+1 < numArgs)
2376 FdStr += ", ";
2377 }
2378 FdStr += ");\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002379 InsertText(FunLocStart, FdStr);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002380 CurFunctionDeclToDeclareForBlock = 0;
2381}
2382
Steve Naroffc0a123c2008-03-11 17:37:02 +00002383// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002384void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002385 if (SuperContructorFunctionDecl)
2386 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002387 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroffc0a123c2008-03-11 17:37:02 +00002388 llvm::SmallVector<QualType, 16> ArgTys;
2389 QualType argT = Context->getObjCIdType();
2390 assert(!argT.isNull() && "Can't find 'id' type");
2391 ArgTys.push_back(argT);
2392 ArgTys.push_back(argT);
2393 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2394 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002395 false, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002396 false, false, 0, 0,
2397 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002398 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002399 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002400 msgSendIdent, msgSendType, 0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002401 FunctionDecl::Extern,
2402 FunctionDecl::None, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002403}
2404
Steve Naroff09b266e2007-10-30 23:14:51 +00002405// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002406void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002407 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2408 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002409 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002410 assert(!argT.isNull() && "Can't find 'id' type");
2411 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002412 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002413 assert(!argT.isNull() && "Can't find 'SEL' type");
2414 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002415 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002416 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002417 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002418 false, false, 0, 0,
2419 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002420 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002421 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002422 msgSendIdent, msgSendType, 0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002423 FunctionDecl::Extern,
2424 FunctionDecl::None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002425}
2426
Steve Naroff874e2322007-11-15 10:28:18 +00002427// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002428void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002429 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2430 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002431 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002432 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002433 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002434 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2435 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2436 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002437 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002438 assert(!argT.isNull() && "Can't find 'SEL' type");
2439 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002440 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00002441 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002442 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002443 false, false, 0, 0,
2444 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002445 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002446 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002447 msgSendIdent, msgSendType, 0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002448 FunctionDecl::Extern,
2449 FunctionDecl::None, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002450}
2451
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002452// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002453void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002454 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2455 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002456 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002457 assert(!argT.isNull() && "Can't find 'id' type");
2458 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002459 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002460 assert(!argT.isNull() && "Can't find 'SEL' type");
2461 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002462 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002463 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002464 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002465 false, false, 0, 0,
2466 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002467 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002468 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002469 msgSendIdent, msgSendType, 0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002470 FunctionDecl::Extern,
2471 FunctionDecl::None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002472}
2473
Mike Stump1eb44332009-09-09 15:08:12 +00002474// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002475// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002476void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002477 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002478 &Context->Idents.get("objc_msgSendSuper_stret");
2479 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002480 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002481 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002482 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002483 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2484 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2485 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002486 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002487 assert(!argT.isNull() && "Can't find 'SEL' type");
2488 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002489 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002490 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002491 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002492 false, false, 0, 0,
2493 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002494 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002495 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002496 msgSendIdent, msgSendType, 0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002497 FunctionDecl::Extern,
2498 FunctionDecl::None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002499}
2500
Steve Naroff1284db82008-05-08 22:02:18 +00002501// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002502void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002503 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2504 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002505 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002506 assert(!argT.isNull() && "Can't find 'id' type");
2507 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002508 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002509 assert(!argT.isNull() && "Can't find 'SEL' type");
2510 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00002511 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002512 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002513 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002514 false, false, 0, 0,
2515 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002516 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002517 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002518 msgSendIdent, msgSendType, 0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002519 FunctionDecl::Extern,
2520 FunctionDecl::None, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002521}
2522
Steve Naroff09b266e2007-10-30 23:14:51 +00002523// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002524void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002525 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2526 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002527 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002528 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002529 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002530 false /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002531 false, false, 0, 0,
2532 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002533 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002534 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002535 getClassIdent, getClassType, 0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002536 FunctionDecl::Extern,
2537 FunctionDecl::None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002538}
2539
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002540// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2541void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2542 IdentifierInfo *getSuperClassIdent =
2543 &Context->Idents.get("class_getSuperclass");
2544 llvm::SmallVector<QualType, 16> ArgTys;
2545 ArgTys.push_back(Context->getObjCClassType());
2546 QualType getClassType = Context->getFunctionType(Context->getObjCClassType(),
2547 &ArgTys[0], ArgTys.size(),
2548 false /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002549 false, false, 0, 0,
2550 FunctionType::ExtInfo());
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002551 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002552 SourceLocation(),
2553 getSuperClassIdent,
2554 getClassType, 0,
2555 FunctionDecl::Extern,
2556 FunctionDecl::None,
2557 false);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002558}
2559
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002560// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002561void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002562 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2563 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002564 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002565 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002566 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002567 false /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002568 false, false, 0, 0,
2569 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002570 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002571 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002572 getClassIdent, getClassType, 0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002573 FunctionDecl::Extern,
2574 FunctionDecl::None, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002575}
2576
Steve Naroffb29b4272008-04-14 22:03:09 +00002577Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002578 QualType strType = getConstantStringStructType();
2579
2580 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002581
2582 std::string tmpName = InFileName;
2583 unsigned i;
2584 for (i=0; i < tmpName.length(); i++) {
2585 char c = tmpName.at(i);
2586 // replace any non alphanumeric characters with '_'.
2587 if (!isalpha(c) && (c < '0' || c > '9'))
2588 tmpName[i] = '_';
2589 }
2590 S += tmpName;
2591 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002592 S += utostr(NumObjCStringLiterals++);
2593
Steve Naroffba92b2e2008-03-27 22:29:16 +00002594 Preamble += "static __NSConstantStringImpl " + S;
2595 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2596 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002597 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002598 std::string prettyBufS;
2599 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002600 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2601 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002602 Preamble += prettyBuf.str();
2603 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002604 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002605
2606 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Benjamin Kramerd999b372010-02-14 14:14:16 +00002607 &Context->Idents.get(S), strType, 0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002608 VarDecl::Static, VarDecl::None);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002609 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2610 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002611 Context->getPointerType(DRE->getType()),
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002612 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002613 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002614 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2615 CastExpr::CK_Unknown, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002616 ReplaceStmt(Exp, cast);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002617 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002618 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002619}
2620
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002621bool RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002622 // check if we are sending a message to 'super'
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002623 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return false;
2624 return isa<ObjCSuperExpr>(recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +00002625}
2626
2627// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002628QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002629 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002630 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002631 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002632 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002633 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002634
Steve Naroff874e2322007-11-15 10:28:18 +00002635 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002636 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002637 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002638 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002639
Steve Naroff874e2322007-11-15 10:28:18 +00002640 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002641 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002642 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2643 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002644 FieldTypes[i], 0,
2645 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002646 /*Mutable=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002647 }
Mike Stump1eb44332009-09-09 15:08:12 +00002648
Douglas Gregor838db382010-02-11 01:19:42 +00002649 SuperStructDecl->completeDefinition();
Steve Naroff874e2322007-11-15 10:28:18 +00002650 }
2651 return Context->getTagDeclType(SuperStructDecl);
2652}
2653
Steve Naroffb29b4272008-04-14 22:03:09 +00002654QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002655 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002656 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002657 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002658 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002659 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002660
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002661 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002662 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002663 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002664 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002665 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002666 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002667 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002668 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002669
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002670 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002671 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002672 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2673 ConstantStringDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002674 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002675 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002676 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002677 /*Mutable=*/true));
Douglas Gregor44b43212008-12-11 16:49:14 +00002678 }
2679
Douglas Gregor838db382010-02-11 01:19:42 +00002680 ConstantStringDecl->completeDefinition();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002681 }
2682 return Context->getTagDeclType(ConstantStringDecl);
2683}
2684
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002685Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2686 SourceLocation StartLoc,
2687 SourceLocation EndLoc) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002688 if (!SelGetUidFunctionDecl)
2689 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002690 if (!MsgSendFunctionDecl)
2691 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002692 if (!MsgSendSuperFunctionDecl)
2693 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002694 if (!MsgSendStretFunctionDecl)
2695 SynthMsgSendStretFunctionDecl();
2696 if (!MsgSendSuperStretFunctionDecl)
2697 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002698 if (!MsgSendFpretFunctionDecl)
2699 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002700 if (!GetClassFunctionDecl)
2701 SynthGetClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002702 if (!GetSuperClassFunctionDecl)
2703 SynthGetSuperClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002704 if (!GetMetaClassFunctionDecl)
2705 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002706
Steve Naroff874e2322007-11-15 10:28:18 +00002707 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002708 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2709 // May need to use objc_msgSend_stret() as well.
2710 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002711 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2712 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002713 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002714 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002715 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002716 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002717 }
Mike Stump1eb44332009-09-09 15:08:12 +00002718
Steve Naroff934f2762007-10-24 22:48:43 +00002719 // Synthesize a call to objc_msgSend().
2720 llvm::SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002721 switch (Exp->getReceiverKind()) {
2722 case ObjCMessageExpr::SuperClass: {
2723 MsgSendFlavor = MsgSendSuperFunctionDecl;
2724 if (MsgSendStretFlavor)
2725 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2726 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002727
Douglas Gregor04badcf2010-04-21 00:45:42 +00002728 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00002729
Douglas Gregor04badcf2010-04-21 00:45:42 +00002730 llvm::SmallVector<Expr*, 4> InitExprs;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002731
Douglas Gregor04badcf2010-04-21 00:45:42 +00002732 // set the receiver to self, the first argument to all methods.
2733 InitExprs.push_back(
2734 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2735 CastExpr::CK_Unknown,
2736 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2737 Context->getObjCIdType(),
2738 SourceLocation()))
2739 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002740
Douglas Gregor04badcf2010-04-21 00:45:42 +00002741 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2742 llvm::SmallVector<Expr*, 8> ClsExprs;
2743 QualType argType = Context->getPointerType(Context->CharTy);
2744 ClsExprs.push_back(StringLiteral::Create(*Context,
2745 ClassDecl->getIdentifier()->getNameStart(),
2746 ClassDecl->getIdentifier()->getLength(),
2747 false, argType, SourceLocation()));
2748 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2749 &ClsExprs[0],
2750 ClsExprs.size(),
2751 StartLoc,
2752 EndLoc);
2753 // (Class)objc_getClass("CurrentClass")
2754 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2755 Context->getObjCClassType(),
2756 CastExpr::CK_Unknown, Cls);
2757 ClsExprs.clear();
2758 ClsExprs.push_back(ArgExpr);
2759 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2760 &ClsExprs[0], ClsExprs.size(),
2761 StartLoc, EndLoc);
2762
2763 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2764 // To turn off a warning, type-cast to 'id'
2765 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2766 NoTypeInfoCStyleCastExpr(Context,
2767 Context->getObjCIdType(),
2768 CastExpr::CK_Unknown, Cls));
2769 // struct objc_super
2770 QualType superType = getSuperStructType();
2771 Expr *SuperRep;
Steve Naroff621edce2009-04-29 16:37:50 +00002772
Douglas Gregor04badcf2010-04-21 00:45:42 +00002773 if (LangOpts.Microsoft) {
2774 SynthSuperContructorFunctionDecl();
2775 // Simulate a contructor call...
2776 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
2777 superType, SourceLocation());
2778 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2779 InitExprs.size(),
2780 superType, SourceLocation());
2781 // The code for super is a little tricky to prevent collision with
2782 // the structure definition in the header. The rewriter has it's own
2783 // internal definition (__rw_objc_super) that is uses. This is why
2784 // we need the cast below. For example:
2785 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2786 //
2787 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2788 Context->getPointerType(SuperRep->getType()),
2789 SourceLocation());
2790 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2791 Context->getPointerType(superType),
2792 CastExpr::CK_Unknown, SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002793 } else {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002794 // (struct objc_super) { <exprs from above> }
2795 InitListExpr *ILE =
2796 new (Context) InitListExpr(*Context, SourceLocation(),
2797 &InitExprs[0], InitExprs.size(),
2798 SourceLocation());
2799 TypeSourceInfo *superTInfo
2800 = Context->getTrivialTypeSourceInfo(superType);
2801 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2802 superType, ILE, false);
2803 // struct objc_super *
2804 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2805 Context->getPointerType(SuperRep->getType()),
2806 SourceLocation());
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002807 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002808 MsgExprs.push_back(SuperRep);
2809 break;
Steve Naroff6568d4d2007-11-14 23:54:14 +00002810 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002811
2812 case ObjCMessageExpr::Class: {
2813 llvm::SmallVector<Expr*, 8> ClsExprs;
2814 QualType argType = Context->getPointerType(Context->CharTy);
2815 ObjCInterfaceDecl *Class
2816 = Exp->getClassReceiver()->getAs<ObjCInterfaceType>()->getDecl();
2817 IdentifierInfo *clsName = Class->getIdentifier();
2818 ClsExprs.push_back(StringLiteral::Create(*Context,
2819 clsName->getNameStart(),
2820 clsName->getLength(),
2821 false, argType,
2822 SourceLocation()));
2823 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2824 &ClsExprs[0],
2825 ClsExprs.size(),
2826 StartLoc, EndLoc);
2827 MsgExprs.push_back(Cls);
2828 break;
2829 }
2830
2831 case ObjCMessageExpr::SuperInstance:{
2832 MsgSendFlavor = MsgSendSuperFunctionDecl;
2833 if (MsgSendStretFlavor)
2834 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2835 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2836 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2837 llvm::SmallVector<Expr*, 4> InitExprs;
2838
2839 InitExprs.push_back(
2840 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2841 CastExpr::CK_Unknown,
2842 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2843 Context->getObjCIdType(),
2844 SourceLocation()))
2845 ); // set the 'receiver'.
2846
2847 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2848 llvm::SmallVector<Expr*, 8> ClsExprs;
2849 QualType argType = Context->getPointerType(Context->CharTy);
2850 ClsExprs.push_back(StringLiteral::Create(*Context,
2851 ClassDecl->getIdentifier()->getNameStart(),
2852 ClassDecl->getIdentifier()->getLength(),
2853 false, argType, SourceLocation()));
2854 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2855 &ClsExprs[0],
2856 ClsExprs.size(),
2857 StartLoc, EndLoc);
2858 // (Class)objc_getClass("CurrentClass")
2859 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2860 Context->getObjCClassType(),
2861 CastExpr::CK_Unknown, Cls);
2862 ClsExprs.clear();
2863 ClsExprs.push_back(ArgExpr);
2864 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2865 &ClsExprs[0], ClsExprs.size(),
2866 StartLoc, EndLoc);
2867
2868 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2869 // To turn off a warning, type-cast to 'id'
2870 InitExprs.push_back(
2871 // set 'super class', using class_getSuperclass().
2872 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2873 CastExpr::CK_Unknown, Cls));
2874 // struct objc_super
2875 QualType superType = getSuperStructType();
2876 Expr *SuperRep;
2877
2878 if (LangOpts.Microsoft) {
2879 SynthSuperContructorFunctionDecl();
2880 // Simulate a contructor call...
2881 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
2882 superType, SourceLocation());
2883 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2884 InitExprs.size(),
2885 superType, SourceLocation());
2886 // The code for super is a little tricky to prevent collision with
2887 // the structure definition in the header. The rewriter has it's own
2888 // internal definition (__rw_objc_super) that is uses. This is why
2889 // we need the cast below. For example:
2890 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2891 //
2892 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2893 Context->getPointerType(SuperRep->getType()),
2894 SourceLocation());
2895 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2896 Context->getPointerType(superType),
2897 CastExpr::CK_Unknown, SuperRep);
2898 } else {
2899 // (struct objc_super) { <exprs from above> }
2900 InitListExpr *ILE =
2901 new (Context) InitListExpr(*Context, SourceLocation(),
2902 &InitExprs[0], InitExprs.size(),
2903 SourceLocation());
2904 TypeSourceInfo *superTInfo
2905 = Context->getTrivialTypeSourceInfo(superType);
2906 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2907 superType, ILE, false);
2908 }
2909 MsgExprs.push_back(SuperRep);
2910 break;
2911 }
2912
2913 case ObjCMessageExpr::Instance: {
2914 // Remove all type-casts because it may contain objc-style types; e.g.
2915 // Foo<Proto> *.
2916 Expr *recExpr = Exp->getInstanceReceiver();
2917 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2918 recExpr = CE->getSubExpr();
2919 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2920 CastExpr::CK_Unknown, recExpr);
2921 MsgExprs.push_back(recExpr);
2922 break;
2923 }
2924 }
2925
Steve Naroffbeaf2992007-11-03 11:27:19 +00002926 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002927 llvm::SmallVector<Expr*, 8> SelExprs;
2928 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002929 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002930 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002931 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002932 false, argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00002933 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002934 &SelExprs[0], SelExprs.size(),
2935 StartLoc,
2936 EndLoc);
Steve Naroff934f2762007-10-24 22:48:43 +00002937 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002938
Steve Naroff934f2762007-10-24 22:48:43 +00002939 // Now push any user supplied arguments.
2940 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002941 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002942 // Make all implicit casts explicit...ICE comes in handy:-)
2943 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2944 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002945 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002946 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002947 : ICE->getType();
John McCall9d125032010-01-15 18:39:57 +00002948 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CastExpr::CK_Unknown,
2949 userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002950 }
2951 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002952 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002953 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002954 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002955 userExpr = CE->getSubExpr();
John McCall9d125032010-01-15 18:39:57 +00002956 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2957 CastExpr::CK_Unknown, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002958 }
Mike Stump1eb44332009-09-09 15:08:12 +00002959 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002960 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00002961 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2962 // out the argument in the original expression (since we aren't deleting
2963 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2964 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00002965 }
Steve Naroffab972d32007-11-04 22:37:50 +00002966 // Generate the funky cast.
2967 CastExpr *cast;
2968 llvm::SmallVector<QualType, 8> ArgTypes;
2969 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00002970
Steve Naroffab972d32007-11-04 22:37:50 +00002971 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002972 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2973 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2974 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002975 ArgTypes.push_back(Context->getObjCIdType());
2976 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00002977 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002978 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00002979 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2980 E = OMD->param_end(); PI != E; ++PI) {
2981 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00002982 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00002983 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002984 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00002985 if (isTopLevelBlockPointerType(t)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002986 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroffa206b062008-10-29 14:49:46 +00002987 t = Context->getPointerType(BPT->getPointeeType());
2988 }
Steve Naroff352336b2007-11-05 14:36:37 +00002989 ArgTypes.push_back(t);
2990 }
Chris Lattner89951a82009-02-20 18:43:26 +00002991 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2992 ? Context->getObjCIdType() : OMD->getResultType();
Fariborz Jahanian86aa9fd2010-02-24 01:25:40 +00002993 if (isTopLevelBlockPointerType(returnType)) {
2994 const BlockPointerType *BPT = returnType->getAs<BlockPointerType>();
2995 returnType = Context->getPointerType(BPT->getPointeeType());
2996 }
Steve Naroffab972d32007-11-04 22:37:50 +00002997 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002998 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002999 }
3000 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00003001 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003002
Steve Naroffab972d32007-11-04 22:37:50 +00003003 // Create a reference to the objc_msgSend() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003004 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003005 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00003006
Mike Stump1eb44332009-09-09 15:08:12 +00003007 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00003008 // If we don't do this cast, we get the following bizarre warning/note:
3009 // xx.m:13: warning: function called through a non-compatible type
3010 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00003011 cast = NoTypeInfoCStyleCastExpr(Context,
3012 Context->getPointerType(Context->VoidTy),
3013 CastExpr::CK_Unknown, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00003014
Steve Naroffab972d32007-11-04 22:37:50 +00003015 // Now do the "normal" pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00003016 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00003017 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00003018 // If we don't have a method decl, force a variadic cast.
Douglas Gregorce056bc2010-02-21 22:15:06 +00003019 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00003020 false, false, 0, 0,
3021 FunctionType::ExtInfo());
Steve Naroffab972d32007-11-04 22:37:50 +00003022 castType = Context->getPointerType(castType);
John McCall9d125032010-01-15 18:39:57 +00003023 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
3024 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00003025
3026 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003027 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003028
John McCall183700f2009-09-21 23:43:11 +00003029 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003030 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003031 MsgExprs.size(),
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003032 FT->getResultType(), EndLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003033 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003034 if (MsgSendStretFlavor) {
3035 // We have the method which returns a struct/union. Must also generate
3036 // call to objc_msgSend_stret and hang both varieties on a conditional
3037 // expression which dictate which one to envoke depending on size of
3038 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00003039
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003040 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003041 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003042 SourceLocation());
3043 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall9d125032010-01-15 18:39:57 +00003044 cast = NoTypeInfoCStyleCastExpr(Context,
3045 Context->getPointerType(Context->VoidTy),
3046 CastExpr::CK_Unknown, STDRE);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003047 // Now do the "normal" pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00003048 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00003049 &ArgTypes[0], ArgTypes.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00003050 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00003051 false, false, 0, 0,
3052 FunctionType::ExtInfo());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003053 castType = Context->getPointerType(castType);
John McCall9d125032010-01-15 18:39:57 +00003054 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
3055 cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003056
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003057 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003058 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003059
John McCall183700f2009-09-21 23:43:11 +00003060 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003061 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003062 MsgExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00003063 FT->getResultType(), SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003064
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003065 // Build sizeof(returnType)
Mike Stump1eb44332009-09-09 15:08:12 +00003066 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCalla93c9342009-12-07 02:54:59 +00003067 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl05189992008-11-11 17:56:53 +00003068 Context->getSizeType(),
3069 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003070 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3071 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3072 // For X86 it is more complicated and some kind of target specific routine
3073 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00003074 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00003075 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Mike Stump1eb44332009-09-09 15:08:12 +00003076 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003077 Context->IntTy,
3078 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003079 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
3080 BinaryOperator::LE,
3081 Context->IntTy,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003082 SourceLocation());
3083 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00003084 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003085 new (Context) ConditionalOperator(lessThanExpr,
3086 SourceLocation(), CE,
3087 SourceLocation(), STCE, returnType);
Ted Kremenek8189cde2009-02-07 01:47:29 +00003088 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003089 }
Mike Stump1eb44332009-09-09 15:08:12 +00003090 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003091 return ReplacingStmt;
3092}
3093
Steve Naroffb29b4272008-04-14 22:03:09 +00003094Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003095 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3096 Exp->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00003097
Steve Naroff934f2762007-10-24 22:48:43 +00003098 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00003099 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00003100
3101 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003102 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00003103}
3104
Steve Naroff621edce2009-04-29 16:37:50 +00003105// typedef struct objc_object Protocol;
3106QualType RewriteObjC::getProtocolType() {
3107 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00003108 TypeSourceInfo *TInfo
3109 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00003110 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00003111 SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00003112 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00003113 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00003114 }
3115 return Context->getTypeDeclType(ProtocolTypeDecl);
3116}
3117
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003118/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00003119/// a synthesized/forward data reference (to the protocol's metadata).
3120/// The forward references (and metadata) are generated in
3121/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00003122Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00003123 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3124 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00003125 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00003126 ID, getProtocolType(), 0,
3127 VarDecl::Extern, VarDecl::None);
Steve Naroff621edce2009-04-29 16:37:50 +00003128 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
3129 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
3130 Context->getPointerType(DRE->getType()),
3131 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00003132 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3133 CastExpr::CK_Unknown,
3134 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003135 ReplaceStmt(Exp, castExpr);
3136 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump1eb44332009-09-09 15:08:12 +00003137 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003138 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003139
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003140}
3141
Mike Stump1eb44332009-09-09 15:08:12 +00003142bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00003143 const char *endBuf) {
3144 while (startBuf < endBuf) {
3145 if (*startBuf == '#') {
3146 // Skip whitespace.
3147 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3148 ;
3149 if (!strncmp(startBuf, "if", strlen("if")) ||
3150 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3151 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3152 !strncmp(startBuf, "define", strlen("define")) ||
3153 !strncmp(startBuf, "undef", strlen("undef")) ||
3154 !strncmp(startBuf, "else", strlen("else")) ||
3155 !strncmp(startBuf, "elif", strlen("elif")) ||
3156 !strncmp(startBuf, "endif", strlen("endif")) ||
3157 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3158 !strncmp(startBuf, "include", strlen("include")) ||
3159 !strncmp(startBuf, "import", strlen("import")) ||
3160 !strncmp(startBuf, "include_next", strlen("include_next")))
3161 return true;
3162 }
3163 startBuf++;
3164 }
3165 return false;
3166}
3167
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003168/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003169/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00003170void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003171 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003172 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Mike Stump1eb44332009-09-09 15:08:12 +00003173 assert(CDecl->getNameAsCString() &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003174 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003175 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003176 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003177 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003178 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003179 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00003180 SourceLocation LocStart = CDecl->getLocStart();
3181 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00003182
Steve Narofffea763e82007-11-14 19:25:57 +00003183 const char *startBuf = SM->getCharacterData(LocStart);
3184 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00003185
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003186 // If no ivars and no root or if its root, directly or indirectly,
3187 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003188 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3189 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00003190 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003191 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003192 return;
3193 }
Mike Stump1eb44332009-09-09 15:08:12 +00003194
3195 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003196 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003197 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003198 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00003199 if (LangOpts.Microsoft)
3200 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00003201
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003202 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00003203 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00003204 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003205 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00003206 // If the buffer contains preprocessor directives, we do more fine-grained
3207 // rewrites. This is intended to fix code that looks like (which occurs in
3208 // NSURL.h, for example):
3209 //
3210 // #ifdef XYZ
3211 // @interface Foo : NSObject
3212 // #else
3213 // @interface FooBar : NSObject
3214 // #endif
3215 // {
3216 // int i;
3217 // }
3218 // @end
3219 //
3220 // This clause is segregated to avoid breaking the common case.
3221 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003222 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffbaf58c32008-05-31 14:15:04 +00003223 CDecl->getClassLoc();
3224 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00003225 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003226
Chris Lattnercafeb352009-02-20 18:18:36 +00003227 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00003228 // advance to the end of the referenced protocols.
3229 while (endHeader < cursor && *endHeader != '>') endHeader++;
3230 endHeader++;
3231 }
3232 // rewrite the original header
Benjamin Kramerd999b372010-02-14 14:14:16 +00003233 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003234 } else {
3235 // rewrite the original header *without* disturbing the '{'
Benjamin Kramerd999b372010-02-14 14:14:16 +00003236 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003237 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003238 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00003239 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003240 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003241 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003242 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003243 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003244
Steve Narofffea763e82007-11-14 19:25:57 +00003245 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00003246 SourceLocation OnePastCurly =
3247 LocStart.getFileLocWithOffset(cursor-startBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003248 InsertText(OnePastCurly, Result);
Steve Narofffea763e82007-11-14 19:25:57 +00003249 }
3250 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00003251
Steve Narofffea763e82007-11-14 19:25:57 +00003252 // Now comment out any visibility specifiers.
3253 while (cursor < endBuf) {
3254 if (*cursor == '@') {
3255 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00003256 // Skip whitespace.
3257 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3258 /*scan*/;
3259
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003260 // FIXME: presence of @public, etc. inside comment results in
3261 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00003262 if (!strncmp(cursor, "public", strlen("public")) ||
3263 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00003264 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00003265 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramerd999b372010-02-14 14:14:16 +00003266 InsertText(atLoc, "// ");
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003267 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00003268 // FIXME: If there are cases where '<' is used in ivar declaration part
3269 // of user code, then scan the ivar list and use needToScanForQualifiers
3270 // for type checking.
3271 else if (*cursor == '<') {
3272 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003273 InsertText(atLoc, "/* ");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003274 cursor = strchr(cursor, '>');
3275 cursor++;
3276 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003277 InsertText(atLoc, " */");
Steve Naroffced80a82008-10-30 12:09:33 +00003278 } else if (*cursor == '^') { // rewrite block specifier.
3279 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003280 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003281 }
Steve Narofffea763e82007-11-14 19:25:57 +00003282 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003283 }
Steve Narofffea763e82007-11-14 19:25:57 +00003284 // Don't forget to add a ';'!!
Benjamin Kramerd999b372010-02-14 14:14:16 +00003285 InsertText(LocEnd.getFileLocWithOffset(1), ";");
Steve Narofffea763e82007-11-14 19:25:57 +00003286 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003287 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003288 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003289 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003290 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003291 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003292 Result += "_IVARS;\n};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003293 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003294 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003295 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003296 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00003297 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003298}
3299
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003300// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003301/// class methods.
Douglas Gregor653f1b12009-04-23 01:02:12 +00003302template<typename MethodIterator>
3303void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3304 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00003305 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003306 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00003307 const char *ClassName,
3308 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003309 if (MethodBegin == MethodEnd) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003310
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003311 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003312 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003313 SEL _cmd;
3314 char *method_types;
3315 void *_imp;
3316 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003317 */
Chris Lattner158ecb92007-10-25 17:07:24 +00003318 Result += "\nstruct _objc_method {\n";
3319 Result += "\tSEL _cmd;\n";
3320 Result += "\tchar *method_types;\n";
3321 Result += "\tvoid *_imp;\n";
3322 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003323
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003324 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00003325 }
Mike Stump1eb44332009-09-09 15:08:12 +00003326
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003327 // Build _objc_method_list for class's methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003328
Steve Naroff946a6932008-03-11 00:12:29 +00003329 /* struct {
3330 struct _objc_method_list *next_method;
3331 int method_count;
3332 struct _objc_method method_list[];
3333 }
3334 */
Douglas Gregor653f1b12009-04-23 01:02:12 +00003335 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroff946a6932008-03-11 00:12:29 +00003336 Result += "\nstatic struct {\n";
3337 Result += "\tstruct _objc_method_list *next_method;\n";
3338 Result += "\tint method_count;\n";
3339 Result += "\tstruct _objc_method method_list[";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003340 Result += utostr(NumMethods);
Steve Naroff946a6932008-03-11 00:12:29 +00003341 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003342 Result += prefix;
3343 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3344 Result += "_METHODS_";
3345 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003346 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003347 Result += IsInstanceMethod ? "inst" : "cls";
3348 Result += "_meth\")))= ";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003349 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003350
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003351 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003352 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003353 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003354 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003355 Result += "\", \"";
3356 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003357 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003358 Result += MethodInternalNames[*MethodBegin];
3359 Result += "}\n";
3360 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3361 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003362 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003363 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003364 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003365 Result += "\", \"";
3366 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003367 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003368 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00003369 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003370 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003371 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003372}
3373
Steve Naroff621edce2009-04-29 16:37:50 +00003374/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00003375void RewriteObjC::
Steve Naroff621edce2009-04-29 16:37:50 +00003376RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
3377 const char *ClassName, std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003378 static bool objc_protocol_methods = false;
Steve Naroff621edce2009-04-29 16:37:50 +00003379
3380 // Output struct protocol_methods holder of method selector and type.
3381 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3382 /* struct protocol_methods {
3383 SEL _cmd;
3384 char *method_types;
3385 }
3386 */
3387 Result += "\nstruct _protocol_methods {\n";
3388 Result += "\tstruct objc_selector *_cmd;\n";
3389 Result += "\tchar *method_types;\n";
3390 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003391
Steve Naroff621edce2009-04-29 16:37:50 +00003392 objc_protocol_methods = true;
3393 }
3394 // Do not synthesize the protocol more than once.
3395 if (ObjCSynthesizedProtocols.count(PDecl))
3396 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003397
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003398 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3399 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3400 PDecl->instmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003401 /* struct _objc_protocol_method_list {
3402 int protocol_method_count;
3403 struct protocol_methods protocols[];
3404 }
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003405 */
Steve Naroff621edce2009-04-29 16:37:50 +00003406 Result += "\nstatic struct {\n";
3407 Result += "\tint protocol_method_count;\n";
3408 Result += "\tstruct _protocol_methods protocol_methods[";
3409 Result += utostr(NumMethods);
3410 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3411 Result += PDecl->getNameAsString();
3412 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3413 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003414
Steve Naroff621edce2009-04-29 16:37:50 +00003415 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003416 for (ObjCProtocolDecl::instmeth_iterator
3417 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003418 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003419 if (I == PDecl->instmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003420 Result += "\t ,{{(struct objc_selector *)\"";
3421 else
3422 Result += "\t ,{(struct objc_selector *)\"";
3423 Result += (*I)->getSelector().getAsString().c_str();
3424 std::string MethodTypeString;
3425 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3426 Result += "\", \"";
3427 Result += MethodTypeString;
3428 Result += "\"}\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003429 }
Steve Naroff621edce2009-04-29 16:37:50 +00003430 Result += "\t }\n};\n";
3431 }
Mike Stump1eb44332009-09-09 15:08:12 +00003432
Steve Naroff621edce2009-04-29 16:37:50 +00003433 // Output class methods declared in this protocol.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003434 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3435 PDecl->classmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003436 if (NumMethods > 0) {
3437 /* struct _objc_protocol_method_list {
3438 int protocol_method_count;
3439 struct protocol_methods protocols[];
3440 }
3441 */
3442 Result += "\nstatic struct {\n";
3443 Result += "\tint protocol_method_count;\n";
3444 Result += "\tstruct _protocol_methods protocol_methods[";
3445 Result += utostr(NumMethods);
3446 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3447 Result += PDecl->getNameAsString();
3448 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3449 "{\n\t";
3450 Result += utostr(NumMethods);
3451 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003452
Steve Naroff621edce2009-04-29 16:37:50 +00003453 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003454 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003455 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003456 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003457 if (I == PDecl->classmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003458 Result += "\t ,{{(struct objc_selector *)\"";
3459 else
3460 Result += "\t ,{(struct objc_selector *)\"";
3461 Result += (*I)->getSelector().getAsString().c_str();
3462 std::string MethodTypeString;
3463 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3464 Result += "\", \"";
3465 Result += MethodTypeString;
3466 Result += "\"}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003467 }
Steve Naroff621edce2009-04-29 16:37:50 +00003468 Result += "\t }\n};\n";
3469 }
3470
3471 // Output:
3472 /* struct _objc_protocol {
3473 // Objective-C 1.0 extensions
3474 struct _objc_protocol_extension *isa;
3475 char *protocol_name;
3476 struct _objc_protocol **protocol_list;
3477 struct _objc_protocol_method_list *instance_methods;
3478 struct _objc_protocol_method_list *class_methods;
Mike Stump1eb44332009-09-09 15:08:12 +00003479 };
Steve Naroff621edce2009-04-29 16:37:50 +00003480 */
3481 static bool objc_protocol = false;
3482 if (!objc_protocol) {
3483 Result += "\nstruct _objc_protocol {\n";
3484 Result += "\tstruct _objc_protocol_extension *isa;\n";
3485 Result += "\tchar *protocol_name;\n";
3486 Result += "\tstruct _objc_protocol **protocol_list;\n";
3487 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3488 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003489 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003490
Steve Naroff621edce2009-04-29 16:37:50 +00003491 objc_protocol = true;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003492 }
Mike Stump1eb44332009-09-09 15:08:12 +00003493
Steve Naroff621edce2009-04-29 16:37:50 +00003494 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3495 Result += PDecl->getNameAsString();
3496 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3497 "{\n\t0, \"";
3498 Result += PDecl->getNameAsString();
3499 Result += "\", 0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003500 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003501 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3502 Result += PDecl->getNameAsString();
3503 Result += ", ";
3504 }
3505 else
3506 Result += "0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003507 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003508 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3509 Result += PDecl->getNameAsString();
3510 Result += "\n";
3511 }
3512 else
3513 Result += "0\n";
3514 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003515
Steve Naroff621edce2009-04-29 16:37:50 +00003516 // Mark this protocol as having been generated.
3517 if (!ObjCSynthesizedProtocols.insert(PDecl))
3518 assert(false && "protocol already synthesized");
3519
3520}
3521
3522void RewriteObjC::
3523RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3524 const char *prefix, const char *ClassName,
3525 std::string &Result) {
3526 if (Protocols.empty()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003527
Steve Naroff621edce2009-04-29 16:37:50 +00003528 for (unsigned i = 0; i != Protocols.size(); i++)
3529 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3530
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003531 // Output the top lovel protocol meta-data for the class.
3532 /* struct _objc_protocol_list {
3533 struct _objc_protocol_list *next;
3534 int protocol_count;
3535 struct _objc_protocol *class_protocols[];
3536 }
3537 */
3538 Result += "\nstatic struct {\n";
3539 Result += "\tstruct _objc_protocol_list *next;\n";
3540 Result += "\tint protocol_count;\n";
3541 Result += "\tstruct _objc_protocol *class_protocols[";
3542 Result += utostr(Protocols.size());
3543 Result += "];\n} _OBJC_";
3544 Result += prefix;
3545 Result += "_PROTOCOLS_";
3546 Result += ClassName;
3547 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3548 "{\n\t0, ";
3549 Result += utostr(Protocols.size());
3550 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003551
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003552 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003553 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003554 Result += " \n";
Mike Stump1eb44332009-09-09 15:08:12 +00003555
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003556 for (unsigned i = 1; i != Protocols.size(); i++) {
3557 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003558 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003559 Result += "\n";
3560 }
3561 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003562}
3563
Steve Naroff621edce2009-04-29 16:37:50 +00003564
Mike Stump1eb44332009-09-09 15:08:12 +00003565/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003566/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003567void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003568 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003569 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003570 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003571 ObjCCategoryDecl *CDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00003572 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003573 CDecl = CDecl->getNextClassCategory())
3574 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3575 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003576
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003577 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003578 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003579 FullCategoryName += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003580
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003581 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003582 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003583 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003584
3585 // If any of our property implementations have associated getters or
3586 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003587 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3588 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003589 Prop != PropEnd; ++Prop) {
3590 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3591 continue;
3592 if (!(*Prop)->getPropertyIvarDecl())
3593 continue;
3594 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3595 if (!PD)
3596 continue;
3597 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3598 InstanceMethods.push_back(Getter);
3599 if (PD->isReadOnly())
3600 continue;
3601 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3602 InstanceMethods.push_back(Setter);
3603 }
3604 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003605 true, "CATEGORY_", FullCategoryName.c_str(),
3606 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003607
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003608 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003609 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003610 false, "CATEGORY_", FullCategoryName.c_str(),
3611 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003612
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003613 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003614 // Null CDecl is case of a category implementation with no category interface
3615 if (CDecl)
Steve Naroff621edce2009-04-29 16:37:50 +00003616 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3617 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003618 /* struct _objc_category {
3619 char *category_name;
3620 char *class_name;
3621 struct _objc_method_list *instance_methods;
3622 struct _objc_method_list *class_methods;
3623 struct _objc_protocol_list *protocols;
3624 // Objective-C 1.0 extensions
3625 uint32_t size; // sizeof (struct _objc_category)
Mike Stump1eb44332009-09-09 15:08:12 +00003626 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003627 // @property decl.
Mike Stump1eb44332009-09-09 15:08:12 +00003628 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003629 */
Mike Stump1eb44332009-09-09 15:08:12 +00003630
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003631 static bool objc_category = false;
3632 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003633 Result += "\nstruct _objc_category {\n";
3634 Result += "\tchar *category_name;\n";
3635 Result += "\tchar *class_name;\n";
3636 Result += "\tstruct _objc_method_list *instance_methods;\n";
3637 Result += "\tstruct _objc_method_list *class_methods;\n";
3638 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003639 Result += "\tunsigned int size;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003640 Result += "\tstruct _objc_property_list *instance_properties;\n";
3641 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003642 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003643 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003644 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3645 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003646 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003647 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003648 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003649 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003650 Result += "\"\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003651
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003652 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003653 Result += "\t, (struct _objc_method_list *)"
3654 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3655 Result += FullCategoryName;
3656 Result += "\n";
3657 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003658 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003659 Result += "\t, 0\n";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003660 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003661 Result += "\t, (struct _objc_method_list *)"
3662 "&_OBJC_CATEGORY_CLASS_METHODS_";
3663 Result += FullCategoryName;
3664 Result += "\n";
3665 }
3666 else
3667 Result += "\t, 0\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003668
Chris Lattnercafeb352009-02-20 18:18:36 +00003669 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003670 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003671 Result += FullCategoryName;
3672 Result += "\n";
3673 }
3674 else
3675 Result += "\t, 0\n";
3676 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003677}
3678
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003679/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3680/// ivar offset.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00003681void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCContainerDecl *IDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00003682 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003683 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003684 if (ivar->isBitField()) {
3685 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3686 // place all bitfields at offset 0.
3687 Result += "0";
3688 } else {
3689 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003690 Result += IDecl->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003691 if (LangOpts.Microsoft)
3692 Result += "_IMPL";
3693 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003694 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003695 Result += ")";
3696 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003697}
3698
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003699//===----------------------------------------------------------------------===//
3700// Meta Data Emission
3701//===----------------------------------------------------------------------===//
3702
Steve Naroffb29b4272008-04-14 22:03:09 +00003703void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003704 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003705 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00003706
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003707 // Explictly declared @interface's are already synthesized.
Steve Naroff33feeb02009-04-20 20:09:33 +00003708 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003709 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003710 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003711 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003712 }
Mike Stump1eb44332009-09-09 15:08:12 +00003713
Chris Lattnerbe6df082007-12-12 07:56:42 +00003714 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003715 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump1eb44332009-09-09 15:08:12 +00003716 ? IDecl->ivar_size()
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003717 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003718 if (NumIvars > 0) {
3719 static bool objc_ivar = false;
3720 if (!objc_ivar) {
3721 /* struct _objc_ivar {
3722 char *ivar_name;
3723 char *ivar_type;
3724 int ivar_offset;
Mike Stump1eb44332009-09-09 15:08:12 +00003725 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003726 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003727 Result += "\nstruct _objc_ivar {\n";
3728 Result += "\tchar *ivar_name;\n";
3729 Result += "\tchar *ivar_type;\n";
3730 Result += "\tint ivar_offset;\n";
3731 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003732
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003733 objc_ivar = true;
3734 }
3735
Steve Naroff946a6932008-03-11 00:12:29 +00003736 /* struct {
3737 int ivar_count;
3738 struct _objc_ivar ivar_list[nIvars];
Mike Stump1eb44332009-09-09 15:08:12 +00003739 };
Steve Naroff946a6932008-03-11 00:12:29 +00003740 */
Mike Stump1eb44332009-09-09 15:08:12 +00003741 Result += "\nstatic struct {\n";
Steve Naroff946a6932008-03-11 00:12:29 +00003742 Result += "\tint ivar_count;\n";
3743 Result += "\tstruct _objc_ivar ivar_list[";
3744 Result += utostr(NumIvars);
3745 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003746 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003747 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003748 "{\n\t";
3749 Result += utostr(NumIvars);
3750 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003751
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003752 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003753 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003754 if (!IDecl->ivar_empty()) {
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003755 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003756 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003757 IV != IVEnd; ++IV)
3758 IVars.push_back(*IV);
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003759 IVI = IDecl->ivar_begin();
3760 IVE = IDecl->ivar_end();
Chris Lattnerbe6df082007-12-12 07:56:42 +00003761 } else {
3762 IVI = CDecl->ivar_begin();
3763 IVE = CDecl->ivar_end();
3764 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003765 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003766 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003767 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003768 std::string TmpString, StrEncoding;
3769 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3770 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003771 Result += StrEncoding;
3772 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003773 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003774 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003775 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003776 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003777 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003778 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003779 std::string TmpString, StrEncoding;
3780 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3781 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003782 Result += StrEncoding;
3783 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003784 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003785 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003786 }
Mike Stump1eb44332009-09-09 15:08:12 +00003787
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003788 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003789 }
Mike Stump1eb44332009-09-09 15:08:12 +00003790
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003791 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003792 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003793 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003794
3795 // If any of our property implementations have associated getters or
3796 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003797 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3798 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003799 Prop != PropEnd; ++Prop) {
3800 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3801 continue;
3802 if (!(*Prop)->getPropertyIvarDecl())
3803 continue;
3804 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3805 if (!PD)
3806 continue;
3807 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3808 InstanceMethods.push_back(Getter);
3809 if (PD->isReadOnly())
3810 continue;
3811 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3812 InstanceMethods.push_back(Setter);
3813 }
3814 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003815 true, "", IDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003816
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003817 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003818 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003819 false, "", IDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003820
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003821 // Protocols referenced in class declaration?
Steve Naroff621edce2009-04-29 16:37:50 +00003822 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3823 "CLASS", CDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003824
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003825 // Declaration of class/meta-class metadata
3826 /* struct _objc_class {
3827 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003828 const char *super_class_name;
3829 char *name;
3830 long version;
3831 long info;
3832 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003833 struct _objc_ivar_list *ivars;
3834 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003835 struct objc_cache *cache;
3836 struct objc_protocol_list *protocols;
3837 const char *ivar_layout;
3838 struct _objc_class_ext *ext;
Mike Stump1eb44332009-09-09 15:08:12 +00003839 };
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003840 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003841 static bool objc_class = false;
3842 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003843 Result += "\nstruct _objc_class {\n";
3844 Result += "\tstruct _objc_class *isa;\n";
3845 Result += "\tconst char *super_class_name;\n";
3846 Result += "\tchar *name;\n";
3847 Result += "\tlong version;\n";
3848 Result += "\tlong info;\n";
3849 Result += "\tlong instance_size;\n";
3850 Result += "\tstruct _objc_ivar_list *ivars;\n";
3851 Result += "\tstruct _objc_method_list *methods;\n";
3852 Result += "\tstruct objc_cache *cache;\n";
3853 Result += "\tstruct _objc_protocol_list *protocols;\n";
3854 Result += "\tconst char *ivar_layout;\n";
3855 Result += "\tstruct _objc_class_ext *ext;\n";
3856 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003857 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003858 }
Mike Stump1eb44332009-09-09 15:08:12 +00003859
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003860 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003861 ObjCInterfaceDecl *RootClass = 0;
3862 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003863 while (SuperClass) {
3864 RootClass = SuperClass;
3865 SuperClass = SuperClass->getSuperClass();
3866 }
3867 SuperClass = CDecl->getSuperClass();
Mike Stump1eb44332009-09-09 15:08:12 +00003868
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003869 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003870 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003871 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003872 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003873 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003874 Result += "\"";
3875
3876 if (SuperClass) {
3877 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003878 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003879 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003880 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003881 Result += "\"";
3882 }
3883 else {
3884 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003885 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003886 Result += "\"";
3887 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003888 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003889 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003890 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003891 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff23f41272008-03-11 18:14:26 +00003892 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003893 Result += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003894 Result += "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003895 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003896 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003897 Result += ", 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00003898 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003899 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003900 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003901 Result += ",0,0\n";
3902 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003903 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003904 Result += "\t,0,0,0,0\n";
3905 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003906
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003907 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003908 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003909 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003910 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003911 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003912 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003913 if (SuperClass) {
3914 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003915 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003916 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003917 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003918 Result += "\"";
3919 }
3920 else {
3921 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003922 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003923 Result += "\"";
3924 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003925 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003926 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003927 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003928 Result += ",0";
3929 else {
3930 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003931 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003932 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003933 if (LangOpts.Microsoft)
3934 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003935 Result += ")";
3936 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003937 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003938 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003939 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003940 Result += "\n\t";
3941 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003942 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003943 Result += ",0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003944 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroff946a6932008-03-11 00:12:29 +00003945 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003946 Result += CDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003947 Result += ", 0\n\t";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003948 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003949 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003950 Result += ",0,0";
Chris Lattnercafeb352009-02-20 18:18:36 +00003951 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003952 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003953 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003954 Result += ", 0,0\n";
3955 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003956 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003957 Result += ",0,0,0\n";
3958 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003959}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003960
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003961/// RewriteImplementations - This routine rewrites all method implementations
3962/// and emits meta-data.
3963
Steve Narofface66252008-11-13 20:07:04 +00003964void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003965 int ClsDefCount = ClassImplementation.size();
3966 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003967
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003968 // Rewrite implemented methods
3969 for (int i = 0; i < ClsDefCount; i++)
3970 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00003971
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003972 for (int i = 0; i < CatDefCount; i++)
3973 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003974}
Mike Stump1eb44332009-09-09 15:08:12 +00003975
Steve Narofface66252008-11-13 20:07:04 +00003976void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3977 int ClsDefCount = ClassImplementation.size();
3978 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00003979
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003980 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003981 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003982 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003983
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003984 // For each implemented category, write out all its meta data.
3985 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003986 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroff621edce2009-04-29 16:37:50 +00003987
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003988 // Write objc_symtab metadata
3989 /*
3990 struct _objc_symtab
3991 {
3992 long sel_ref_cnt;
3993 SEL *refs;
3994 short cls_def_cnt;
3995 short cat_def_cnt;
3996 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump1eb44332009-09-09 15:08:12 +00003997 };
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003998 */
Mike Stump1eb44332009-09-09 15:08:12 +00003999
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004000 Result += "\nstruct _objc_symtab {\n";
4001 Result += "\tlong sel_ref_cnt;\n";
4002 Result += "\tSEL *refs;\n";
4003 Result += "\tshort cls_def_cnt;\n";
4004 Result += "\tshort cat_def_cnt;\n";
4005 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
4006 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004007
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004008 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00004009 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004010 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004011 + ", " + utostr(CatDefCount) + "\n";
4012 for (int i = 0; i < ClsDefCount; i++) {
4013 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004014 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004015 Result += "\n";
4016 }
Mike Stump1eb44332009-09-09 15:08:12 +00004017
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004018 for (int i = 0; i < CatDefCount; i++) {
4019 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004020 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004021 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004022 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004023 Result += "\n";
4024 }
Mike Stump1eb44332009-09-09 15:08:12 +00004025
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004026 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004027
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004028 // Write objc_module metadata
Mike Stump1eb44332009-09-09 15:08:12 +00004029
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004030 /*
4031 struct _objc_module {
4032 long version;
4033 long size;
4034 const char *name;
4035 struct _objc_symtab *symtab;
4036 }
4037 */
Mike Stump1eb44332009-09-09 15:08:12 +00004038
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004039 Result += "\nstruct _objc_module {\n";
4040 Result += "\tlong version;\n";
4041 Result += "\tlong size;\n";
4042 Result += "\tconst char *name;\n";
4043 Result += "\tstruct _objc_symtab *symtab;\n";
4044 Result += "};\n\n";
4045 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00004046 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004047 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00004048 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004049 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004050
4051 if (LangOpts.Microsoft) {
Steve Naroff621edce2009-04-29 16:37:50 +00004052 if (ProtocolExprDecls.size()) {
4053 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
4054 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004055 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00004056 E = ProtocolExprDecls.end(); I != E; ++I) {
4057 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
4058 Result += (*I)->getNameAsString();
4059 Result += " = &_OBJC_PROTOCOL_";
4060 Result += (*I)->getNameAsString();
4061 Result += ";\n";
4062 }
4063 Result += "#pragma data_seg(pop)\n\n";
4064 }
Steve Naroff4f943c22008-03-10 20:43:59 +00004065 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00004066 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004067 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
4068 Result += "&_OBJC_MODULES;\n";
4069 Result += "#pragma data_seg(pop)\n\n";
4070 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004071}
Chris Lattner311ff022007-10-16 22:36:42 +00004072
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004073void RewriteObjC::RewriteByRefString(std::string &ResultStr,
4074 const std::string &Name,
4075 ValueDecl *VD) {
4076 assert(BlockByRefDeclNo.count(VD) &&
4077 "RewriteByRefString: ByRef decl missing");
4078 ResultStr += "struct __Block_byref_" + Name +
4079 "_" + utostr(BlockByRefDeclNo[VD]) ;
4080}
4081
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004082static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4083 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4084 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4085 return false;
4086}
4087
Steve Naroff54055232008-10-27 17:20:55 +00004088std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4089 const char *funcName,
4090 std::string Tag) {
4091 const FunctionType *AFT = CE->getFunctionType();
4092 QualType RT = AFT->getResultType();
4093 std::string StructRef = "struct " + Tag;
4094 std::string S = "static " + RT.getAsString() + " __" +
4095 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00004096
Steve Naroff54055232008-10-27 17:20:55 +00004097 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004098
Douglas Gregor72564e72009-02-26 23:50:07 +00004099 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004100 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00004101 // block (to reference imported block decl refs).
4102 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00004103 } else if (BD->param_empty()) {
4104 S += "(" + StructRef + " *__cself)";
4105 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004106 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00004107 assert(FT && "SynthesizeBlockFunc: No function proto");
4108 S += '(';
4109 // first add the implicit argument.
4110 S += StructRef + " *__cself, ";
4111 std::string ParamStr;
4112 for (BlockDecl::param_iterator AI = BD->param_begin(),
4113 E = BD->param_end(); AI != E; ++AI) {
4114 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004115 ParamStr = (*AI)->getNameAsString();
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00004116 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00004117 S += ParamStr;
4118 }
4119 if (FT->isVariadic()) {
4120 if (!BD->param_empty()) S += ", ";
4121 S += "...";
4122 }
4123 S += ')';
4124 }
4125 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004126
Steve Naroff54055232008-10-27 17:20:55 +00004127 // Create local declarations to avoid rewriting all closure decl ref exprs.
4128 // First, emit a declaration for all "by ref" decls.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004129 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004130 E = BlockByRefDecls.end(); I != E; ++I) {
4131 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004132 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004133 std::string TypeString;
4134 RewriteByRefString(TypeString, Name, (*I));
4135 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004136 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004137 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004138 }
Steve Naroff54055232008-10-27 17:20:55 +00004139 // Next, emit a declaration for all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004140 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004141 E = BlockByCopyDecls.end(); I != E; ++I) {
4142 S += " ";
Steve Naroff54055232008-10-27 17:20:55 +00004143 // Handle nested closure invocation. For example:
4144 //
4145 // void (^myImportedClosure)(void);
4146 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004147 //
Steve Naroff54055232008-10-27 17:20:55 +00004148 // void (^anotherClosure)(void);
4149 // anotherClosure = ^(void) {
4150 // myImportedClosure(); // import and invoke the closure
4151 // };
4152 //
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004153 if (isTopLevelBlockPointerType((*I)->getType())) {
4154 RewriteBlockPointerTypeVariable(S, (*I));
4155 S += " = (";
4156 RewriteBlockPointerType(S, (*I)->getType());
4157 S += ")";
4158 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4159 }
4160 else {
Fariborz Jahanian210c2482010-02-16 17:26:03 +00004161 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004162 QualType QT = (*I)->getType();
4163 if (HasLocalVariableExternalStorage(*I))
4164 QT = Context->getPointerType(QT);
4165 QT.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004166 S += Name + " = __cself->" +
4167 (*I)->getNameAsString() + "; // bound by copy\n";
4168 }
Steve Naroff54055232008-10-27 17:20:55 +00004169 }
4170 std::string RewrittenStr = RewrittenBlockExprs[CE];
4171 const char *cstr = RewrittenStr.c_str();
4172 while (*cstr++ != '{') ;
4173 S += cstr;
4174 S += "\n";
4175 return S;
4176}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00004177
Steve Naroff54055232008-10-27 17:20:55 +00004178std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4179 const char *funcName,
4180 std::string Tag) {
4181 std::string StructRef = "struct " + Tag;
4182 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00004183
Steve Naroff54055232008-10-27 17:20:55 +00004184 S += funcName;
4185 S += "_block_copy_" + utostr(i);
4186 S += "(" + StructRef;
4187 S += "*dst, " + StructRef;
4188 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004189 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004190 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00004191 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004192 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00004193 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004194 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004195 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004196 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004197 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004198 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004199 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004200 S += "}\n";
4201
Steve Naroff54055232008-10-27 17:20:55 +00004202 S += "\nstatic void __";
4203 S += funcName;
4204 S += "_block_dispose_" + utostr(i);
4205 S += "(" + StructRef;
4206 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004207 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004208 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00004209 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004210 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004211 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004212 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004213 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004214 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004215 }
Mike Stump1eb44332009-09-09 15:08:12 +00004216 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00004217 return S;
4218}
4219
Steve Naroff01aec112009-12-06 21:14:13 +00004220std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4221 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00004222 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00004223 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00004224
Steve Naroff54055232008-10-27 17:20:55 +00004225 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004226 S += " struct " + Desc;
4227 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004228
Steve Naroff01aec112009-12-06 21:14:13 +00004229 Constructor += "(void *fp, "; // Invoke function pointer.
4230 Constructor += "struct " + Desc; // Descriptor pointer.
4231 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00004232
Steve Naroff54055232008-10-27 17:20:55 +00004233 if (BlockDeclRefs.size()) {
4234 // Output all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004235 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004236 E = BlockByCopyDecls.end(); I != E; ++I) {
4237 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004238 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004239 std::string ArgName = "_" + FieldName;
4240 // Handle nested closure invocation. For example:
4241 //
4242 // void (^myImportedBlock)(void);
4243 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004244 //
Steve Naroff54055232008-10-27 17:20:55 +00004245 // void (^anotherBlock)(void);
4246 // anotherBlock = ^(void) {
4247 // myImportedBlock(); // import and invoke the closure
4248 // };
4249 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004250 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004251 S += "struct __block_impl *";
4252 Constructor += ", void *" + ArgName;
4253 } else {
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004254 QualType QT = (*I)->getType();
4255 if (HasLocalVariableExternalStorage(*I))
4256 QT = Context->getPointerType(QT);
4257 QT.getAsStringInternal(FieldName, Context->PrintingPolicy);
4258 QT.getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00004259 Constructor += ", " + ArgName;
4260 }
4261 S += FieldName + ";\n";
4262 }
4263 // Output all "by ref" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004264 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004265 E = BlockByRefDecls.end(); I != E; ++I) {
4266 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004267 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004268 std::string ArgName = "_" + FieldName;
4269 // Handle nested closure invocation. For example:
4270 //
4271 // void (^myImportedBlock)(void);
4272 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004273 //
Steve Naroff54055232008-10-27 17:20:55 +00004274 // void (^anotherBlock)(void);
4275 // anotherBlock = ^(void) {
4276 // myImportedBlock(); // import and invoke the closure
4277 // };
4278 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004279 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004280 S += "struct __block_impl *";
4281 Constructor += ", void *" + ArgName;
4282 } else {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004283 std::string TypeString;
4284 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004285 TypeString += " *";
4286 FieldName = TypeString + FieldName;
4287 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00004288 Constructor += ", " + ArgName;
4289 }
4290 S += FieldName + "; // by ref\n";
4291 }
4292 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00004293 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004294 if (GlobalVarDecl)
4295 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4296 else
4297 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004298 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004299
Steve Naroff01aec112009-12-06 21:14:13 +00004300 Constructor += " Desc = desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004301
Steve Naroff54055232008-10-27 17:20:55 +00004302 // Initialize all "by copy" arguments.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004303 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004304 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004305 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004306 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004307 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00004308 Constructor += Name + " = (struct __block_impl *)_";
4309 else
4310 Constructor += Name + " = _";
4311 Constructor += Name + ";\n";
4312 }
4313 // Initialize all "by ref" arguments.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004314 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004315 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004316 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004317 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004318 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00004319 Constructor += Name + " = (struct __block_impl *)_";
4320 else
4321 Constructor += Name + " = _";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004322 Constructor += Name + "->__forwarding;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004323 }
4324 } else {
4325 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00004326 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004327 if (GlobalVarDecl)
4328 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4329 else
4330 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004331 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4332 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004333 }
4334 Constructor += " ";
4335 Constructor += "}\n";
4336 S += Constructor;
4337 S += "};\n";
4338 return S;
4339}
4340
Steve Naroff01aec112009-12-06 21:14:13 +00004341std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4342 std::string ImplTag, int i,
4343 const char *FunName,
4344 unsigned hasCopy) {
4345 std::string S = "\nstatic struct " + DescTag;
4346
4347 S += " {\n unsigned long reserved;\n";
4348 S += " unsigned long Block_size;\n";
4349 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004350 S += " void (*copy)(struct ";
4351 S += ImplTag; S += "*, struct ";
4352 S += ImplTag; S += "*);\n";
4353
4354 S += " void (*dispose)(struct ";
4355 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004356 }
4357 S += "} ";
4358
4359 S += DescTag + "_DATA = { 0, sizeof(struct ";
4360 S += ImplTag + ")";
4361 if (hasCopy) {
4362 S += ", __" + std::string(FunName) + "_block_copy_" + utostr(i);
4363 S += ", __" + std::string(FunName) + "_block_dispose_" + utostr(i);
4364 }
4365 S += "};\n";
4366 return S;
4367}
4368
Steve Naroff54055232008-10-27 17:20:55 +00004369void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004370 const char *FunName) {
4371 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00004372 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004373 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004374 bool RewriteSC = (GlobalVarDecl &&
4375 !Blocks.empty() &&
4376 GlobalVarDecl->getStorageClass() == VarDecl::Static &&
4377 GlobalVarDecl->getType().getCVRQualifiers());
4378 if (RewriteSC) {
4379 std::string SC(" void __");
4380 SC += GlobalVarDecl->getNameAsString();
4381 SC += "() {}";
4382 InsertText(FunLocStart, SC);
4383 }
4384
Steve Naroff54055232008-10-27 17:20:55 +00004385 // Insert closures that were part of the function.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004386 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4387 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004388 // Need to copy-in the inner copied-in variables not actually used in this
4389 // block.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004390 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4391 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
4392 ValueDecl *VD = Exp->getDecl();
4393 BlockDeclRefs.push_back(Exp);
4394 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4395 BlockByCopyDeclsPtrSet.insert(VD);
4396 BlockByCopyDecls.push_back(VD);
4397 }
4398 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4399 BlockByRefDeclsPtrSet.insert(VD);
4400 BlockByRefDecls.push_back(VD);
4401 }
4402 }
Steve Naroff54055232008-10-27 17:20:55 +00004403
Steve Naroff01aec112009-12-06 21:14:13 +00004404 std::string ImplTag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
4405 std::string DescTag = "__" + std::string(FunName) + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00004406
Steve Naroff01aec112009-12-06 21:14:13 +00004407 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00004408
Benjamin Kramerd999b372010-02-14 14:14:16 +00004409 InsertText(FunLocStart, CI);
Steve Naroff54055232008-10-27 17:20:55 +00004410
Steve Naroff01aec112009-12-06 21:14:13 +00004411 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00004412
Benjamin Kramerd999b372010-02-14 14:14:16 +00004413 InsertText(FunLocStart, CF);
Steve Naroff54055232008-10-27 17:20:55 +00004414
4415 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00004416 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004417 InsertText(FunLocStart, HF);
Steve Naroff54055232008-10-27 17:20:55 +00004418 }
Steve Naroff01aec112009-12-06 21:14:13 +00004419 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4420 ImportedBlockDecls.size() > 0);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004421 InsertText(FunLocStart, BD);
Mike Stump1eb44332009-09-09 15:08:12 +00004422
Steve Naroff54055232008-10-27 17:20:55 +00004423 BlockDeclRefs.clear();
4424 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004425 BlockByRefDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004426 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004427 BlockByCopyDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004428 ImportedBlockDecls.clear();
4429 }
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004430 if (RewriteSC) {
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004431 // Must insert any 'const/volatile/static here. Since it has been
4432 // removed as result of rewriting of block literals.
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004433 std::string SC;
4434 if (GlobalVarDecl->getStorageClass() == VarDecl::Static)
4435 SC = "static ";
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004436 if (GlobalVarDecl->getType().isConstQualified())
4437 SC += "const ";
4438 if (GlobalVarDecl->getType().isVolatileQualified())
4439 SC += "volatile ";
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004440 if (GlobalVarDecl->getType().isRestrictQualified())
4441 SC += "restrict ";
4442 InsertText(FunLocStart, SC);
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004443 }
4444
Steve Naroff54055232008-10-27 17:20:55 +00004445 Blocks.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004446 InnerDeclRefsCount.clear();
4447 InnerDeclRefs.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004448 RewrittenBlockExprs.clear();
4449}
4450
4451void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4452 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner8ec03f52008-11-24 03:54:41 +00004453 const char *FuncName = FD->getNameAsCString();
Mike Stump1eb44332009-09-09 15:08:12 +00004454
Steve Naroff54055232008-10-27 17:20:55 +00004455 SynthesizeBlockLiterals(FunLocStart, FuncName);
4456}
4457
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004458static void BuildUniqueMethodName(std::string &Name,
4459 ObjCMethodDecl *MD) {
4460 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4461 Name = IFace->getNameAsCString();
4462 Name += "__" + MD->getSelector().getAsString();
4463 // Convert colons to underscores.
4464 std::string::size_type loc = 0;
4465 while ((loc = Name.find(":", loc)) != std::string::npos)
4466 Name.replace(loc, 1, "_");
4467}
4468
Steve Naroff54055232008-10-27 17:20:55 +00004469void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00004470 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4471 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00004472 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004473 std::string FuncName;
4474 BuildUniqueMethodName(FuncName, MD);
Steve Naroff54055232008-10-27 17:20:55 +00004475 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
4476}
4477
4478void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4479 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4480 CI != E; ++CI)
4481 if (*CI) {
4482 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4483 GetBlockDeclRefExprs(CBE->getBody());
4484 else
4485 GetBlockDeclRefExprs(*CI);
4486 }
4487 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004488 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Steve Naroff54055232008-10-27 17:20:55 +00004489 // FIXME: Handle enums.
4490 if (!isa<FunctionDecl>(CDRE->getDecl()))
4491 BlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004492 }
4493 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4494 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
4495 BlockDeclRefExpr *BDRE =
4496 new (Context)BlockDeclRefExpr(DRE->getDecl(), DRE->getType(),
4497 DRE->getLocation(), false);
4498 BlockDeclRefs.push_back(BDRE);
4499 }
4500
Steve Naroff54055232008-10-27 17:20:55 +00004501 return;
4502}
4503
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004504void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4505 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004506 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004507 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4508 CI != E; ++CI)
4509 if (*CI) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004510 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4511 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004512 GetInnerBlockDeclRefExprs(CBE->getBody(),
4513 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004514 InnerContexts);
4515 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004516 else
4517 GetInnerBlockDeclRefExprs(*CI,
4518 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004519 InnerContexts);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004520
4521 }
4522 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004523 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004524 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004525 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004526 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004527 }
4528 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4529 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4530 if (Var->isFunctionOrMethodVarDecl())
4531 ImportedLocalExternalDecls.insert(Var);
4532 }
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004533
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004534 return;
4535}
4536
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004537Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00004538 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00004539 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004540
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004541 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004542 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004543 } else if (const BlockDeclRefExpr *CDRE =
4544 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004545 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004546 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004547 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004548 }
4549 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4550 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4551 }
4552 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4553 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4554 else if (const ConditionalOperator *CEXPR =
4555 dyn_cast<ConditionalOperator>(BlockExp)) {
4556 Expr *LHSExp = CEXPR->getLHS();
4557 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4558 Expr *RHSExp = CEXPR->getRHS();
4559 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4560 Expr *CONDExp = CEXPR->getCond();
4561 ConditionalOperator *CondExpr =
4562 new (Context) ConditionalOperator(CONDExp,
4563 SourceLocation(), cast<Expr>(LHSStmt),
4564 SourceLocation(), cast<Expr>(RHSStmt),
4565 Exp->getType());
4566 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00004567 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4568 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004569 } else {
4570 assert(1 && "RewriteBlockClass: Bad type");
4571 }
4572 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00004573 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00004574 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00004575 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00004576 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004577
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004578 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4579 SourceLocation(),
4580 &Context->Idents.get("__block_impl"));
4581 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00004582
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004583 // Generate a funky cast.
4584 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004585
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004586 // Push the block argument type.
4587 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00004588 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004589 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004590 E = FTP->arg_type_end(); I && (I != E); ++I) {
4591 QualType t = *I;
4592 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004593 if (isTopLevelBlockPointerType(t)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004594 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004595 t = Context->getPointerType(BPT->getPointeeType());
4596 }
4597 ArgTypes.push_back(t);
4598 }
Steve Naroff54055232008-10-27 17:20:55 +00004599 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004600 // Now do the pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00004601 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00004602 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0,
4603 false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00004604 FunctionType::ExtInfo());
Mike Stump1eb44332009-09-09 15:08:12 +00004605
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004606 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00004607
John McCall9d125032010-01-15 18:39:57 +00004608 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4609 CastExpr::CK_Unknown,
4610 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004611 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004612 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4613 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004614 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00004615
Douglas Gregor44b43212008-12-11 16:49:14 +00004616 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00004617 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004618 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004619 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4620 FD->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00004621
John McCall9d125032010-01-15 18:39:57 +00004622 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4623 CastExpr::CK_Unknown, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004624 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00004625
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004626 llvm::SmallVector<Expr*, 8> BlkExprs;
4627 // Add the implicit argument.
4628 BlkExprs.push_back(BlkCast);
4629 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004630 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004631 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004632 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00004633 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004634 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4635 BlkExprs.size(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00004636 Exp->getType(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004637 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00004638}
4639
4640void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004641 Stmt *BlockCall = SynthesizeBlockCall(Exp, Exp->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004642 ReplaceStmt(Exp, BlockCall);
Steve Naroff54055232008-10-27 17:20:55 +00004643}
4644
Steve Naroff621edce2009-04-29 16:37:50 +00004645// We need to return the rewritten expression to handle cases where the
4646// BlockDeclRefExpr is embedded in another expression being rewritten.
4647// For example:
4648//
4649// int main() {
4650// __block Foo *f;
4651// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00004652//
Steve Naroff621edce2009-04-29 16:37:50 +00004653// void (^myblock)() = ^() {
4654// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4655// i = 77;
4656// };
4657//}
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004658Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00004659 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004660 // for each DeclRefExp where BYREFVAR is name of the variable.
4661 ValueDecl *VD;
4662 bool isArrow = true;
4663 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4664 VD = BDRE->getDecl();
4665 else {
4666 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4667 isArrow = false;
4668 }
4669
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004670 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4671 &Context->Idents.get("__forwarding"),
4672 Context->VoidPtrTy, 0,
4673 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004674 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4675 FD, SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004676 FD->getType());
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004677
4678 const char *Name = VD->getNameAsCString();
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004679 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4680 &Context->Idents.get(Name),
4681 Context->VoidPtrTy, 0,
4682 /*BitWidth=*/0, /*Mutable=*/true);
4683 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004684 DeclRefExp->getType());
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004685
4686
4687
Steve Naroffdf8570d2009-02-02 17:19:26 +00004688 // Need parens to enforce precedence.
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004689 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4690 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004691 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00004692 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00004693}
4694
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004695// Rewrites the imported local variable V with external storage
4696// (static, extern, etc.) as *V
4697//
4698Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4699 ValueDecl *VD = DRE->getDecl();
4700 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4701 if (!ImportedLocalExternalDecls.count(Var))
4702 return DRE;
4703 Expr *Exp = new (Context) UnaryOperator(DRE, UnaryOperator::Deref,
4704 DRE->getType(), DRE->getLocation());
4705 // Need parens to enforce precedence.
4706 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4707 Exp);
4708 ReplaceStmt(DRE, PE);
4709 return PE;
4710}
4711
Steve Naroffb2f9e512008-11-03 23:29:32 +00004712void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4713 SourceLocation LocStart = CE->getLParenLoc();
4714 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00004715
4716 // Need to avoid trying to rewrite synthesized casts.
4717 if (LocStart.isInvalid())
4718 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004719 // Need to avoid trying to rewrite casts contained in macros.
4720 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4721 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004722
Steve Naroff54055232008-10-27 17:20:55 +00004723 const char *startBuf = SM->getCharacterData(LocStart);
4724 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004725 QualType QT = CE->getType();
4726 const Type* TypePtr = QT->getAs<Type>();
4727 if (isa<TypeOfExprType>(TypePtr)) {
4728 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4729 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4730 std::string TypeAsString = "(";
Fariborz Jahanianafad76f2010-02-18 01:20:22 +00004731 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004732 TypeAsString += ")";
Benjamin Kramerd999b372010-02-14 14:14:16 +00004733 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004734 return;
4735 }
Steve Naroff54055232008-10-27 17:20:55 +00004736 // advance the location to startArgList.
4737 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004738
Steve Naroff54055232008-10-27 17:20:55 +00004739 while (*argPtr++ && (argPtr < endBuf)) {
4740 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004741 case '^':
4742 // Replace the '^' with '*'.
4743 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004744 ReplaceText(LocStart, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004745 break;
Steve Naroff54055232008-10-27 17:20:55 +00004746 }
4747 }
4748 return;
4749}
4750
4751void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4752 SourceLocation DeclLoc = FD->getLocation();
4753 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004754
Steve Naroff54055232008-10-27 17:20:55 +00004755 // We have 1 or more arguments that have closure pointers.
4756 const char *startBuf = SM->getCharacterData(DeclLoc);
4757 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004758
Steve Naroff54055232008-10-27 17:20:55 +00004759 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004760
Steve Naroff54055232008-10-27 17:20:55 +00004761 parenCount++;
4762 // advance the location to startArgList.
4763 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4764 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004765
Steve Naroff54055232008-10-27 17:20:55 +00004766 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004767
Steve Naroff54055232008-10-27 17:20:55 +00004768 while (*argPtr++ && parenCount) {
4769 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004770 case '^':
4771 // Replace the '^' with '*'.
4772 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004773 ReplaceText(DeclLoc, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004774 break;
4775 case '(':
4776 parenCount++;
4777 break;
4778 case ')':
4779 parenCount--;
4780 break;
Steve Naroff54055232008-10-27 17:20:55 +00004781 }
4782 }
4783 return;
4784}
4785
4786bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004787 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004788 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004789 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004790 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004791 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004792 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004793 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004794 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004795 }
4796 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004797 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004798 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004799 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004800 return true;
4801 }
4802 return false;
4803}
4804
Ted Kremenek8189cde2009-02-07 01:47:29 +00004805void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4806 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004807 const char *argPtr = strchr(Name, '(');
4808 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004809
Steve Naroff54055232008-10-27 17:20:55 +00004810 LParen = argPtr; // output the start.
4811 argPtr++; // skip past the left paren.
4812 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004813
Steve Naroff54055232008-10-27 17:20:55 +00004814 while (*argPtr && parenCount) {
4815 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004816 case '(': parenCount++; break;
4817 case ')': parenCount--; break;
4818 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00004819 }
4820 if (parenCount) argPtr++;
4821 }
4822 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4823 RParen = argPtr; // output the end
4824}
4825
4826void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4827 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4828 RewriteBlockPointerFunctionArgs(FD);
4829 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004830 }
Steve Naroff54055232008-10-27 17:20:55 +00004831 // Handle Variables and Typedefs.
4832 SourceLocation DeclLoc = ND->getLocation();
4833 QualType DeclT;
4834 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4835 DeclT = VD->getType();
4836 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4837 DeclT = TDD->getUnderlyingType();
4838 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4839 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004840 else
Steve Naroff54055232008-10-27 17:20:55 +00004841 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00004842
Steve Naroff54055232008-10-27 17:20:55 +00004843 const char *startBuf = SM->getCharacterData(DeclLoc);
4844 const char *endBuf = startBuf;
4845 // scan backward (from the decl location) for the end of the previous decl.
4846 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4847 startBuf--;
Mike Stump1eb44332009-09-09 15:08:12 +00004848
Steve Naroff54055232008-10-27 17:20:55 +00004849 // *startBuf != '^' if we are dealing with a pointer to function that
4850 // may take block argument types (which will be handled below).
4851 if (*startBuf == '^') {
4852 // Replace the '^' with '*', computing a negative offset.
4853 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004854 ReplaceText(DeclLoc, 1, "*");
Steve Naroff54055232008-10-27 17:20:55 +00004855 }
4856 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4857 // Replace the '^' with '*' for arguments.
4858 DeclLoc = ND->getLocation();
4859 startBuf = SM->getCharacterData(DeclLoc);
4860 const char *argListBegin, *argListEnd;
4861 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4862 while (argListBegin < argListEnd) {
4863 if (*argListBegin == '^') {
4864 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004865 ReplaceText(CaretLoc, 1, "*");
Steve Naroff54055232008-10-27 17:20:55 +00004866 }
4867 argListBegin++;
4868 }
4869 }
4870 return;
4871}
4872
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004873
4874/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4875/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4876/// struct Block_byref_id_object *src) {
4877/// _Block_object_assign (&_dest->object, _src->object,
4878/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4879/// [|BLOCK_FIELD_IS_WEAK]) // object
4880/// _Block_object_assign(&_dest->object, _src->object,
4881/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4882/// [|BLOCK_FIELD_IS_WEAK]) // block
4883/// }
4884/// And:
4885/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4886/// _Block_object_dispose(_src->object,
4887/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4888/// [|BLOCK_FIELD_IS_WEAK]) // object
4889/// _Block_object_dispose(_src->object,
4890/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4891/// [|BLOCK_FIELD_IS_WEAK]) // block
4892/// }
4893
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004894std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4895 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004896 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00004897 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004898 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004899 CopyDestroyCache.insert(flag);
4900 S = "static void __Block_byref_id_object_copy_";
4901 S += utostr(flag);
4902 S += "(void *dst, void *src) {\n";
4903
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004904 // offset into the object pointer is computed as:
4905 // void * + void* + int + int + void* + void *
4906 unsigned IntSize =
4907 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4908 unsigned VoidPtrSize =
4909 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4910
4911 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
4912 S += " _Block_object_assign((char*)dst + ";
4913 S += utostr(offset);
4914 S += ", *(void * *) ((char*)src + ";
4915 S += utostr(offset);
4916 S += "), ";
4917 S += utostr(flag);
4918 S += ");\n}\n";
4919
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004920 S += "static void __Block_byref_id_object_dispose_";
4921 S += utostr(flag);
4922 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004923 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4924 S += utostr(offset);
4925 S += "), ";
4926 S += utostr(flag);
4927 S += ");\n}\n";
4928 return S;
4929}
4930
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004931/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4932/// the declaration into:
4933/// struct __Block_byref_ND {
4934/// void *__isa; // NULL for everything except __weak pointers
4935/// struct __Block_byref_ND *__forwarding;
4936/// int32_t __flags;
4937/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004938/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4939/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004940/// typex ND;
4941/// };
4942///
4943/// It then replaces declaration of ND variable with:
4944/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4945/// __size=sizeof(struct __Block_byref_ND),
4946/// ND=initializer-if-any};
4947///
4948///
4949void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004950 // Insert declaration for the function in which block literal is
4951 // used.
4952 if (CurFunctionDeclToDeclareForBlock)
4953 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004954 int flag = 0;
4955 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004956 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahaniand64a4f42010-02-26 22:49:11 +00004957 if (DeclLoc.isInvalid())
4958 // If type location is missing, it is because of missing type (a warning).
4959 // Use variable's location which is good for this case.
4960 DeclLoc = ND->getLocation();
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004961 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00004962 SourceLocation X = ND->getLocEnd();
4963 X = SM->getInstantiationLoc(X);
4964 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004965 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004966 std::string ByrefType;
4967 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004968 ByrefType += " {\n";
4969 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004970 RewriteByRefString(ByrefType, Name, ND);
4971 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004972 ByrefType += " int __flags;\n";
4973 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004974 // Add void *__Block_byref_id_object_copy;
4975 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004976 QualType Ty = ND->getType();
4977 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4978 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004979 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4980 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004981 }
4982
4983 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004984 ByrefType += " " + Name + ";\n";
4985 ByrefType += "};\n";
4986 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004987 SourceLocation FunLocStart;
4988 if (CurFunctionDef)
4989 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4990 else {
4991 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4992 FunLocStart = CurMethodDef->getLocStart();
4993 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00004994 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004995 if (Ty.isObjCGCWeak()) {
4996 flag |= BLOCK_FIELD_IS_WEAK;
4997 isa = 1;
4998 }
4999
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005000 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005001 flag = BLOCK_BYREF_CALLER;
5002 QualType Ty = ND->getType();
5003 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5004 if (Ty->isBlockPointerType())
5005 flag |= BLOCK_FIELD_IS_BLOCK;
5006 else
5007 flag |= BLOCK_FIELD_IS_OBJECT;
5008 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005009 if (!HF.empty())
Benjamin Kramerd999b372010-02-14 14:14:16 +00005010 InsertText(FunLocStart, HF);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005011 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005012
5013 // struct __Block_byref_ND ND =
5014 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5015 // initializer-if-any};
5016 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00005017 unsigned flags = 0;
5018 if (HasCopyAndDispose)
5019 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005020 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005021 ByrefType.clear();
5022 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005023 std::string ForwardingCastType("(");
5024 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005025 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005026 ByrefType += " " + Name + " = {(void*)";
5027 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005028 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005029 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005030 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005031 ByrefType += "sizeof(";
5032 RewriteByRefString(ByrefType, Name, ND);
5033 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005034 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005035 ByrefType += ", __Block_byref_id_object_copy_";
5036 ByrefType += utostr(flag);
5037 ByrefType += ", __Block_byref_id_object_dispose_";
5038 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005039 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005040 ByrefType += "};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00005041 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(), ByrefType);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005042 }
5043 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005044 SourceLocation startLoc;
5045 Expr *E = ND->getInit();
5046 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5047 startLoc = ECE->getLParenLoc();
5048 else
5049 startLoc = E->getLocStart();
Fariborz Jahanian791b10d2010-01-05 23:06:29 +00005050 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005051 endBuf = SM->getCharacterData(startLoc);
5052
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005053 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005054 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005055 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005056 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005057 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005058 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005059 ByrefType += "sizeof(";
5060 RewriteByRefString(ByrefType, Name, ND);
5061 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005062 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005063 ByrefType += "__Block_byref_id_object_copy_";
5064 ByrefType += utostr(flag);
5065 ByrefType += ", __Block_byref_id_object_dispose_";
5066 ByrefType += utostr(flag);
5067 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005068 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005069 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroffc5143c52009-12-23 17:24:33 +00005070
5071 // Complete the newly synthesized compound expression by inserting a right
5072 // curly brace before the end of the declaration.
5073 // FIXME: This approach avoids rewriting the initializer expression. It
5074 // also assumes there is only one declarator. For example, the following
5075 // isn't currently supported by this routine (in general):
5076 //
5077 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
5078 //
5079 const char *startBuf = SM->getCharacterData(startLoc);
5080 const char *semiBuf = strchr(startBuf, ';');
5081 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
5082 SourceLocation semiLoc =
5083 startLoc.getFileLocWithOffset(semiBuf-startBuf);
5084
Benjamin Kramerd999b372010-02-14 14:14:16 +00005085 InsertText(semiLoc, "}");
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005086 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00005087 return;
5088}
5089
Mike Stump1eb44332009-09-09 15:08:12 +00005090void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00005091 // Add initializers for any closure decl refs.
5092 GetBlockDeclRefExprs(Exp->getBody());
5093 if (BlockDeclRefs.size()) {
5094 // Unique all "by copy" declarations.
5095 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005096 if (!BlockDeclRefs[i]->isByRef()) {
5097 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5098 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5099 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5100 }
5101 }
Steve Naroff54055232008-10-27 17:20:55 +00005102 // Unique all "by ref" declarations.
5103 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5104 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005105 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5106 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5107 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5108 }
Steve Naroff54055232008-10-27 17:20:55 +00005109 }
5110 // Find any imported blocks...they will need special attention.
5111 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00005112 if (BlockDeclRefs[i]->isByRef() ||
5113 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian5b011b02010-02-26 21:46:27 +00005114 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff54055232008-10-27 17:20:55 +00005115 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff54055232008-10-27 17:20:55 +00005116 }
5117}
5118
Steve Narofffa15fd92008-10-28 20:29:00 +00005119FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
5120 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00005121 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump1eb44332009-09-09 15:08:12 +00005122 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00005123 ID, FType, 0, FunctionDecl::Extern,
5124 FunctionDecl::None, false, false);
Steve Narofffa15fd92008-10-28 20:29:00 +00005125}
5126
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005127Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
5128 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005129 Blocks.push_back(Exp);
5130
5131 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005132
5133 // Add inner imported variables now used in current block.
5134 int countOfInnerDecls = 0;
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005135 if (!InnerBlockDeclRefs.empty()) {
5136 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5137 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
5138 ValueDecl *VD = Exp->getDecl();
5139 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005140 // We need to save the copied-in variables in nested
5141 // blocks because it is needed at the end for some of the API generations.
5142 // See SynthesizeBlockLiterals routine.
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005143 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5144 BlockDeclRefs.push_back(Exp);
5145 BlockByCopyDeclsPtrSet.insert(VD);
5146 BlockByCopyDecls.push_back(VD);
5147 }
5148 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
5149 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5150 BlockDeclRefs.push_back(Exp);
5151 BlockByRefDeclsPtrSet.insert(VD);
5152 BlockByRefDecls.push_back(VD);
5153 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005154 }
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005155 // Find any imported blocks...they will need special attention.
5156 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5157 if (InnerBlockDeclRefs[i]->isByRef() ||
5158 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5159 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5160 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005161 }
5162 InnerDeclRefsCount.push_back(countOfInnerDecls);
5163
Steve Narofffa15fd92008-10-28 20:29:00 +00005164 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00005165
Steve Narofffa15fd92008-10-28 20:29:00 +00005166 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00005167 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00005168 else if (CurMethodDef)
5169 BuildUniqueMethodName(FuncName, CurMethodDef);
5170 else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005171 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00005172
Steve Narofffa15fd92008-10-28 20:29:00 +00005173 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00005174
Steve Narofffa15fd92008-10-28 20:29:00 +00005175 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
5176 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00005177
Steve Narofffa15fd92008-10-28 20:29:00 +00005178 // Get a pointer to the function type so we can cast appropriately.
5179 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
5180
5181 FunctionDecl *FD;
5182 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00005183
Steve Narofffa15fd92008-10-28 20:29:00 +00005184 // Simulate a contructor call...
5185 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005186 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00005187
Steve Narofffa15fd92008-10-28 20:29:00 +00005188 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00005189
Steve Narofffdc03722008-10-29 21:23:59 +00005190 // Initialize the block function.
Steve Narofffa15fd92008-10-28 20:29:00 +00005191 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005192 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
5193 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005194 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5195 CastExpr::CK_Unknown, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00005196 InitExprs.push_back(castExpr);
5197
Steve Naroff01aec112009-12-06 21:14:13 +00005198 // Initialize the block descriptor.
5199 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00005200
Steve Naroff01aec112009-12-06 21:14:13 +00005201 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
5202 &Context->Idents.get(DescData.c_str()),
5203 Context->VoidPtrTy, 0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00005204 VarDecl::Static, VarDecl::None);
Steve Naroff01aec112009-12-06 21:14:13 +00005205 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
5206 new (Context) DeclRefExpr(NewVD,
5207 Context->VoidPtrTy, SourceLocation()),
5208 UnaryOperator::AddrOf,
5209 Context->getPointerType(Context->VoidPtrTy),
5210 SourceLocation());
5211 InitExprs.push_back(DescRefExpr);
5212
Steve Narofffa15fd92008-10-28 20:29:00 +00005213 // Add initializers for any closure decl refs.
5214 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00005215 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00005216 // Output all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005217 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005218 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005219 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00005220 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner8ec03f52008-11-24 03:54:41 +00005221 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005222 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005223 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00005224 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005225 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005226 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5227 CastExpr::CK_Unknown, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00005228 } else {
Chris Lattner8ec03f52008-11-24 03:54:41 +00005229 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005230 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005231 if (HasLocalVariableExternalStorage(*I)) {
5232 QualType QT = (*I)->getType();
5233 QT = Context->getPointerType(QT);
5234 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf, QT,
5235 SourceLocation());
5236 }
5237
Steve Narofffa15fd92008-10-28 20:29:00 +00005238 }
Mike Stump1eb44332009-09-09 15:08:12 +00005239 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005240 }
5241 // Output all "by ref" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005242 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005243 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005244 ValueDecl *ND = (*I);
5245 std::string Name(ND->getNameAsString());
5246 std::string RecName;
5247 RewriteByRefString(RecName, Name, ND);
5248 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5249 + sizeof("struct"));
5250 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
5251 SourceLocation(), II);
5252 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5253 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5254
Chris Lattner8ec03f52008-11-24 03:54:41 +00005255 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005256 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
5257 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00005258 Context->getPointerType(Exp->getType()),
Steve Narofffdc03722008-10-29 21:23:59 +00005259 SourceLocation());
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005260 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CastExpr::CK_Unknown, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00005261 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005262 }
5263 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00005264 if (ImportedBlockDecls.size()) {
5265 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5266 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00005267 unsigned IntSize =
5268 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanianff127882009-12-23 21:52:32 +00005269 Expr *FlagExp = new (Context) IntegerLiteral(llvm::APInt(IntSize, flag),
5270 Context->IntTy, SourceLocation());
5271 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00005272 }
Ted Kremenek668bf912009-02-09 20:51:47 +00005273 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
5274 FType, SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005275 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00005276 Context->getPointerType(NewRep->getType()),
Steve Narofffa15fd92008-10-28 20:29:00 +00005277 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005278 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CastExpr::CK_Unknown,
5279 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00005280 BlockDeclRefs.clear();
5281 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005282 BlockByRefDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005283 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005284 BlockByCopyDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005285 ImportedBlockDecls.clear();
5286 return NewRep;
5287}
5288
5289//===----------------------------------------------------------------------===//
5290// Function Body / Expression rewriting
5291//===----------------------------------------------------------------------===//
5292
Steve Naroffc77a6362008-12-04 16:24:46 +00005293// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
5294// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
5295// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
5296// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
5297// Since the rewriter isn't capable of rewriting rewritten code, it's important
5298// we get this right.
5299void RewriteObjC::CollectPropertySetters(Stmt *S) {
5300 // Perform a bottom up traversal of all children.
5301 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5302 CI != E; ++CI)
5303 if (*CI)
5304 CollectPropertySetters(*CI);
5305
5306 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
5307 if (BinOp->isAssignmentOp()) {
5308 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
5309 PropSetters[PRE] = BinOp;
5310 }
5311 }
5312}
5313
Steve Narofffa15fd92008-10-28 20:29:00 +00005314Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00005315 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005316 isa<DoStmt>(S) || isa<ForStmt>(S))
5317 Stmts.push_back(S);
5318 else if (isa<ObjCForCollectionStmt>(S)) {
5319 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00005320 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00005321 }
Mike Stump1eb44332009-09-09 15:08:12 +00005322
Steve Narofffa15fd92008-10-28 20:29:00 +00005323 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005324
Steve Narofffa15fd92008-10-28 20:29:00 +00005325 // Perform a bottom up rewrite of all children.
5326 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5327 CI != E; ++CI)
5328 if (*CI) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005329 Stmt *newStmt;
5330 Stmt *S = (*CI);
5331 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5332 Expr *OldBase = IvarRefExpr->getBase();
5333 bool replaced = false;
5334 newStmt = RewriteObjCNestedIvarRefExpr(S, replaced);
5335 if (replaced) {
5336 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
5337 ReplaceStmt(OldBase, IRE->getBase());
5338 else
5339 ReplaceStmt(S, newStmt);
5340 }
5341 }
5342 else
5343 newStmt = RewriteFunctionBodyOrGlobalInitializer(S);
Mike Stump1eb44332009-09-09 15:08:12 +00005344 if (newStmt)
Steve Narofffa15fd92008-10-28 20:29:00 +00005345 *CI = newStmt;
5346 }
Mike Stump1eb44332009-09-09 15:08:12 +00005347
Steve Narofffa15fd92008-10-28 20:29:00 +00005348 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005349 llvm::SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005350 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5351 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005352 ImportedLocalExternalDecls.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005353 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005354 InnerBlockDeclRefs, InnerContexts);
Steve Narofffa15fd92008-10-28 20:29:00 +00005355 // Rewrite the block body in place.
5356 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005357 ImportedLocalExternalDecls.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005358 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenek6a12a142010-01-07 18:00:35 +00005359 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005360 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00005361
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005362 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5363
Steve Narofffa15fd92008-10-28 20:29:00 +00005364 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005365 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00005366 return blockTranscribed;
5367 }
5368 // Handle specific things.
5369 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5370 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00005371
Steve Naroffc77a6362008-12-04 16:24:46 +00005372 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
5373 BinaryOperator *BinOp = PropSetters[PropRefExpr];
5374 if (BinOp) {
5375 // Because the rewriter doesn't allow us to rewrite rewritten code,
5376 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00005377 DisableReplaceStmt = true;
5378 // Save the source range. Even if we disable the replacement, the
5379 // rewritten node will have been inserted into the tree. If the synthesized
5380 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump1eb44332009-09-09 15:08:12 +00005381 // self.errorHandler = handler ? handler :
Steve Naroffb619d952008-12-09 12:56:34 +00005382 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5383 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00005384 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroffb619d952008-12-09 12:56:34 +00005385 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00005386 //
5387 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
5388 // we changed the RHS of BinOp, the rewriter would fail (since it needs
5389 // to see the original expression). Consider this example:
5390 //
5391 // Foo *obj1, *obj2;
5392 //
5393 // obj1.i = [obj2 rrrr];
5394 //
5395 // 'BinOp' for the previous expression looks like:
5396 //
5397 // (BinaryOperator 0x231ccf0 'int' '='
5398 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5399 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5400 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5401 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5402 //
5403 // 'newStmt' represents the rewritten message expression. For example:
5404 //
5405 // (CallExpr 0x231d300 'id':'struct objc_object *'
5406 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5407 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5408 // (CStyleCastExpr 0x231d220 'void *'
5409 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5410 //
5411 // Note that 'newStmt' is passed to RewritePropertySetter so that it
5412 // can be used as the setter argument. ReplaceStmt() will still 'see'
5413 // the original RHS (since we haven't altered BinOp).
5414 //
Mike Stump1eb44332009-09-09 15:08:12 +00005415 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff4c3580e2008-12-04 23:50:32 +00005416 // node. As a result, we now leak the original AST nodes.
5417 //
Steve Naroffb619d952008-12-09 12:56:34 +00005418 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00005419 } else {
5420 return RewritePropertyGetter(PropRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00005421 }
5422 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005423 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5424 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00005425
Steve Narofffa15fd92008-10-28 20:29:00 +00005426 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5427 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00005428
Steve Narofffa15fd92008-10-28 20:29:00 +00005429 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00005430#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00005431 // Before we rewrite it, put the original message expression in a comment.
5432 SourceLocation startLoc = MessExpr->getLocStart();
5433 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00005434
Steve Narofffa15fd92008-10-28 20:29:00 +00005435 const char *startBuf = SM->getCharacterData(startLoc);
5436 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00005437
Steve Narofffa15fd92008-10-28 20:29:00 +00005438 std::string messString;
5439 messString += "// ";
5440 messString.append(startBuf, endBuf-startBuf+1);
5441 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00005442
5443 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00005444 // InsertText(clang::SourceLocation, char const*, unsigned int).
5445 // InsertText(startLoc, messString.c_str(), messString.size());
5446 // Tried this, but it didn't work either...
5447 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00005448#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00005449 return RewriteMessageExpr(MessExpr);
5450 }
Mike Stump1eb44332009-09-09 15:08:12 +00005451
Steve Narofffa15fd92008-10-28 20:29:00 +00005452 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5453 return RewriteObjCTryStmt(StmtTry);
5454
5455 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5456 return RewriteObjCSynchronizedStmt(StmtTry);
5457
5458 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5459 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00005460
Steve Narofffa15fd92008-10-28 20:29:00 +00005461 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5462 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00005463
5464 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00005465 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00005466 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00005467 OrigStmtRange.getEnd());
5468 if (BreakStmt *StmtBreakStmt =
5469 dyn_cast<BreakStmt>(S))
5470 return RewriteBreakStmt(StmtBreakStmt);
5471 if (ContinueStmt *StmtContinueStmt =
5472 dyn_cast<ContinueStmt>(S))
5473 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00005474
5475 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00005476 // and cast exprs.
5477 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5478 // FIXME: What we're doing here is modifying the type-specifier that
5479 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00005480 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00005481 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5482 // the context of an ObjCForCollectionStmt. For example:
5483 // NSArray *someArray;
5484 // for (id <FooProtocol> index in someArray) ;
5485 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5486 // and it depends on the original text locations/positions.
Benjamin Kramerb2041de2009-12-05 22:16:51 +00005487 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroff3d7e7862009-12-05 15:55:59 +00005488 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00005489
Steve Narofffa15fd92008-10-28 20:29:00 +00005490 // Blocks rewrite rules.
5491 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5492 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00005493 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00005494 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005495 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005496 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00005497 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005498 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005499 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005500 if (VD->hasAttr<BlocksAttr>()) {
5501 static unsigned uniqueByrefDeclCount = 0;
5502 assert(!BlockByRefDeclNo.count(ND) &&
5503 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5504 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005505 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005506 }
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005507 else
5508 RewriteTypeOfDecl(VD);
5509 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005510 }
5511 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005512 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005513 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005514 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005515 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5516 }
5517 }
5518 }
Mike Stump1eb44332009-09-09 15:08:12 +00005519
Steve Narofffa15fd92008-10-28 20:29:00 +00005520 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5521 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00005522
5523 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005524 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5525 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00005526 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5527 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005528 && "Statement stack mismatch");
5529 Stmts.pop_back();
5530 }
5531 // Handle blocks rewriting.
5532 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5533 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00005534 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00005535 }
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005536 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5537 ValueDecl *VD = DRE->getDecl();
5538 if (VD->hasAttr<BlocksAttr>())
5539 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005540 if (HasLocalVariableExternalStorage(VD))
5541 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005542 }
5543
Steve Narofffa15fd92008-10-28 20:29:00 +00005544 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005545 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00005546 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005547 ReplaceStmt(S, BlockCall);
5548 return BlockCall;
5549 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005550 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00005551 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005552 RewriteCastExpr(CE);
5553 }
5554#if 0
5555 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00005556 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00005557 // Get the new text.
5558 std::string SStr;
5559 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00005560 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00005561 const std::string &Str = Buf.str();
5562
5563 printf("CAST = %s\n", &Str[0]);
5564 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5565 delete S;
5566 return Replacement;
5567 }
5568#endif
5569 // Return this stmt unmodified.
5570 return S;
5571}
5572
Steve Naroff3d7e7862009-12-05 15:55:59 +00005573void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5574 for (RecordDecl::field_iterator i = RD->field_begin(),
5575 e = RD->field_end(); i != e; ++i) {
5576 FieldDecl *FD = *i;
5577 if (isTopLevelBlockPointerType(FD->getType()))
5578 RewriteBlockPointerDecl(FD);
5579 if (FD->getType()->isObjCQualifiedIdType() ||
5580 FD->getType()->isObjCQualifiedInterfaceType())
5581 RewriteObjCQualifiedInterfaceTypes(FD);
5582 }
5583}
5584
Steve Narofffa15fd92008-10-28 20:29:00 +00005585/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5586/// main file of the input.
5587void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5588 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00005589 if (FD->isOverloadedOperator())
5590 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005591
Steve Narofffa15fd92008-10-28 20:29:00 +00005592 // Since function prototypes don't have ParmDecl's, we check the function
5593 // prototype. This enables us to rewrite function declarations and
5594 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00005595 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005596
Sebastian Redld3a413d2009-04-26 20:35:05 +00005597 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005598 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005599 CurFunctionDef = FD;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005600 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005601 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005602 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005603 Body =
5604 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5605 FD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005606 CurrentBody = 0;
5607 if (PropParentMap) {
5608 delete PropParentMap;
5609 PropParentMap = 0;
5610 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005611 // This synthesizes and inserts the block "impl" struct, invoke function,
5612 // and any copy/dispose helper functions.
5613 InsertBlockLiteralsWithinFunction(FD);
5614 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005615 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005616 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005617 return;
5618 }
5619 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005620 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005621 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005622 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005623 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005624 Body =
5625 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5626 MD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005627 CurrentBody = 0;
5628 if (PropParentMap) {
5629 delete PropParentMap;
5630 PropParentMap = 0;
5631 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005632 InsertBlockLiteralsWithinMethod(MD);
5633 CurMethodDef = 0;
5634 }
5635 }
5636 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5637 ClassImplementation.push_back(CI);
5638 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5639 CategoryImplementation.push_back(CI);
5640 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5641 RewriteForwardClassDecl(CD);
5642 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5643 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005644 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005645 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005646 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005647 CheckFunctionPointerDecl(VD->getType(), VD);
5648 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00005649 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005650 RewriteCastExpr(CE);
5651 }
5652 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00005653 } else if (VD->getType()->isRecordType()) {
5654 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5655 if (RD->isDefinition())
5656 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005657 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005658 if (VD->getInit()) {
5659 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005660 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005661 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005662 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005663 CurrentBody = 0;
5664 if (PropParentMap) {
5665 delete PropParentMap;
5666 PropParentMap = 0;
5667 }
Mike Stump1eb44332009-09-09 15:08:12 +00005668 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00005669 VD->getNameAsCString());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005670 GlobalVarDecl = 0;
5671
5672 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00005673 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005674 RewriteCastExpr(CE);
5675 }
5676 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005677 return;
5678 }
5679 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005680 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005681 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005682 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005683 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5684 return;
5685 }
5686 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroff3d7e7862009-12-05 15:55:59 +00005687 if (RD->isDefinition())
5688 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005689 return;
5690 }
5691 // Nothing yet.
5692}
5693
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00005694void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005695 if (Diags.hasErrorOccurred())
5696 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005697
Steve Narofffa15fd92008-10-28 20:29:00 +00005698 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00005699
Steve Naroff621edce2009-04-29 16:37:50 +00005700 // Here's a great place to add any extra declarations that may be needed.
5701 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00005702 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00005703 E = ProtocolExprDecls.end(); I != E; ++I)
5704 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5705
Benjamin Kramerd999b372010-02-14 14:14:16 +00005706 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff0aab7962008-11-14 14:10:01 +00005707 if (ClassImplementation.size() || CategoryImplementation.size())
5708 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00005709
Steve Narofffa15fd92008-10-28 20:29:00 +00005710 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5711 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00005712 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00005713 Rewrite.getRewriteBufferFor(MainFileID)) {
5714 //printf("Changed:\n");
5715 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5716 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +00005717 llvm::errs() << "No changes\n";
Steve Narofffa15fd92008-10-28 20:29:00 +00005718 }
Steve Narofface66252008-11-13 20:07:04 +00005719
Steve Naroff621edce2009-04-29 16:37:50 +00005720 if (ClassImplementation.size() || CategoryImplementation.size() ||
5721 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00005722 // Rewrite Objective-c meta data*
5723 std::string ResultStr;
5724 SynthesizeMetaDataIntoBuffer(ResultStr);
5725 // Emit metadata.
5726 *OutFile << ResultStr;
5727 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005728 OutFile->flush();
5729}