blob: 13de937141afe4d45d4669d9eb581113fe63b1b1 [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"
Chris Lattner77cd2a02007-10-11 00:43:27 +000029using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000030using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000031
Chris Lattner77cd2a02007-10-11 00:43:27 +000032namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000033 class RewriteObjC : public ASTConsumer {
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000034 enum {
35 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
36 block, ... */
37 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
38 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
39 __block variable */
40 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
41 helpers */
42 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
43 support routines */
44 BLOCK_BYREF_CURRENT_MAX = 256
45 };
46
47 enum {
48 BLOCK_NEEDS_FREE = (1 << 24),
49 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
50 BLOCK_HAS_CXX_OBJ = (1 << 26),
51 BLOCK_IS_GC = (1 << 27),
52 BLOCK_IS_GLOBAL = (1 << 28),
53 BLOCK_HAS_DESCRIPTOR = (1 << 29)
54 };
55
Chris Lattner2c64b7b2007-10-16 21:07:07 +000056 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000057 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000058 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000059 unsigned RewriteFailedDiag;
Steve Naroff8c565152008-12-05 17:03:39 +000060 unsigned TryFinallyContainsReturnDiag;
Mike Stump1eb44332009-09-09 15:08:12 +000061
Chris Lattner01c57482007-10-17 22:35:30 +000062 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000063 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000064 TranslationUnitDecl *TUDecl;
Chris Lattner2b2453a2009-01-17 06:22:33 +000065 FileID MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000066 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000067 SourceLocation LastIncLoc;
Mike Stump1eb44332009-09-09 15:08:12 +000068
Ted Kremeneka526c5c2008-01-07 19:49:32 +000069 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
70 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
71 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +000072 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000073 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
74 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000075 llvm::SmallVector<Stmt *, 32> Stmts;
76 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroff621edce2009-04-29 16:37:50 +000077 // Remember all the @protocol(<expr>) expressions.
78 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +000079
80 llvm::DenseSet<uint64_t> CopyDestroyCache;
81
Steve Naroffd82a9ab2008-03-15 00:55:56 +000082 unsigned NumObjCStringLiterals;
Mike Stump1eb44332009-09-09 15:08:12 +000083
Steve Naroffebf2b562007-10-23 23:50:29 +000084 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000085 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000086 FunctionDecl *MsgSendStretFunctionDecl;
87 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000088 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000089 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000090 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000091 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000092 FunctionDecl *CFStringFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000093 FunctionDecl *SuperContructorFunctionDecl;
Mike Stump1eb44332009-09-09 15:08:12 +000094
Steve Naroffbeaf2992007-11-03 11:27:19 +000095 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000096 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000097 RecordDecl *NSStringRecord;
Mike Stump1eb44332009-09-09 15:08:12 +000098
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000099 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000100 int BcLabelCount;
Mike Stump1eb44332009-09-09 15:08:12 +0000101
Steve Naroff874e2322007-11-15 10:28:18 +0000102 // Needed for super.
Steve Naroff54055232008-10-27 17:20:55 +0000103 ObjCMethodDecl *CurMethodDef;
Steve Naroff874e2322007-11-15 10:28:18 +0000104 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000105 RecordDecl *ConstantStringDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000106
Steve Naroff621edce2009-04-29 16:37:50 +0000107 TypeDecl *ProtocolTypeDecl;
108 QualType getProtocolType();
Mike Stump1eb44332009-09-09 15:08:12 +0000109
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000110 // Needed for header files being rewritten
111 bool IsHeader;
Mike Stump1eb44332009-09-09 15:08:12 +0000112
Steve Naroffa7b402d2008-03-28 22:26:09 +0000113 std::string InFileName;
Eli Friedman66d6f042009-05-18 22:20:00 +0000114 llvm::raw_ostream* OutFile;
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000115
116 bool SilenceRewriteMacroWarning;
117
Steve Naroffba92b2e2008-03-27 22:29:16 +0000118 std::string Preamble;
Steve Naroff54055232008-10-27 17:20:55 +0000119
120 // Block expressions.
121 llvm::SmallVector<BlockExpr *, 32> Blocks;
122 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
123 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Mike Stump1eb44332009-09-09 15:08:12 +0000124
Steve Naroff54055232008-10-27 17:20:55 +0000125 // Block related declarations.
126 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
127 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
128 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
129
130 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
131
Steve Naroffc77a6362008-12-04 16:24:46 +0000132 // This maps a property to it's assignment statement.
133 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Naroff8599e7a2008-12-08 16:43:47 +0000134 // This maps a property to it's synthesied message expression.
135 // This allows us to rewrite chained getters (e.g. o.a.b.c).
136 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
Mike Stump1eb44332009-09-09 15:08:12 +0000137
Steve Naroff4c3580e2008-12-04 23:50:32 +0000138 // This maps an original source AST to it's rewritten form. This allows
139 // us to avoid rewriting the same node twice (which is very uncommon).
140 // This is needed to support some of the exotic property rewriting.
141 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000142
Steve Naroff54055232008-10-27 17:20:55 +0000143 FunctionDecl *CurFunctionDef;
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000144 VarDecl *GlobalVarDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000145
Steve Naroffb619d952008-12-09 12:56:34 +0000146 bool DisableReplaceStmt;
Mike Stump1eb44332009-09-09 15:08:12 +0000147
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000148 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000149 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000150 virtual void Initialize(ASTContext &context);
151
Chris Lattnerf04da132007-10-24 17:06:59 +0000152 // Top Level Driver code.
Chris Lattner682bf922009-03-29 16:50:03 +0000153 virtual void HandleTopLevelDecl(DeclGroupRef D) {
154 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
155 HandleTopLevelSingleDecl(*I);
156 }
157 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000158 void HandleDeclInMainFile(Decl *D);
Eli Friedman66d6f042009-05-18 22:20:00 +0000159 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000160 Diagnostic &D, const LangOptions &LOpts,
161 bool silenceMacroWarn);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000162
163 ~RewriteObjC() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000164
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000165 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump1eb44332009-09-09 15:08:12 +0000166
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000167 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000168 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump1eb44332009-09-09 15:08:12 +0000169
Steve Naroff4c3580e2008-12-04 23:50:32 +0000170 if (ReplacingStmt)
171 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000172
Steve Naroffb619d952008-12-09 12:56:34 +0000173 if (DisableReplaceStmt)
174 return; // Used when rewriting the assignment of a property setter.
175
Steve Naroff4c3580e2008-12-04 23:50:32 +0000176 // If replacement succeeded or warning disabled return with no warning.
177 if (!Rewrite.ReplaceStmt(Old, New)) {
178 ReplacedNodes[Old] = New;
179 return;
180 }
181 if (SilenceRewriteMacroWarning)
182 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000183 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
184 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000185 }
Steve Naroffb619d952008-12-09 12:56:34 +0000186
187 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
188 // Measaure the old text.
189 int Size = Rewrite.getRangeSize(SrcRange);
190 if (Size == -1) {
191 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
192 << Old->getSourceRange();
193 return;
194 }
195 // Get the new text.
196 std::string SStr;
197 llvm::raw_string_ostream S(SStr);
Chris Lattnere4f21422009-06-30 01:26:17 +0000198 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroffb619d952008-12-09 12:56:34 +0000199 const std::string &Str = S.str();
200
201 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000202 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroffb619d952008-12-09 12:56:34 +0000203 ReplacedNodes[Old] = New;
204 return;
205 }
206 if (SilenceRewriteMacroWarning)
207 return;
208 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
209 << Old->getSourceRange();
210 }
211
Steve Naroffba92b2e2008-03-27 22:29:16 +0000212 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
213 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000214 // If insertion succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000215 if (!Rewrite.InsertText(Loc, llvm::StringRef(StrData, StrLen),
216 InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000217 SilenceRewriteMacroWarning)
218 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000219
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000220 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
221 }
Mike Stump1eb44332009-09-09 15:08:12 +0000222
Chris Lattneraadaf782008-01-31 19:51:04 +0000223 void RemoveText(SourceLocation Loc, unsigned StrLen) {
224 // If removal succeeded or warning disabled return with no warning.
225 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
226 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000227
Chris Lattneraadaf782008-01-31 19:51:04 +0000228 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
229 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000230
Chris Lattneraadaf782008-01-31 19:51:04 +0000231 void ReplaceText(SourceLocation Start, unsigned OrigLength,
232 const char *NewStr, unsigned NewLength) {
233 // If removal succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000234 if (!Rewrite.ReplaceText(Start, OrigLength,
235 llvm::StringRef(NewStr, NewLength)) ||
Chris Lattneraadaf782008-01-31 19:51:04 +0000236 SilenceRewriteMacroWarning)
237 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000238
Chris Lattneraadaf782008-01-31 19:51:04 +0000239 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
240 }
Mike Stump1eb44332009-09-09 15:08:12 +0000241
Chris Lattnerf04da132007-10-24 17:06:59 +0000242 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000243 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000244 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000245 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000246 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffa0876e82008-12-02 17:36:43 +0000247 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
248 ObjCImplementationDecl *IMD,
249 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000250 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000251 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000252 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
253 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
254 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
255 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
256 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000257 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000258 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000259 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff4f95b752008-07-29 18:15:38 +0000260 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000261 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000262 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000263 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000264 QualType getConstantStringStructType();
Steve Naroffbaf58c32008-05-31 14:15:04 +0000265 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump1eb44332009-09-09 15:08:12 +0000266
Chris Lattnerf04da132007-10-24 17:06:59 +0000267 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000268 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroffc77a6362008-12-04 16:24:46 +0000269 void CollectPropertySetters(Stmt *S);
Mike Stump1eb44332009-09-09 15:08:12 +0000270
Steve Naroff8599e7a2008-12-08 16:43:47 +0000271 Stmt *CurrentBody;
272 ParentMap *PropParentMap; // created lazily.
Mike Stump1eb44332009-09-09 15:08:12 +0000273
Chris Lattnere64b7772007-10-24 16:57:36 +0000274 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000275 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroffc77a6362008-12-04 16:24:46 +0000276 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Mike Stump1eb44332009-09-09 15:08:12 +0000277 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroffb619d952008-12-09 12:56:34 +0000278 SourceRange SrcRange);
Steve Naroffb42f8412007-11-05 14:50:49 +0000279 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000280 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000281 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000282 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffb85e77a2009-12-05 21:43:12 +0000283 void WarnAboutReturnGotoStmts(Stmt *S);
284 void HasReturnStmts(Stmt *S, bool &hasReturns);
285 void RewriteTryReturnStmts(Stmt *S);
286 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000287 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000288 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000289 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
290 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
291 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000292 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
293 SourceLocation OrigEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000294 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Steve Naroff934f2762007-10-24 22:48:43 +0000295 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000296 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000297 Stmt *RewriteBreakStmt(BreakStmt *S);
298 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000299 void SynthCountByEnumWithState(std::string &buf);
Mike Stump1eb44332009-09-09 15:08:12 +0000300
Steve Naroff09b266e2007-10-30 23:14:51 +0000301 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000302 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000303 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000304 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000305 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000306 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000307 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000308 void SynthSelGetUidFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000309 void SynthSuperContructorFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000310
Chris Lattnerf04da132007-10-24 17:06:59 +0000311 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000312 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000313 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000314
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000315 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000316 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000317
Douglas Gregor653f1b12009-04-23 01:02:12 +0000318 template<typename MethodIterator>
319 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
320 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000321 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000322 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000323 const char *ClassName,
324 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000325
Steve Naroff621edce2009-04-29 16:37:50 +0000326 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
327 const char *prefix,
328 const char *ClassName,
329 std::string &Result);
330 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Mike Stump1eb44332009-09-09 15:08:12 +0000331 const char *prefix,
Steve Naroff621edce2009-04-29 16:37:50 +0000332 const char *ClassName,
333 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000334 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000335 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000336 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
337 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000338 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000339 void RewriteImplementations();
340 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000341
Steve Naroff54055232008-10-27 17:20:55 +0000342 // Block rewriting.
Mike Stump1eb44332009-09-09 15:08:12 +0000343 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff54055232008-10-27 17:20:55 +0000344 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump1eb44332009-09-09 15:08:12 +0000345
Steve Naroff54055232008-10-27 17:20:55 +0000346 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
347 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump1eb44332009-09-09 15:08:12 +0000348
349 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000350 void RewriteBlockCall(CallExpr *Exp);
351 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000352 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +0000353 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +0000354 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Steve Naroff54055232008-10-27 17:20:55 +0000355 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000356
357 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Steve Naroff54055232008-10-27 17:20:55 +0000358 const char *funcName, std::string Tag);
Mike Stump1eb44332009-09-09 15:08:12 +0000359 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Steve Naroff54055232008-10-27 17:20:55 +0000360 const char *funcName, std::string Tag);
Steve Naroff01aec112009-12-06 21:14:13 +0000361 std::string SynthesizeBlockImpl(BlockExpr *CE,
362 std::string Tag, std::string Desc);
363 std::string SynthesizeBlockDescriptor(std::string DescTag,
364 std::string ImplTag,
365 int i, const char *funcName,
366 unsigned hasCopy);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +0000367 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff54055232008-10-27 17:20:55 +0000368 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
369 const char *FunName);
Steve Naroff3d7e7862009-12-05 15:55:59 +0000370 void RewriteRecordBody(RecordDecl *RD);
Mike Stump1eb44332009-09-09 15:08:12 +0000371
Steve Naroff54055232008-10-27 17:20:55 +0000372 void CollectBlockDeclRefInfo(BlockExpr *Exp);
373 void GetBlockCallExprs(Stmt *S);
374 void GetBlockDeclRefExprs(Stmt *S);
Mike Stump1eb44332009-09-09 15:08:12 +0000375
Steve Naroff54055232008-10-27 17:20:55 +0000376 // We avoid calling Type::isBlockPointerType(), since it operates on the
377 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000378 bool isTopLevelBlockPointerType(QualType T) {
379 return isa<BlockPointerType>(T);
380 }
Mike Stump1eb44332009-09-09 15:08:12 +0000381
Steve Naroff54055232008-10-27 17:20:55 +0000382 // FIXME: This predicate seems like it would be useful to add to ASTContext.
383 bool isObjCType(QualType T) {
384 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
385 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000386
Steve Naroff54055232008-10-27 17:20:55 +0000387 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000388
Steve Naroff54055232008-10-27 17:20:55 +0000389 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
390 OCT == Context->getCanonicalType(Context->getObjCClassType()))
391 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000392
Ted Kremenek6217b802009-07-29 21:53:49 +0000393 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000394 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000395 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000396 return true;
397 }
398 return false;
399 }
400 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000401 void GetExtentOfArgList(const char *Name, const char *&LParen,
402 const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000403 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump1eb44332009-09-09 15:08:12 +0000404
Steve Narofffa15fd92008-10-28 20:29:00 +0000405 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000406 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Mike Stump1eb44332009-09-09 15:08:12 +0000407
Steve Naroff621edce2009-04-29 16:37:50 +0000408 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000409 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000410 if (From[i] == '"')
411 To += "\\\"";
412 else
413 To += From[i];
414 }
415 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000416 };
417}
418
Mike Stump1eb44332009-09-09 15:08:12 +0000419void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
420 NamedDecl *D) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000421 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000422 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000423 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000424 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000425 // All the args are checked/rewritten. Don't call twice!
426 RewriteBlockPointerDecl(D);
427 break;
428 }
429 }
430}
431
432void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000433 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000434 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000435 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000436}
437
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000438static bool IsHeaderFile(const std::string &Filename) {
439 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000440
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000441 if (DotPos == std::string::npos) {
442 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000443 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000444 }
Mike Stump1eb44332009-09-09 15:08:12 +0000445
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000446 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
447 // C header: .h
448 // C++ header: .hh or .H;
449 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000450}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000451
Eli Friedman66d6f042009-05-18 22:20:00 +0000452RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000453 Diagnostic &D, const LangOptions &LOpts,
454 bool silenceMacroWarn)
455 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
456 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000457 IsHeader = IsHeaderFile(inFile);
Mike Stump1eb44332009-09-09 15:08:12 +0000458 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000459 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump1eb44332009-09-09 15:08:12 +0000460 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000461 "rewriter doesn't support user-specified control flow semantics "
462 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000463}
464
Eli Friedmanbce831b2009-05-18 22:29:17 +0000465ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
466 llvm::raw_ostream* OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000467 Diagnostic &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000468 const LangOptions &LOpts,
469 bool SilenceRewriteMacroWarning) {
470 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000471}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000472
Steve Naroffb29b4272008-04-14 22:03:09 +0000473void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000474 Context = &context;
475 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000476 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000477 MsgSendFunctionDecl = 0;
478 MsgSendSuperFunctionDecl = 0;
479 MsgSendStretFunctionDecl = 0;
480 MsgSendSuperStretFunctionDecl = 0;
481 MsgSendFpretFunctionDecl = 0;
482 GetClassFunctionDecl = 0;
483 GetMetaClassFunctionDecl = 0;
484 SelGetUidFunctionDecl = 0;
485 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000486 ConstantStringClassReference = 0;
487 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000488 CurMethodDef = 0;
489 CurFunctionDef = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000490 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000491 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000492 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000493 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000494 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000495 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000496 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000497 PropParentMap = 0;
498 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000499 DisableReplaceStmt = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000500
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000501 // Get the ID and start/end of the main file.
502 MainFileID = SM->getMainFileID();
503 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
504 MainFileStart = MainBuf->getBufferStart();
505 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000506
Chris Lattner2c78b872009-04-14 23:22:57 +0000507 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump1eb44332009-09-09 15:08:12 +0000508
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000509 // declaring objc_selector outside the parameter list removes a silly
510 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000511 if (IsHeader)
Steve Naroff62c26322009-02-03 20:39:18 +0000512 Preamble = "#pragma once\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000513 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000514 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000515 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000516 if (LangOpts.Microsoft) {
517 // Add a constructor for creating temporary objects.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000518 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
519 ": ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000520 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000521 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000522 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000523 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
524 Preamble += "typedef struct objc_object Protocol;\n";
525 Preamble += "#define _REWRITER_typedef_Protocol\n";
526 Preamble += "#endif\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000527 if (LangOpts.Microsoft) {
528 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
529 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
530 } else
531 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
532 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000533 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000534 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000535 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000536 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000537 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000538 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000539 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000540 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000541 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000542 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000543 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000544 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000545 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000546 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
547 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
548 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
549 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
550 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000551 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000552 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000553 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
554 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
555 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000556 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
557 Preamble += "struct __objcFastEnumerationState {\n\t";
558 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000559 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000560 Preamble += "unsigned long *mutationsPtr;\n\t";
561 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000562 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000563 Preamble += "#define __FASTENUMERATIONSTATE\n";
564 Preamble += "#endif\n";
565 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
566 Preamble += "struct __NSConstantStringImpl {\n";
567 Preamble += " int *isa;\n";
568 Preamble += " int flags;\n";
569 Preamble += " char *str;\n";
570 Preamble += " long length;\n";
571 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000572 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
573 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
574 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000575 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000576 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000577 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
578 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000579 // Blocks preamble.
580 Preamble += "#ifndef BLOCK_IMPL\n";
581 Preamble += "#define BLOCK_IMPL\n";
582 Preamble += "struct __block_impl {\n";
583 Preamble += " void *isa;\n";
584 Preamble += " int Flags;\n";
Steve Naroff01aec112009-12-06 21:14:13 +0000585 Preamble += " int Reserved;\n";
Steve Naroff54055232008-10-27 17:20:55 +0000586 Preamble += " void *FuncPtr;\n";
587 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000588 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroffc9c1e9c2009-12-06 01:52:22 +0000589 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000590 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_assign(void *, const void *, const int);\n";
591 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
592 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
593 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
594 Preamble += "#else\n";
Steve Naroffcd826372010-01-05 18:09:31 +0000595 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
596 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000597 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
598 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
599 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000600 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000601 if (LangOpts.Microsoft) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000602 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
603 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000604 Preamble += "#define __attribute__(X)\n";
605 }
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000606 else {
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000607 Preamble += "#define __block\n";
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000608 Preamble += "#define __weak\n";
609 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000610}
611
612
Chris Lattnerf04da132007-10-24 17:06:59 +0000613//===----------------------------------------------------------------------===//
614// Top Level Driver Code
615//===----------------------------------------------------------------------===//
616
Chris Lattner682bf922009-03-29 16:50:03 +0000617void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000618 // Two cases: either the decl could be in the main file, or it could be in a
619 // #included file. If the former, rewrite it now. If the later, check to see
620 // if we rewrote the #include/#import.
621 SourceLocation Loc = D->getLocation();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000622 Loc = SM->getInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000623
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000624 // If this is for a builtin, ignore it.
625 if (Loc.isInvalid()) return;
626
Steve Naroffebf2b562007-10-23 23:50:29 +0000627 // Look for built-in declarations that we need to refer during the rewrite.
628 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000629 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000630 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000631 // declared in <Foundation/NSString.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +0000632 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000633 ConstantStringClassReference = FVD;
634 return;
635 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000636 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000637 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000638 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000639 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000640 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000641 RewriteProtocolDecl(PD);
Mike Stump1eb44332009-09-09 15:08:12 +0000642 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000643 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000644 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000645 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
646 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000647 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
648 DIEnd = LSD->decls_end();
Douglas Gregord0434102009-01-09 00:49:46 +0000649 DI != DIEnd; ++DI)
Chris Lattner682bf922009-03-29 16:50:03 +0000650 HandleTopLevelSingleDecl(*DI);
Steve Naroffebf2b562007-10-23 23:50:29 +0000651 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000652 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000653 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000654 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000655}
656
Chris Lattnerf04da132007-10-24 17:06:59 +0000657//===----------------------------------------------------------------------===//
658// Syntactic (non-AST) Rewriting Code
659//===----------------------------------------------------------------------===//
660
Steve Naroffb29b4272008-04-14 22:03:09 +0000661void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000662 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000663 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
664 const char *MainBufStart = MainBuf.first;
665 const char *MainBufEnd = MainBuf.second;
666 size_t ImportLen = strlen("import");
667 size_t IncludeLen = strlen("include");
Mike Stump1eb44332009-09-09 15:08:12 +0000668
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000669 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000670 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
671 if (*BufPtr == '#') {
672 if (++BufPtr == MainBufEnd)
673 return;
674 while (*BufPtr == ' ' || *BufPtr == '\t')
675 if (++BufPtr == MainBufEnd)
676 return;
677 if (!strncmp(BufPtr, "import", ImportLen)) {
678 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000679 SourceLocation ImportLoc =
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000680 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000681 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000682 BufPtr += ImportLen;
683 }
684 }
685 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000686}
687
Steve Naroffb29b4272008-04-14 22:03:09 +0000688void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000689 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
690 const char *MainBufStart = MainBuf.first;
691 const char *MainBufEnd = MainBuf.second;
Mike Stump1eb44332009-09-09 15:08:12 +0000692
Chris Lattnerf04da132007-10-24 17:06:59 +0000693 // Loop over the whole file, looking for tabs.
694 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
695 if (*BufPtr != '\t')
696 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000697
Chris Lattnerf04da132007-10-24 17:06:59 +0000698 // Okay, we found a tab. This tab will turn into at least one character,
699 // but it depends on which 'virtual column' it is in. Compute that now.
700 unsigned VCol = 0;
701 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
702 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
703 ++VCol;
Mike Stump1eb44332009-09-09 15:08:12 +0000704
Chris Lattnerf04da132007-10-24 17:06:59 +0000705 // Okay, now that we know the virtual column, we know how many spaces to
706 // insert. We assume 8-character tab-stops.
707 unsigned Spaces = 8-(VCol & 7);
Mike Stump1eb44332009-09-09 15:08:12 +0000708
Chris Lattnerf04da132007-10-24 17:06:59 +0000709 // Get the location of the tab.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000710 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
711 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Mike Stump1eb44332009-09-09 15:08:12 +0000712
Chris Lattnerf04da132007-10-24 17:06:59 +0000713 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000714 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000715 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000716}
717
Steve Naroffeb0646c2008-12-02 15:48:25 +0000718static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
719 ObjCIvarDecl *OID) {
720 std::string S;
721 S = "((struct ";
722 S += ClassDecl->getIdentifier()->getName();
723 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000724 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000725 return S;
726}
727
Steve Naroffa0876e82008-12-02 17:36:43 +0000728void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
729 ObjCImplementationDecl *IMD,
730 ObjCCategoryImplDecl *CID) {
Steve Naroffd40910b2008-12-01 20:33:01 +0000731 SourceLocation startLoc = PID->getLocStart();
732 InsertText(startLoc, "// ", 3);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000733 const char *startBuf = SM->getCharacterData(startLoc);
734 assert((*startBuf == '@') && "bogus @synthesize location");
735 const char *semiBuf = strchr(startBuf, ';');
736 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000737 SourceLocation onePastSemiLoc =
738 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000739
740 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
741 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000742
Steve Naroffeb0646c2008-12-02 15:48:25 +0000743 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000744 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000745 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000746 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000747
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000748 if (!OID)
749 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000750
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000751 std::string Getr;
752 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
753 Getr += "{ ";
754 // Synthesize an explicit cast to gain access to the ivar.
Mike Stump1eb44332009-09-09 15:08:12 +0000755 // FIXME: deal with code generation implications for various property
756 // attributes (copy, retain, nonatomic).
Steve Naroff3539cdb2008-12-02 17:54:50 +0000757 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000758 Getr += "return " + getIvarAccessString(ClassDecl, OID);
759 Getr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000760 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroffeb0646c2008-12-02 15:48:25 +0000761 if (PD->isReadOnly())
762 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000763
Steve Naroffeb0646c2008-12-02 15:48:25 +0000764 // Generate the 'setter' function.
765 std::string Setr;
766 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000767 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000768 // Synthesize an explicit cast to initialize the ivar.
Mike Stump1eb44332009-09-09 15:08:12 +0000769 // FIXME: deal with code generation implications for various property
770 // attributes (copy, retain, nonatomic).
Steve Naroff15f081d2008-12-03 00:56:33 +0000771 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000772 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Narofff4312dc2008-12-11 19:29:16 +0000773 Setr += PD->getNameAsCString();
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000774 Setr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000775 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffd40910b2008-12-01 20:33:01 +0000776}
Chris Lattner8a12c272007-10-11 18:38:32 +0000777
Steve Naroffb29b4272008-04-14 22:03:09 +0000778void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000779 // Get the start location and compute the semi location.
780 SourceLocation startLoc = ClassDecl->getLocation();
781 const char *startBuf = SM->getCharacterData(startLoc);
782 const char *semiPtr = strchr(startBuf, ';');
Mike Stump1eb44332009-09-09 15:08:12 +0000783
Chris Lattnerf04da132007-10-24 17:06:59 +0000784 // Translate to typedef's that forward reference structs with the same name
785 // as the class. As a convenience, we include the original declaration
786 // as a comment.
787 std::string typedefString;
788 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000789 typedefString.append(startBuf, semiPtr-startBuf+1);
790 typedefString += "\n";
Chris Lattner67956052009-02-20 18:04:31 +0000791 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
792 I != E; ++I) {
Ted Kremenek321c22f2009-11-18 00:28:11 +0000793 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff32174822007-11-09 12:50:28 +0000794 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000795 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000796 typedefString += "\n";
797 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000798 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000799 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000800 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000801 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000802 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000803 }
Mike Stump1eb44332009-09-09 15:08:12 +0000804
Steve Naroff934f2762007-10-24 22:48:43 +0000805 // Replace the @class with typedefs corresponding to the classes.
Mike Stump1eb44332009-09-09 15:08:12 +0000806 ReplaceText(startLoc, semiPtr-startBuf+1,
Chris Lattneraadaf782008-01-31 19:51:04 +0000807 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000808}
809
Steve Naroffb29b4272008-04-14 22:03:09 +0000810void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000811 SourceLocation LocStart = Method->getLocStart();
812 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000813
Chris Lattner30fc9332009-02-04 01:06:56 +0000814 if (SM->getInstantiationLineNumber(LocEnd) >
815 SM->getInstantiationLineNumber(LocStart)) {
Steve Naroff94ac21e2008-10-21 13:37:27 +0000816 InsertText(LocStart, "#if 0\n", 6);
817 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000818 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000819 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000820 }
821}
822
Mike Stump1eb44332009-09-09 15:08:12 +0000823void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Steve Naroff6327e0d2009-01-11 01:06:09 +0000824 SourceLocation Loc = prop->getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000825
Steve Naroff6327e0d2009-01-11 01:06:09 +0000826 ReplaceText(Loc, 0, "// ", 3);
Mike Stump1eb44332009-09-09 15:08:12 +0000827
Steve Naroff6327e0d2009-01-11 01:06:09 +0000828 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000829}
830
Steve Naroffb29b4272008-04-14 22:03:09 +0000831void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000832 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000833
Steve Naroff423cb562007-10-30 13:30:57 +0000834 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000835 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump1eb44332009-09-09 15:08:12 +0000836
837 for (ObjCCategoryDecl::instmeth_iterator
838 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000839 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000840 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +0000841 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000842 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000843 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000844 RewriteMethodDeclaration(*I);
845
Steve Naroff423cb562007-10-30 13:30:57 +0000846 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +0000847 ReplaceText(CatDecl->getAtEndRange().getBegin(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000848}
849
Steve Naroffb29b4272008-04-14 22:03:09 +0000850void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000851 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Mike Stump1eb44332009-09-09 15:08:12 +0000852
Steve Naroff752d6ef2007-10-30 16:42:30 +0000853 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000854
Steve Naroff752d6ef2007-10-30 16:42:30 +0000855 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000856 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump1eb44332009-09-09 15:08:12 +0000857
858 for (ObjCProtocolDecl::instmeth_iterator
859 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000860 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000861 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000862 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000863 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000864 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000865 RewriteMethodDeclaration(*I);
866
Steve Naroff752d6ef2007-10-30 16:42:30 +0000867 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +0000868 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Chris Lattneraadaf782008-01-31 19:51:04 +0000869 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000870
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000871 // Must comment out @optional/@required
872 const char *startBuf = SM->getCharacterData(LocStart);
873 const char *endBuf = SM->getCharacterData(LocEnd);
874 for (const char *p = startBuf; p < endBuf; p++) {
875 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
876 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000877 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000878 ReplaceText(OptionalLoc, strlen("@optional"),
879 CommentedOptional.c_str(), CommentedOptional.size());
Mike Stump1eb44332009-09-09 15:08:12 +0000880
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000881 }
882 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
883 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000884 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000885 ReplaceText(OptionalLoc, strlen("@required"),
886 CommentedRequired.c_str(), CommentedRequired.size());
Mike Stump1eb44332009-09-09 15:08:12 +0000887
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000888 }
889 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000890}
891
Steve Naroffb29b4272008-04-14 22:03:09 +0000892void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000893 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000894 if (LocStart.isInvalid())
895 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000896 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000897 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000898}
899
Mike Stump1eb44332009-09-09 15:08:12 +0000900void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000901 std::string &ResultStr) {
Steve Naroffced80a82008-10-30 12:09:33 +0000902 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff76e429d2008-07-16 14:40:40 +0000903 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000904 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000905 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000906 ResultStr += "id";
Steve Narofff4312dc2008-12-11 19:29:16 +0000907 else if (OMD->getResultType()->isFunctionPointerType() ||
908 OMD->getResultType()->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +0000909 // needs special handling, since pointer-to-functions have special
910 // syntax (where a decaration models use).
911 QualType retType = OMD->getResultType();
Steve Narofff4312dc2008-12-11 19:29:16 +0000912 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +0000913 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +0000914 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000915 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +0000916 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +0000917 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Steve Narofff4312dc2008-12-11 19:29:16 +0000918 ResultStr += FPRetType->getResultType().getAsString();
919 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +0000920 }
921 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000922 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000923 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +0000924
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000925 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000926 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +0000927
Douglas Gregorf8d49f62009-01-09 17:18:27 +0000928 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000929 NameStr += "_I_";
930 else
931 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +0000932
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000933 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000934 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +0000935
936 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +0000937 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000938 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000939 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000940 }
Mike Stump1eb44332009-09-09 15:08:12 +0000941 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +0000942 {
943 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000944 int len = selString.size();
945 for (int i = 0; i < len; i++)
946 if (selString[i] == ':')
947 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000948 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000949 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000950 // Remember this name for metadata emission
951 MethodInternalNames[OMD] = NameStr;
952 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +0000953
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000954 // Rewrite arguments
955 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +0000956
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000957 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +0000958 if (OMD->isInstanceMethod()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000959 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000960 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000961 if (!LangOpts.Microsoft) {
962 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
963 ResultStr += "struct ";
964 }
965 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000966 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000967 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000968 }
969 else
Steve Naroff621edce2009-04-29 16:37:50 +0000970 ResultStr += Context->getObjCClassType().getAsString();
Mike Stump1eb44332009-09-09 15:08:12 +0000971
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000972 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000973 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000974 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +0000975
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000976 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +0000977 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
978 E = OMD->param_end(); PI != E; ++PI) {
979 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000980 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000981 if (PDecl->getType()->isObjCQualifiedIdType()) {
982 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000983 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +0000984 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000985 std::string Name = PDecl->getNameAsString();
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000986 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroffc8ad87b2008-10-30 14:45:29 +0000987 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Ted Kremenek6217b802009-07-29 21:53:49 +0000988 const BlockPointerType *BPT = PDecl->getType()->getAs<BlockPointerType>();
Douglas Gregord249e1d1f2009-05-29 20:38:28 +0000989 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name,
990 Context->PrintingPolicy);
Steve Naroffc8ad87b2008-10-30 14:45:29 +0000991 } else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +0000992 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroff543409e2008-04-18 21:13:19 +0000993 ResultStr += Name;
994 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000995 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000996 if (OMD->isVariadic())
997 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000998 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +0000999
Steve Naroff76e429d2008-07-16 14:40:40 +00001000 if (FPRetType) {
1001 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001002
Steve Naroff76e429d2008-07-16 14:40:40 +00001003 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001004 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001005 ResultStr += "(";
1006 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1007 if (i) ResultStr += ", ";
1008 std::string ParamStr = FT->getArgType(i).getAsString();
1009 ResultStr += ParamStr;
1010 }
1011 if (FT->isVariadic()) {
1012 if (FT->getNumArgs()) ResultStr += ", ";
1013 ResultStr += "...";
1014 }
1015 ResultStr += ")";
1016 } else {
1017 ResultStr += "()";
1018 }
1019 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001020}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001021void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001022 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1023 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001024
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001025 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001026 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001027 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001028 InsertText(CID->getLocStart(), "// ", 3);
Mike Stump1eb44332009-09-09 15:08:12 +00001029
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001030 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001031 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1032 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001033 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001034 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001035 ObjCMethodDecl *OMD = *I;
1036 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001037 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001038 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001039
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001040 const char *startBuf = SM->getCharacterData(LocStart);
1041 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +00001042 ReplaceText(LocStart, endBuf-startBuf,
1043 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001044 }
Mike Stump1eb44332009-09-09 15:08:12 +00001045
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001046 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001047 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1048 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001049 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001050 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001051 ObjCMethodDecl *OMD = *I;
1052 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001053 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001054 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001055
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001056 const char *startBuf = SM->getCharacterData(LocStart);
1057 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +00001058 ReplaceText(LocStart, endBuf-startBuf,
Mike Stump1eb44332009-09-09 15:08:12 +00001059 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001060 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001061 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001062 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001063 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001064 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001065 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001066 }
1067
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001068 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001069 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001070 else
Mike Stump1eb44332009-09-09 15:08:12 +00001071 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001072}
1073
Steve Naroffb29b4272008-04-14 22:03:09 +00001074void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001075 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001076 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001077 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001078 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001079 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001080 ResultStr += "\n";
1081 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001082 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001083 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001084 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001085 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001086 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001087 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001088 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001089 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001090 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001091
1092 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001093 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001094 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001095 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001096 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001097 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001098 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001099 for (ObjCInterfaceDecl::classmeth_iterator
1100 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001101 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001102 RewriteMethodDeclaration(*I);
1103
Steve Naroff2feac5e2007-10-30 03:43:13 +00001104 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +00001105 ReplaceText(ClassDecl->getAtEndRange().getBegin(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +00001106}
1107
Steve Naroffb619d952008-12-09 12:56:34 +00001108Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1109 SourceRange SrcRange) {
Steve Naroffc77a6362008-12-04 16:24:46 +00001110 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1111 // This allows us to reuse all the fun and games in SynthMessageExpr().
1112 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1113 ObjCMessageExpr *MsgExpr;
1114 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1115 llvm::SmallVector<Expr *, 1> ExprVec;
1116 ExprVec.push_back(newStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001117
Steve Naroff8599e7a2008-12-08 16:43:47 +00001118 Stmt *Receiver = PropRefExpr->getBase();
1119 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1120 if (PRE && PropGetters[PRE]) {
1121 // This allows us to handle chain/nested property getters.
1122 Receiver = PropGetters[PRE];
1123 }
Mike Stump1eb44332009-09-09 15:08:12 +00001124 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1125 PDecl->getSetterName(), PDecl->getType(),
1126 PDecl->getSetterMethodDecl(),
1127 SourceLocation(), SourceLocation(),
Steve Naroffc77a6362008-12-04 16:24:46 +00001128 &ExprVec[0], 1);
1129 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001130
Steve Naroffc77a6362008-12-04 16:24:46 +00001131 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001132 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001133 //delete BinOp;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001134 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1135 // to things that stay around.
1136 Context->Deallocate(MsgExpr);
Steve Naroffc77a6362008-12-04 16:24:46 +00001137 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001138}
1139
Steve Naroffc77a6362008-12-04 16:24:46 +00001140Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Naroff15f081d2008-12-03 00:56:33 +00001141 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1142 // This allows us to reuse all the fun and games in SynthMessageExpr().
1143 ObjCMessageExpr *MsgExpr;
1144 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
Mike Stump1eb44332009-09-09 15:08:12 +00001145
Steve Naroff8599e7a2008-12-08 16:43:47 +00001146 Stmt *Receiver = PropRefExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00001147
Steve Naroff8599e7a2008-12-08 16:43:47 +00001148 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1149 if (PRE && PropGetters[PRE]) {
1150 // This allows us to handle chain/nested property getters.
1151 Receiver = PropGetters[PRE];
1152 }
Mike Stump1eb44332009-09-09 15:08:12 +00001153 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1154 PDecl->getGetterName(), PDecl->getType(),
1155 PDecl->getGetterMethodDecl(),
1156 SourceLocation(), SourceLocation(),
Steve Naroff15f081d2008-12-03 00:56:33 +00001157 0, 0);
1158
Steve Naroff4c3580e2008-12-04 23:50:32 +00001159 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001160
1161 if (!PropParentMap)
1162 PropParentMap = new ParentMap(CurrentBody);
1163
1164 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1165 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1166 // We stash away the ReplacingStmt since actually doing the
1167 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1168 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001169 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1170 // to things that stay around.
1171 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001172 return PropRefExpr; // return the original...
1173 } else {
1174 ReplaceStmt(PropRefExpr, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001175 // delete PropRefExpr; elsewhere...
Ted Kremenek8189cde2009-02-07 01:47:29 +00001176 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1177 // to things that stay around.
1178 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001179 return ReplacingStmt;
1180 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001181}
1182
Mike Stump1eb44332009-09-09 15:08:12 +00001183Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001184 SourceLocation OrigStart) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001185 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001186 const Expr *BaseExpr = IV->getBase();
Steve Naroff54055232008-10-27 17:20:55 +00001187 if (CurMethodDef) {
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001188 if (IV->isArrow()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001189 ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001190 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Narofff0757612008-05-08 17:52:16 +00001191 // lookup which class implements the instance variable.
1192 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001193 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001194 clsDeclared);
Steve Narofff0757612008-05-08 17:52:16 +00001195 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001196
Steve Narofff0757612008-05-08 17:52:16 +00001197 // Synthesize an explicit cast to gain access to the ivar.
1198 std::string RecName = clsDeclared->getIdentifier()->getName();
1199 RecName += "_IMPL";
1200 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001201 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001202 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001203 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1204 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Mike Stump1eb44332009-09-09 15:08:12 +00001205 CastExpr *castExpr = new (Context) CStyleCastExpr(castT,
Anders Carlssoncdef2b72009-07-31 00:48:10 +00001206 CastExpr::CK_Unknown,
1207 IV->getBase(),
1208 castT,SourceLocation(),
1209 SourceLocation());
Steve Narofff0757612008-05-08 17:52:16 +00001210 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001211 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1212 IV->getBase()->getLocEnd(),
1213 castExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001214 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001215 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001216 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1217 IV->getLocation(),
1218 D->getType());
Steve Narofff0757612008-05-08 17:52:16 +00001219 ReplaceStmt(IV, ME);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001220 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001221 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001222 }
Mike Stump1eb44332009-09-09 15:08:12 +00001223
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001224 ReplaceStmt(IV->getBase(), PE);
1225 // Cannot delete IV->getBase(), since PE points to it.
1226 // Replace the old base with the cast. This is important when doing
1227 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001228 IV->setBase(PE);
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001229 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001230 }
Steve Naroff84472a82008-04-18 21:55:08 +00001231 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001232 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump1eb44332009-09-09 15:08:12 +00001233
Steve Naroff9f525972008-05-06 23:20:07 +00001234 // Explicit ivar refs need to have a cast inserted.
1235 // FIXME: consider sharing some of this code with the code above.
Ted Kremenek6217b802009-07-29 21:53:49 +00001236 if (const PointerType *pType = IV->getBase()->getType()->getAs<PointerType>()) {
Steve Narofff0757612008-05-08 17:52:16 +00001237 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001238 // lookup which class implements the instance variable.
1239 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001240 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001241 clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001242 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001243
Steve Naroff9f525972008-05-06 23:20:07 +00001244 // Synthesize an explicit cast to gain access to the ivar.
1245 std::string RecName = clsDeclared->getIdentifier()->getName();
1246 RecName += "_IMPL";
1247 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001248 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001249 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001250 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1251 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Mike Stump1eb44332009-09-09 15:08:12 +00001252 CastExpr *castExpr = new (Context) CStyleCastExpr(castT,
Anders Carlssoncdef2b72009-07-31 00:48:10 +00001253 CastExpr::CK_Unknown,
1254 IV->getBase(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00001255 castT, SourceLocation(),
1256 SourceLocation());
Steve Naroff9f525972008-05-06 23:20:07 +00001257 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001258 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner8d366162008-05-28 16:38:23 +00001259 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +00001260 ReplaceStmt(IV->getBase(), PE);
1261 // Cannot delete IV->getBase(), since PE points to it.
1262 // Replace the old base with the cast. This is important when doing
1263 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001264 IV->setBase(PE);
Steve Naroff9f525972008-05-06 23:20:07 +00001265 return IV;
1266 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001267 }
Steve Naroff84472a82008-04-18 21:55:08 +00001268 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001269}
1270
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001271/// SynthCountByEnumWithState - To print:
1272/// ((unsigned int (*)
1273/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001274/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001275/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001276/// "countByEnumeratingWithState:objects:count:"),
1277/// &enumState,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001278/// (id *)items, (unsigned int)16)
1279///
Steve Naroffb29b4272008-04-14 22:03:09 +00001280void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001281 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1282 "id *, unsigned int))(void *)objc_msgSend)";
1283 buf += "\n\t\t";
1284 buf += "((id)l_collection,\n\t\t";
1285 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1286 buf += "\n\t\t";
1287 buf += "&enumState, "
1288 "(id *)items, (unsigned int)16)";
1289}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001290
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001291/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1292/// statement to exit to its outer synthesized loop.
1293///
Steve Naroffb29b4272008-04-14 22:03:09 +00001294Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001295 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1296 return S;
1297 // replace break with goto __break_label
1298 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001299
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001300 SourceLocation startLoc = S->getLocStart();
1301 buf = "goto __break_label_";
1302 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001303 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001304
1305 return 0;
1306}
1307
1308/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1309/// statement to continue with its inner synthesized loop.
1310///
Steve Naroffb29b4272008-04-14 22:03:09 +00001311Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001312 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1313 return S;
1314 // replace continue with goto __continue_label
1315 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001316
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001317 SourceLocation startLoc = S->getLocStart();
1318 buf = "goto __continue_label_";
1319 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001320 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001321
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001322 return 0;
1323}
1324
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001325/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001326/// It rewrites:
1327/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001328
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001329/// Into:
1330/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001331/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001332/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001333/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001334/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001335/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001336/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001337/// if (limit) {
1338/// unsigned long startMutations = *enumState.mutationsPtr;
1339/// do {
1340/// unsigned long counter = 0;
1341/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001342/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001343/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001344/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001345/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001346/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001347/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001348/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001349/// objects:items count:16]);
1350/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001351/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001352/// }
1353/// else
1354/// elem = nil;
1355/// }
1356///
Steve Naroffb29b4272008-04-14 22:03:09 +00001357Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001358 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001359 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001360 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001361 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001362 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001363 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001364
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001365 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001366 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001367 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001368 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001369 std::string buf;
1370 buf = "\n{\n\t";
1371 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1372 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001373 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001374 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001375 if (ElementType->isObjCQualifiedIdType() ||
1376 ElementType->isObjCQualifiedInterfaceType())
1377 // Simply use 'id' for all qualified types.
1378 elementTypeAsString = "id";
1379 else
1380 elementTypeAsString = ElementType.getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001381 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001382 buf += " ";
Chris Lattner8ec03f52008-11-24 03:54:41 +00001383 elementName = D->getNameAsCString();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001384 buf += elementName;
1385 buf += ";\n\t";
1386 }
Chris Lattner06767512008-04-08 05:52:18 +00001387 else {
1388 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001389 elementName = DR->getDecl()->getNameAsCString();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001390 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1391 if (VD->getType()->isObjCQualifiedIdType() ||
1392 VD->getType()->isObjCQualifiedInterfaceType())
1393 // Simply use 'id' for all qualified types.
1394 elementTypeAsString = "id";
1395 else
1396 elementTypeAsString = VD->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001397 }
Mike Stump1eb44332009-09-09 15:08:12 +00001398
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001399 // struct __objcFastEnumerationState enumState = { 0 };
1400 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1401 // id items[16];
1402 buf += "id items[16];\n\t";
1403 // id l_collection = (id)
1404 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001405 // Find start location of 'collection' the hard way!
1406 const char *startCollectionBuf = startBuf;
1407 startCollectionBuf += 3; // skip 'for'
1408 startCollectionBuf = strchr(startCollectionBuf, '(');
1409 startCollectionBuf++; // skip '('
1410 // find 'in' and skip it.
1411 while (*startCollectionBuf != ' ' ||
1412 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1413 (*(startCollectionBuf+3) != ' ' &&
1414 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1415 startCollectionBuf++;
1416 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001417
1418 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001419 ReplaceText(startLoc, startCollectionBuf - startBuf,
1420 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001421 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001422 SourceLocation rightParenLoc = S->getRParenLoc();
1423 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1424 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001425 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001426
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001427 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1428 // objects:items count:16];
1429 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001430 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001431 // ((unsigned int (*)
1432 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001433 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001434 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001435 // "countByEnumeratingWithState:objects:count:"),
1436 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001437 // (id *)items, (unsigned int)16);
1438 buf += "unsigned long limit =\n\t\t";
1439 SynthCountByEnumWithState(buf);
1440 buf += ";\n\t";
1441 /// if (limit) {
1442 /// unsigned long startMutations = *enumState.mutationsPtr;
1443 /// do {
1444 /// unsigned long counter = 0;
1445 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001446 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001447 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001448 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001449 buf += "if (limit) {\n\t";
1450 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1451 buf += "do {\n\t\t";
1452 buf += "unsigned long counter = 0;\n\t\t";
1453 buf += "do {\n\t\t\t";
1454 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1455 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1456 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001457 buf += " = (";
1458 buf += elementTypeAsString;
1459 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001460 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001461 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001462
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001463 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001464 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001465 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001466 /// objects:items count:16]);
1467 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001468 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001469 /// }
1470 /// else
1471 /// elem = nil;
1472 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001473 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001474 buf = ";\n\t";
1475 buf += "__continue_label_";
1476 buf += utostr(ObjCBcLabelNo.back());
1477 buf += ": ;";
1478 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001479 buf += "} while (counter < limit);\n\t";
1480 buf += "} while (limit = ";
1481 SynthCountByEnumWithState(buf);
1482 buf += ");\n\t";
1483 buf += elementName;
Steve Naroff5605fdf2008-12-17 14:24:39 +00001484 buf += " = ((id)0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001485 buf += "__break_label_";
1486 buf += utostr(ObjCBcLabelNo.back());
1487 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001488 buf += "}\n\t";
1489 buf += "else\n\t\t";
1490 buf += elementName;
Steve Naroff5605fdf2008-12-17 14:24:39 +00001491 buf += " = ((id)0);\n";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001492 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001493
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001494 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001495 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001496 if (isa<CompoundStmt>(S->getBody())) {
1497 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1498 InsertText(endBodyLoc, buf.c_str(), buf.size());
1499 } else {
1500 /* Need to treat single statements specially. For example:
1501 *
1502 * for (A *a in b) if (stuff()) break;
1503 * for (A *a in b) xxxyy;
1504 *
1505 * The following code simply scans ahead to the semi to find the actual end.
1506 */
1507 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1508 const char *semiBuf = strchr(stmtBuf, ';');
1509 assert(semiBuf && "Can't find ';'");
1510 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1511 InsertText(endBodyLoc, buf.c_str(), buf.size());
1512 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001513 Stmts.pop_back();
1514 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001515 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001516}
1517
Mike Stump1eb44332009-09-09 15:08:12 +00001518/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001519/// This routine rewrites @synchronized(expr) stmt;
1520/// into:
1521/// objc_sync_enter(expr);
1522/// @try stmt @finally { objc_sync_exit(expr); }
1523///
Steve Naroffb29b4272008-04-14 22:03:09 +00001524Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001525 // Get the start location and compute the semi location.
1526 SourceLocation startLoc = S->getLocStart();
1527 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001528
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001529 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001530
1531 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001532 buf = "objc_sync_enter((id)";
1533 const char *lparenBuf = startBuf;
1534 while (*lparenBuf != '(') lparenBuf++;
1535 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001536 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1537 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001538 // been rewritten! (which implies the SourceLocation's are invalid).
1539 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001540 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001541 while (*endBuf != ')') endBuf--;
1542 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001543 buf = ");\n";
1544 // declare a new scope with two variables, _stack and _rethrow.
1545 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1546 buf += "int buf[18/*32-bit i386*/];\n";
1547 buf += "char *pointers[4];} _stack;\n";
1548 buf += "id volatile _rethrow = 0;\n";
1549 buf += "objc_exception_try_enter(&_stack);\n";
1550 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001551 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001552 startLoc = S->getSynchBody()->getLocEnd();
1553 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001554
Steve Naroffc7089f12008-08-19 13:04:19 +00001555 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001556 SourceLocation lastCurlyLoc = startLoc;
1557 buf = "}\nelse {\n";
1558 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001559 buf += "}\n";
1560 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001561 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001562
1563 std::string syncBuf;
1564 syncBuf += " objc_sync_exit(";
Mike Stump1eb44332009-09-09 15:08:12 +00001565 Expr *syncExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00001566 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00001567 S->getSynchExpr(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00001568 Context->getObjCIdType(),
1569 SourceLocation(),
1570 SourceLocation());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001571 std::string syncExprBufS;
1572 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001573 syncExpr->printPretty(syncExprBuf, *Context, 0,
1574 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001575 syncBuf += syncExprBuf.str();
1576 syncBuf += ");";
1577
1578 buf += syncBuf;
1579 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001580 buf += "}\n";
1581 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001582
Chris Lattneraadaf782008-01-31 19:51:04 +00001583 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffb85e77a2009-12-05 21:43:12 +00001584
1585 bool hasReturns = false;
1586 HasReturnStmts(S->getSynchBody(), hasReturns);
1587 if (hasReturns)
1588 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1589
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001590 return 0;
1591}
1592
Steve Naroffb85e77a2009-12-05 21:43:12 +00001593void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1594{
Steve Naroff8c565152008-12-05 17:03:39 +00001595 // Perform a bottom up traversal of all children.
1596 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1597 CI != E; ++CI)
1598 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001599 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001600
Steve Naroffb85e77a2009-12-05 21:43:12 +00001601 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001602 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001603 TryFinallyContainsReturnDiag);
1604 }
1605 return;
1606}
1607
Steve Naroffb85e77a2009-12-05 21:43:12 +00001608void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1609{
1610 // Perform a bottom up traversal of all children.
1611 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1612 CI != E; ++CI)
1613 if (*CI)
1614 HasReturnStmts(*CI, hasReturns);
1615
1616 if (isa<ReturnStmt>(S))
1617 hasReturns = true;
1618 return;
1619}
1620
1621void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1622 // Perform a bottom up traversal of all children.
1623 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1624 CI != E; ++CI)
1625 if (*CI) {
1626 RewriteTryReturnStmts(*CI);
1627 }
1628 if (isa<ReturnStmt>(S)) {
1629 SourceLocation startLoc = S->getLocStart();
1630 const char *startBuf = SM->getCharacterData(startLoc);
1631
1632 const char *semiBuf = strchr(startBuf, ';');
1633 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1634 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1635
1636 std::string buf;
1637 buf = "{ objc_exception_try_exit(&_stack); return";
1638
1639 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1640 InsertText(onePastSemiLoc, "}", 1);
1641 }
1642 return;
1643}
1644
1645void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1646 // Perform a bottom up traversal of all children.
1647 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1648 CI != E; ++CI)
1649 if (*CI) {
1650 RewriteSyncReturnStmts(*CI, syncExitBuf);
1651 }
1652 if (isa<ReturnStmt>(S)) {
1653 SourceLocation startLoc = S->getLocStart();
1654 const char *startBuf = SM->getCharacterData(startLoc);
1655
1656 const char *semiBuf = strchr(startBuf, ';');
1657 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1658 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1659
1660 std::string buf;
1661 buf = "{ objc_exception_try_exit(&_stack);";
1662 buf += syncExitBuf;
1663 buf += " return";
1664
1665 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1666 InsertText(onePastSemiLoc, "}", 1);
1667 }
1668 return;
1669}
1670
Steve Naroffb29b4272008-04-14 22:03:09 +00001671Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001672 // Get the start location and compute the semi location.
1673 SourceLocation startLoc = S->getLocStart();
1674 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001675
Steve Naroff75730982007-11-07 04:08:17 +00001676 assert((*startBuf == '@') && "bogus @try location");
1677
1678 std::string buf;
1679 // declare a new scope with two variables, _stack and _rethrow.
1680 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1681 buf += "int buf[18/*32-bit i386*/];\n";
1682 buf += "char *pointers[4];} _stack;\n";
1683 buf += "id volatile _rethrow = 0;\n";
1684 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001685 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001686
Chris Lattneraadaf782008-01-31 19:51:04 +00001687 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001688
Steve Naroff75730982007-11-07 04:08:17 +00001689 startLoc = S->getTryBody()->getLocEnd();
1690 startBuf = SM->getCharacterData(startLoc);
1691
1692 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001693
Steve Naroff75730982007-11-07 04:08:17 +00001694 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001695 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1696 if (catchList) {
1697 startLoc = startLoc.getFileLocWithOffset(1);
1698 buf = " /* @catch begin */ else {\n";
1699 buf += " id _caught = objc_exception_extract(&_stack);\n";
1700 buf += " objc_exception_try_enter (&_stack);\n";
1701 buf += " if (_setjmp(_stack.buf))\n";
1702 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1703 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001704
Steve Naroffc9ba1722008-07-16 15:31:30 +00001705 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001706 } else { /* no catch list */
1707 buf = "}\nelse {\n";
1708 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1709 buf += "}";
1710 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffc9ba1722008-07-16 15:31:30 +00001711 }
Steve Naroff75730982007-11-07 04:08:17 +00001712 bool sawIdTypedCatch = false;
1713 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001714 while (catchList) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00001715 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001716
Mike Stump1eb44332009-09-09 15:08:12 +00001717 if (catchList == S->getCatchStmts())
Steve Naroff75730982007-11-07 04:08:17 +00001718 buf = "if ("; // we are generating code for the first catch clause
1719 else
1720 buf = "else if (";
1721 startLoc = catchList->getLocStart();
1722 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001723
Steve Naroff75730982007-11-07 04:08:17 +00001724 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001725
Steve Naroff75730982007-11-07 04:08:17 +00001726 const char *lParenLoc = strchr(startBuf, '(');
1727
Steve Naroffbe4b3332008-02-01 22:08:12 +00001728 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001729 // Now rewrite the body...
1730 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001731 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1732 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001733 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1734 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001735 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001736
Steve Naroffe12e6922008-02-01 20:02:07 +00001737 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00001738 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00001739 } else if (catchDecl) {
1740 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001741 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001742 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001743 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001744 sawIdTypedCatch = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001745 } else if (const PointerType *pType = t->getAs<PointerType>()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001746 ObjCInterfaceType *cls; // Should be a pointer to a class.
Mike Stump1eb44332009-09-09 15:08:12 +00001747
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001748 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001749 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001750 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001751 buf += cls->getDecl()->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001752 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001753 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001754 }
1755 }
1756 // Now rewrite the body...
1757 lastCatchBody = catchList->getCatchBody();
1758 SourceLocation rParenLoc = catchList->getRParenLoc();
1759 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1760 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1761 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1762 assert((*rParenBuf == ')') && "bogus @catch paren location");
1763 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001764
Steve Naroff75730982007-11-07 04:08:17 +00001765 buf = " = _caught;";
Mike Stump1eb44332009-09-09 15:08:12 +00001766 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00001767 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001768 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff7ba138a2009-03-03 19:52:17 +00001769 } else {
Steve Naroff75730982007-11-07 04:08:17 +00001770 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001771 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001772 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001773 catchList = catchList->getNextCatchStmt();
1774 }
1775 // Complete the catch list...
1776 if (lastCatchBody) {
1777 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001778 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1779 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001780
Steve Naroff378f47a2008-09-11 15:29:03 +00001781 // Insert the last (implicit) else clause *before* the right curly brace.
1782 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1783 buf = "} /* last catch end */\n";
1784 buf += "else {\n";
1785 buf += " _rethrow = _caught;\n";
1786 buf += " objc_exception_try_exit(&_stack);\n";
1787 buf += "} } /* @catch end */\n";
1788 if (!S->getFinallyStmt())
1789 buf += "}\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001790 InsertText(bodyLoc, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001791
Steve Naroff75730982007-11-07 04:08:17 +00001792 // Set lastCurlyLoc
1793 lastCurlyLoc = lastCatchBody->getLocEnd();
1794 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001795 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001796 startLoc = finalStmt->getLocStart();
1797 startBuf = SM->getCharacterData(startLoc);
1798 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00001799
Steve Naroff75730982007-11-07 04:08:17 +00001800 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001801 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001802
Steve Naroff75730982007-11-07 04:08:17 +00001803 Stmt *body = finalStmt->getFinallyBody();
1804 SourceLocation startLoc = body->getLocStart();
1805 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001806 assert(*SM->getCharacterData(startLoc) == '{' &&
1807 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001808 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00001809 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001810
Steve Naroff75730982007-11-07 04:08:17 +00001811 startLoc = startLoc.getFileLocWithOffset(1);
1812 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001813 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001814 endLoc = endLoc.getFileLocWithOffset(-1);
1815 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001816 InsertText(endLoc, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001817
Steve Naroff75730982007-11-07 04:08:17 +00001818 // Set lastCurlyLoc
1819 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00001820
Steve Naroff8c565152008-12-05 17:03:39 +00001821 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00001822 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001823 } else { /* no finally clause - make sure we synthesize an implicit one */
1824 buf = "{ /* implicit finally clause */\n";
1825 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1826 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1827 buf += "}";
1828 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffb85e77a2009-12-05 21:43:12 +00001829
1830 // Now check for any return/continue/go statements within the @try.
1831 // The implicit finally clause won't called if the @try contains any
1832 // jump statements.
1833 bool hasReturns = false;
1834 HasReturnStmts(S->getTryBody(), hasReturns);
1835 if (hasReturns)
1836 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00001837 }
1838 // Now emit the final closing curly brace...
1839 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1840 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001841 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001842 return 0;
1843}
1844
Steve Naroffb29b4272008-04-14 22:03:09 +00001845Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001846 return 0;
1847}
1848
Steve Naroffb29b4272008-04-14 22:03:09 +00001849Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001850 return 0;
1851}
1852
Mike Stump1eb44332009-09-09 15:08:12 +00001853// This can't be done with ReplaceStmt(S, ThrowExpr), since
1854// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00001855// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001856Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001857 // Get the start location and compute the semi location.
1858 SourceLocation startLoc = S->getLocStart();
1859 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001860
Steve Naroff2bd03922007-11-07 15:32:26 +00001861 assert((*startBuf == '@') && "bogus @throw location");
1862
1863 std::string buf;
1864 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001865 if (S->getThrowExpr())
1866 buf = "objc_exception_throw(";
1867 else // add an implicit argument
1868 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00001869
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001870 // handle "@ throw" correctly.
1871 const char *wBuf = strchr(startBuf, 'w');
1872 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1873 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001874
Steve Naroff2bd03922007-11-07 15:32:26 +00001875 const char *semiBuf = strchr(startBuf, ';');
1876 assert((*semiBuf == ';') && "@throw: can't find ';'");
1877 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1878 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001879 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001880 return 0;
1881}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001882
Steve Naroffb29b4272008-04-14 22:03:09 +00001883Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001884 // Create a new string expression.
1885 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001886 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001887 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattner2085fd62009-02-18 06:40:38 +00001888 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1889 StrEncoding.length(), false,StrType,
1890 SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001891 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00001892
Chris Lattner07506182007-11-30 22:53:43 +00001893 // Replace this subexpr in the parent.
Steve Naroff4c3580e2008-12-04 23:50:32 +00001894 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00001895 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001896}
1897
Steve Naroffb29b4272008-04-14 22:03:09 +00001898Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00001899 if (!SelGetUidFunctionDecl)
1900 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00001901 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1902 // Create a call to sel_registerName("selName").
1903 llvm::SmallVector<Expr*, 8> SelExprs;
1904 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001905 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00001906 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00001907 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00001908 false, argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00001909 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1910 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001911 ReplaceStmt(Exp, SelExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001912 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00001913 return SelExp;
1914}
1915
Steve Naroffb29b4272008-04-14 22:03:09 +00001916CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001917 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001918 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001919 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001920
Steve Naroffebf2b562007-10-23 23:50:29 +00001921 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001922 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001923
Steve Naroffebf2b562007-10-23 23:50:29 +00001924 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001925 QualType pToFunc = Context->getPointerType(msgSendType);
Mike Stump1eb44332009-09-09 15:08:12 +00001926 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc,
Anders Carlssoncdef2b72009-07-31 00:48:10 +00001927 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00001928 DRE,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001929 /*isLvalue=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001930
John McCall183700f2009-09-21 23:43:11 +00001931 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001932
Ted Kremenek668bf912009-02-09 20:51:47 +00001933 return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1934 SourceLocation());
Steve Naroff934f2762007-10-24 22:48:43 +00001935}
1936
Steve Naroffd5255f52007-11-01 13:24:47 +00001937static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1938 const char *&startRef, const char *&endRef) {
1939 while (startBuf < endBuf) {
1940 if (*startBuf == '<')
1941 startRef = startBuf; // mark the start.
1942 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001943 if (startRef && *startRef == '<') {
1944 endRef = startBuf; // mark the end.
1945 return true;
1946 }
1947 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001948 }
1949 startBuf++;
1950 }
1951 return false;
1952}
1953
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001954static void scanToNextArgument(const char *&argRef) {
1955 int angle = 0;
1956 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1957 if (*argRef == '<')
1958 angle++;
1959 else if (*argRef == '>')
1960 angle--;
1961 argRef++;
1962 }
1963 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1964}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001965
Steve Naroffb29b4272008-04-14 22:03:09 +00001966bool RewriteObjC::needToScanForQualifiers(QualType T) {
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001967 return T->isObjCQualifiedIdType() || T->isObjCQualifiedInterfaceType();
Steve Naroffd5255f52007-11-01 13:24:47 +00001968}
1969
Steve Naroff4f95b752008-07-29 18:15:38 +00001970void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1971 QualType Type = E->getType();
1972 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00001973 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00001974
Steve Naroffcda658e2008-11-19 21:15:47 +00001975 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1976 Loc = ECE->getLParenLoc();
1977 EndLoc = ECE->getRParenLoc();
1978 } else {
1979 Loc = E->getLocStart();
1980 EndLoc = E->getLocEnd();
1981 }
1982 // This will defend against trying to rewrite synthesized expressions.
1983 if (Loc.isInvalid() || EndLoc.isInvalid())
1984 return;
1985
Steve Naroff4f95b752008-07-29 18:15:38 +00001986 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00001987 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00001988 const char *startRef = 0, *endRef = 0;
1989 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1990 // Get the locations of the startRef, endRef.
1991 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1992 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1993 // Comment out the protocol references.
1994 InsertText(LessLoc, "/*", 2);
1995 InsertText(GreaterLoc, "*/", 2);
1996 }
1997 }
1998}
1999
Steve Naroffb29b4272008-04-14 22:03:09 +00002000void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002001 SourceLocation Loc;
2002 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002003 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002004 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2005 Loc = VD->getLocation();
2006 Type = VD->getType();
2007 }
2008 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2009 Loc = FD->getLocation();
2010 // Check for ObjC 'id' and class types that have been adorned with protocol
2011 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002012 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002013 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002014 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002015 if (!proto)
2016 return;
2017 Type = proto->getResultType();
2018 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002019 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2020 Loc = FD->getLocation();
2021 Type = FD->getType();
2022 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002023 else
2024 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002025
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002026 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002027 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002028
Steve Naroffd5255f52007-11-01 13:24:47 +00002029 const char *endBuf = SM->getCharacterData(Loc);
2030 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002031 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002032 startBuf--; // scan backward (from the decl location) for return type.
2033 const char *startRef = 0, *endRef = 0;
2034 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2035 // Get the locations of the startRef, endRef.
2036 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2037 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2038 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002039 InsertText(LessLoc, "/*", 2);
2040 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00002041 }
2042 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002043 if (!proto)
2044 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002045 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002046 const char *startBuf = SM->getCharacterData(Loc);
2047 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002048 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2049 if (needToScanForQualifiers(proto->getArgType(i))) {
2050 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002051
Steve Naroffd5255f52007-11-01 13:24:47 +00002052 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002053 // scan forward (from the decl location) for argument types.
2054 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002055 const char *startRef = 0, *endRef = 0;
2056 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2057 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002058 SourceLocation LessLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002059 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002060 SourceLocation GreaterLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002061 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002062 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002063 InsertText(LessLoc, "/*", 2);
2064 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00002065 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002066 startBuf = ++endBuf;
2067 }
2068 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002069 // If the function name is derived from a macro expansion, then the
2070 // argument buffer will not follow the name. Need to speak with Chris.
2071 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002072 startBuf++; // scan forward (from the decl location) for argument types.
2073 startBuf++;
2074 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002075 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002076}
2077
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002078// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002079void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002080 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2081 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002082 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002083 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002084 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002085 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002086 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002087 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002088 SelGetUidIdent, getFuncType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002089 FunctionDecl::Extern, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002090}
2091
Steve Naroffb29b4272008-04-14 22:03:09 +00002092void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002093 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002094 if (FD->getIdentifier() &&
2095 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002096 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002097 return;
2098 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002099 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002100}
2101
Steve Naroffc0a123c2008-03-11 17:37:02 +00002102// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002103void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002104 if (SuperContructorFunctionDecl)
2105 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002106 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroffc0a123c2008-03-11 17:37:02 +00002107 llvm::SmallVector<QualType, 16> ArgTys;
2108 QualType argT = Context->getObjCIdType();
2109 assert(!argT.isNull() && "Can't find 'id' type");
2110 ArgTys.push_back(argT);
2111 ArgTys.push_back(argT);
2112 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2113 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002114 false, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002115 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002116 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002117 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002118 FunctionDecl::Extern, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002119}
2120
Steve Naroff09b266e2007-10-30 23:14:51 +00002121// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002122void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002123 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2124 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002125 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002126 assert(!argT.isNull() && "Can't find 'id' type");
2127 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002128 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002129 assert(!argT.isNull() && "Can't find 'SEL' type");
2130 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002131 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002132 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002133 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002134 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002135 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002136 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002137 FunctionDecl::Extern, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002138}
2139
Steve Naroff874e2322007-11-15 10:28:18 +00002140// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002141void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002142 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2143 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002144 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002145 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002146 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002147 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2148 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2149 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002150 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002151 assert(!argT.isNull() && "Can't find 'SEL' type");
2152 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002153 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00002154 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002155 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002156 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002157 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002158 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002159 FunctionDecl::Extern, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002160}
2161
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002162// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002163void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002164 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2165 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002166 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002167 assert(!argT.isNull() && "Can't find 'id' type");
2168 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002169 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002170 assert(!argT.isNull() && "Can't find 'SEL' type");
2171 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002172 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002173 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002174 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002175 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002176 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002177 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002178 FunctionDecl::Extern, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002179}
2180
Mike Stump1eb44332009-09-09 15:08:12 +00002181// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002182// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002183void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002184 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002185 &Context->Idents.get("objc_msgSendSuper_stret");
2186 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002187 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002188 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002189 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002190 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2191 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2192 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002193 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002194 assert(!argT.isNull() && "Can't find 'SEL' type");
2195 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002196 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002197 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002198 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002199 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002200 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002201 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002202 FunctionDecl::Extern, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002203}
2204
Steve Naroff1284db82008-05-08 22:02:18 +00002205// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002206void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002207 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2208 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002209 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002210 assert(!argT.isNull() && "Can't find 'id' type");
2211 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002212 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002213 assert(!argT.isNull() && "Can't find 'SEL' type");
2214 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00002215 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002216 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002217 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002218 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002219 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002220 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002221 FunctionDecl::Extern, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002222}
2223
Steve Naroff09b266e2007-10-30 23:14:51 +00002224// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002225void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002226 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2227 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002228 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002229 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002230 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002231 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002232 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002233 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002234 getClassIdent, getClassType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002235 FunctionDecl::Extern, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002236}
2237
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002238// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002239void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002240 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2241 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002242 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002243 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002244 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002245 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002246 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002247 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002248 getClassIdent, getClassType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002249 FunctionDecl::Extern, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002250}
2251
Steve Naroffb29b4272008-04-14 22:03:09 +00002252Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002253 QualType strType = getConstantStringStructType();
2254
2255 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002256
2257 std::string tmpName = InFileName;
2258 unsigned i;
2259 for (i=0; i < tmpName.length(); i++) {
2260 char c = tmpName.at(i);
2261 // replace any non alphanumeric characters with '_'.
2262 if (!isalpha(c) && (c < '0' || c > '9'))
2263 tmpName[i] = '_';
2264 }
2265 S += tmpName;
2266 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002267 S += utostr(NumObjCStringLiterals++);
2268
Steve Naroffba92b2e2008-03-27 22:29:16 +00002269 Preamble += "static __NSConstantStringImpl " + S;
2270 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2271 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002272 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002273 std::string prettyBufS;
2274 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002275 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2276 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002277 Preamble += prettyBuf.str();
2278 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002279 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002280
2281 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2282 &Context->Idents.get(S.c_str()), strType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002283 VarDecl::Static);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002284 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2285 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002286 Context->getPointerType(DRE->getType()),
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002287 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002288 // cast to NSConstantString *
Mike Stump1eb44332009-09-09 15:08:12 +00002289 CastExpr *cast = new (Context) CStyleCastExpr(Exp->getType(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002290 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002291 Unop, Exp->getType(),
2292 SourceLocation(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002293 SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002294 ReplaceStmt(Exp, cast);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002295 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002296 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002297}
2298
Steve Naroffb29b4272008-04-14 22:03:09 +00002299ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002300 // check if we are sending a message to 'super'
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002301 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002302
Douglas Gregorcd9b46e2008-11-04 14:56:14 +00002303 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002304 const ObjCObjectPointerType *OPT =
John McCall183700f2009-09-21 23:43:11 +00002305 Super->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00002306 assert(OPT);
2307 const ObjCInterfaceType *IT = OPT->getInterfaceType();
Chris Lattner0d17f6f2008-06-21 18:04:54 +00002308 return IT->getDecl();
2309 }
2310 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00002311}
2312
2313// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002314QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002315 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002316 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002317 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002318 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002319 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002320
Steve Naroff874e2322007-11-15 10:28:18 +00002321 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002322 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002323 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002324 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002325
Steve Naroff874e2322007-11-15 10:28:18 +00002326 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002327 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002328 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2329 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002330 FieldTypes[i], 0,
2331 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002332 /*Mutable=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002333 }
Mike Stump1eb44332009-09-09 15:08:12 +00002334
Douglas Gregor44b43212008-12-11 16:49:14 +00002335 SuperStructDecl->completeDefinition(*Context);
Steve Naroff874e2322007-11-15 10:28:18 +00002336 }
2337 return Context->getTagDeclType(SuperStructDecl);
2338}
2339
Steve Naroffb29b4272008-04-14 22:03:09 +00002340QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002341 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002342 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002343 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002344 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002345 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002346
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002347 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002348 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002349 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002350 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002351 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002352 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002353 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002354 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002355
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002356 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002357 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002358 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2359 ConstantStringDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002360 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002361 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002362 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002363 /*Mutable=*/true));
Douglas Gregor44b43212008-12-11 16:49:14 +00002364 }
2365
2366 ConstantStringDecl->completeDefinition(*Context);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002367 }
2368 return Context->getTagDeclType(ConstantStringDecl);
2369}
2370
Steve Naroffb29b4272008-04-14 22:03:09 +00002371Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002372 if (!SelGetUidFunctionDecl)
2373 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002374 if (!MsgSendFunctionDecl)
2375 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002376 if (!MsgSendSuperFunctionDecl)
2377 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002378 if (!MsgSendStretFunctionDecl)
2379 SynthMsgSendStretFunctionDecl();
2380 if (!MsgSendSuperStretFunctionDecl)
2381 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002382 if (!MsgSendFpretFunctionDecl)
2383 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002384 if (!GetClassFunctionDecl)
2385 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002386 if (!GetMetaClassFunctionDecl)
2387 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002388
Steve Naroff874e2322007-11-15 10:28:18 +00002389 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002390 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2391 // May need to use objc_msgSend_stret() as well.
2392 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002393 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2394 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002395 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002396 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002397 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002398 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002399 }
Mike Stump1eb44332009-09-09 15:08:12 +00002400
Steve Naroff934f2762007-10-24 22:48:43 +00002401 // Synthesize a call to objc_msgSend().
2402 llvm::SmallVector<Expr*, 8> MsgExprs;
2403 IdentifierInfo *clsName = Exp->getClassName();
Mike Stump1eb44332009-09-09 15:08:12 +00002404
Steve Naroff934f2762007-10-24 22:48:43 +00002405 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2406 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002407 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2408 // the 'super' idiom within a class method.
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00002409 if (clsName->getName() == "super") {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002410 MsgSendFlavor = MsgSendSuperFunctionDecl;
2411 if (MsgSendStretFlavor)
2412 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2413 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002414
2415 ObjCInterfaceDecl *SuperDecl =
Steve Naroff54055232008-10-27 17:20:55 +00002416 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002417
2418 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00002419
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002420 // set the receiver to self, the first argument to all methods.
Steve Naroff621edce2009-04-29 16:37:50 +00002421 InitExprs.push_back(
Mike Stump1eb44332009-09-09 15:08:12 +00002422 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002423 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002424 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff621edce2009-04-29 16:37:50 +00002425 Context->getObjCIdType(),
2426 SourceLocation()),
2427 Context->getObjCIdType(),
2428 SourceLocation(), SourceLocation())); // set the 'receiver'.
2429
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002430 llvm::SmallVector<Expr*, 8> ClsExprs;
2431 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002432 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbare013d682009-10-18 20:26:12 +00002433 SuperDecl->getIdentifier()->getNameStart(),
2434 SuperDecl->getIdentifier()->getLength(),
2435 false, argType, SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002436 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002437 &ClsExprs[0],
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002438 ClsExprs.size());
2439 // To turn off a warning, type-cast to 'id'
Douglas Gregor49badde2008-10-27 19:41:14 +00002440 InitExprs.push_back( // set 'super class', using objc_getClass().
Mike Stump1eb44332009-09-09 15:08:12 +00002441 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002442 CastExpr::CK_Unknown,
Douglas Gregor49badde2008-10-27 19:41:14 +00002443 Cls, Context->getObjCIdType(),
Mike Stump1eb44332009-09-09 15:08:12 +00002444 SourceLocation(), SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002445 // struct objc_super
2446 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002447 Expr *SuperRep;
Mike Stump1eb44332009-09-09 15:08:12 +00002448
Steve Naroff23f41272008-03-11 18:14:26 +00002449 if (LangOpts.Microsoft) {
2450 SynthSuperContructorFunctionDecl();
2451 // Simulate a contructor call...
Mike Stump1eb44332009-09-09 15:08:12 +00002452 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff23f41272008-03-11 18:14:26 +00002453 superType, SourceLocation());
Ted Kremenek668bf912009-02-09 20:51:47 +00002454 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002455 InitExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002456 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002457 // The code for super is a little tricky to prevent collision with
2458 // the structure definition in the header. The rewriter has it's own
2459 // internal definition (__rw_objc_super) that is uses. This is why
2460 // we need the cast below. For example:
2461 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2462 //
Ted Kremenek8189cde2009-02-07 01:47:29 +00002463 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002464 Context->getPointerType(SuperRep->getType()),
Steve Naroff46a98a72008-12-23 20:11:22 +00002465 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002466 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
2467 CastExpr::CK_Unknown, SuperRep,
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002468 Context->getPointerType(superType),
Mike Stump1eb44332009-09-09 15:08:12 +00002469 SourceLocation(), SourceLocation());
2470 } else {
Steve Naroff23f41272008-03-11 18:14:26 +00002471 // (struct objc_super) { <exprs from above> }
Mike Stump1eb44332009-09-09 15:08:12 +00002472 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2473 &InitExprs[0], InitExprs.size(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002474 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00002475 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE,
Chris Lattner418f6c72008-10-26 23:43:26 +00002476 false);
Steve Naroff46a98a72008-12-23 20:11:22 +00002477 // struct objc_super *
Ted Kremenek8189cde2009-02-07 01:47:29 +00002478 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002479 Context->getPointerType(SuperRep->getType()),
Steve Naroff46a98a72008-12-23 20:11:22 +00002480 SourceLocation());
Steve Naroff23f41272008-03-11 18:14:26 +00002481 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002482 MsgExprs.push_back(SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002483 } else {
2484 llvm::SmallVector<Expr*, 8> ClsExprs;
2485 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002486 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbare013d682009-10-18 20:26:12 +00002487 clsName->getNameStart(),
Chris Lattner2085fd62009-02-18 06:40:38 +00002488 clsName->getLength(),
2489 false, argType,
2490 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002491 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002492 &ClsExprs[0],
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002493 ClsExprs.size());
2494 MsgExprs.push_back(Cls);
2495 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002496 } else { // instance message.
2497 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002498
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002499 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002500 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002501 if (MsgSendStretFlavor)
2502 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002503 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002504
Steve Naroff874e2322007-11-15 10:28:18 +00002505 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00002506
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002507 InitExprs.push_back(
Mike Stump1eb44332009-09-09 15:08:12 +00002508 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002509 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002510 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002511 Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002512 SourceLocation()),
2513 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002514 SourceLocation(), SourceLocation())); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002515
Steve Naroff874e2322007-11-15 10:28:18 +00002516 llvm::SmallVector<Expr*, 8> ClsExprs;
2517 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002518 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbare013d682009-10-18 20:26:12 +00002519 SuperDecl->getIdentifier()->getNameStart(),
2520 SuperDecl->getIdentifier()->getLength(),
2521 false, argType, SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002522 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002523 &ClsExprs[0],
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002524 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002525 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002526 InitExprs.push_back(
Douglas Gregor49badde2008-10-27 19:41:14 +00002527 // set 'super class', using objc_getClass().
Mike Stump1eb44332009-09-09 15:08:12 +00002528 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002529 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002530 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002531 // struct objc_super
2532 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002533 Expr *SuperRep;
Mike Stump1eb44332009-09-09 15:08:12 +00002534
Steve Naroffc0a123c2008-03-11 17:37:02 +00002535 if (LangOpts.Microsoft) {
2536 SynthSuperContructorFunctionDecl();
2537 // Simulate a contructor call...
Mike Stump1eb44332009-09-09 15:08:12 +00002538 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroffc0a123c2008-03-11 17:37:02 +00002539 superType, SourceLocation());
Ted Kremenek668bf912009-02-09 20:51:47 +00002540 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002541 InitExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002542 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002543 // The code for super is a little tricky to prevent collision with
2544 // the structure definition in the header. The rewriter has it's own
2545 // internal definition (__rw_objc_super) that is uses. This is why
2546 // we need the cast below. For example:
2547 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2548 //
Ted Kremenek8189cde2009-02-07 01:47:29 +00002549 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002550 Context->getPointerType(SuperRep->getType()),
Steve Naroff46a98a72008-12-23 20:11:22 +00002551 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002552 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002553 CastExpr::CK_Unknown,
Steve Naroff46a98a72008-12-23 20:11:22 +00002554 SuperRep, Context->getPointerType(superType),
Mike Stump1eb44332009-09-09 15:08:12 +00002555 SourceLocation(), SourceLocation());
Steve Naroffc0a123c2008-03-11 17:37:02 +00002556 } else {
2557 // (struct objc_super) { <exprs from above> }
Mike Stump1eb44332009-09-09 15:08:12 +00002558 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2559 &InitExprs[0], InitExprs.size(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002560 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00002561 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002562 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002563 MsgExprs.push_back(SuperRep);
Steve Naroff874e2322007-11-15 10:28:18 +00002564 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002565 // Remove all type-casts because it may contain objc-style types; e.g.
2566 // Foo<Proto> *.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002567 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002568 recExpr = CE->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002569 recExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002570 CastExpr::CK_Unknown, recExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00002571 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002572 SourceLocation(), SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002573 MsgExprs.push_back(recExpr);
2574 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002575 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002576 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002577 llvm::SmallVector<Expr*, 8> SelExprs;
2578 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002579 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002580 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002581 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002582 false, argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00002583 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2584 &SelExprs[0], SelExprs.size());
2585 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002586
Steve Naroff934f2762007-10-24 22:48:43 +00002587 // Now push any user supplied arguments.
2588 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002589 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002590 // Make all implicit casts explicit...ICE comes in handy:-)
2591 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2592 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002593 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002594 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002595 : ICE->getType();
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002596 userExpr = new (Context) CStyleCastExpr(type, CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002597 userExpr, type, SourceLocation(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002598 SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002599 }
2600 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002601 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002602 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002603 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002604 userExpr = CE->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002605 userExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002606 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002607 userExpr, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002608 SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002609 }
Mike Stump1eb44332009-09-09 15:08:12 +00002610 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002611 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00002612 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2613 // out the argument in the original expression (since we aren't deleting
2614 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2615 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00002616 }
Steve Naroffab972d32007-11-04 22:37:50 +00002617 // Generate the funky cast.
2618 CastExpr *cast;
2619 llvm::SmallVector<QualType, 8> ArgTypes;
2620 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00002621
Steve Naroffab972d32007-11-04 22:37:50 +00002622 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002623 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2624 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2625 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002626 ArgTypes.push_back(Context->getObjCIdType());
2627 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00002628 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002629 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00002630 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2631 E = OMD->param_end(); PI != E; ++PI) {
2632 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00002633 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00002634 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002635 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00002636 if (isTopLevelBlockPointerType(t)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002637 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroffa206b062008-10-29 14:49:46 +00002638 t = Context->getPointerType(BPT->getPointeeType());
2639 }
Steve Naroff352336b2007-11-05 14:36:37 +00002640 ArgTypes.push_back(t);
2641 }
Chris Lattner89951a82009-02-20 18:43:26 +00002642 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2643 ? Context->getObjCIdType() : OMD->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002644 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002645 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002646 }
2647 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002648 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002649
Steve Naroffab972d32007-11-04 22:37:50 +00002650 // Create a reference to the objc_msgSend() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002651 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002652 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002653
Mike Stump1eb44332009-09-09 15:08:12 +00002654 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00002655 // If we don't do this cast, we get the following bizarre warning/note:
2656 // xx.m:13: warning: function called through a non-compatible type
2657 // xx.m:13: note: if this code is reached, the program will abort
Mike Stump1eb44332009-09-09 15:08:12 +00002658 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy),
2659 CastExpr::CK_Unknown, DRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002660 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002661 SourceLocation(), SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002662
Steve Naroffab972d32007-11-04 22:37:50 +00002663 // Now do the "normal" pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00002664 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002665 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002666 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002667 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroffab972d32007-11-04 22:37:50 +00002668 castType = Context->getPointerType(castType);
Mike Stump1eb44332009-09-09 15:08:12 +00002669 cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown, cast,
2670 castType, SourceLocation(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002671 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002672
2673 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002674 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00002675
John McCall183700f2009-09-21 23:43:11 +00002676 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00002677 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002678 MsgExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002679 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002680 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002681 if (MsgSendStretFlavor) {
2682 // We have the method which returns a struct/union. Must also generate
2683 // call to objc_msgSend_stret and hang both varieties on a conditional
2684 // expression which dictate which one to envoke depending on size of
2685 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00002686
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002687 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002688 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002689 SourceLocation());
2690 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Mike Stump1eb44332009-09-09 15:08:12 +00002691 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy),
2692 CastExpr::CK_Unknown, STDRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002693 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002694 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002695 // Now do the "normal" pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00002696 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002697 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002698 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002699 castType = Context->getPointerType(castType);
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002700 cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown,
2701 cast, castType, SourceLocation(), SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002702
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002703 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002704 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00002705
John McCall183700f2009-09-21 23:43:11 +00002706 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00002707 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002708 MsgExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002709 FT->getResultType(), SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002710
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002711 // Build sizeof(returnType)
Mike Stump1eb44332009-09-09 15:08:12 +00002712 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCalla93c9342009-12-07 02:54:59 +00002713 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl05189992008-11-11 17:56:53 +00002714 Context->getSizeType(),
2715 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002716 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2717 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2718 // For X86 it is more complicated and some kind of target specific routine
2719 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00002720 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00002721 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Mike Stump1eb44332009-09-09 15:08:12 +00002722 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002723 Context->IntTy,
2724 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002725 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
2726 BinaryOperator::LE,
2727 Context->IntTy,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002728 SourceLocation());
2729 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00002730 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00002731 new (Context) ConditionalOperator(lessThanExpr,
2732 SourceLocation(), CE,
2733 SourceLocation(), STCE, returnType);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002734 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002735 }
Mike Stump1eb44332009-09-09 15:08:12 +00002736 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002737 return ReplacingStmt;
2738}
2739
Steve Naroffb29b4272008-04-14 22:03:09 +00002740Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002741 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00002742
Steve Naroff934f2762007-10-24 22:48:43 +00002743 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002744 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00002745
2746 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002747 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002748}
2749
Steve Naroff621edce2009-04-29 16:37:50 +00002750// typedef struct objc_object Protocol;
2751QualType RewriteObjC::getProtocolType() {
2752 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00002753 TypeSourceInfo *TInfo
2754 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00002755 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002756 SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00002757 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00002758 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00002759 }
2760 return Context->getTypeDeclType(ProtocolTypeDecl);
2761}
2762
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002763/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00002764/// a synthesized/forward data reference (to the protocol's metadata).
2765/// The forward references (and metadata) are generated in
2766/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00002767Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00002768 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
2769 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00002770 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregor0da76df2009-11-23 11:41:28 +00002771 ID, getProtocolType(), 0, VarDecl::Extern);
Steve Naroff621edce2009-04-29 16:37:50 +00002772 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
2773 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
2774 Context->getPointerType(DRE->getType()),
2775 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002776 CastExpr *castExpr = new (Context) CStyleCastExpr(DerefExpr->getType(),
2777 CastExpr::CK_Unknown,
2778 DerefExpr, DerefExpr->getType(),
Steve Naroff621edce2009-04-29 16:37:50 +00002779 SourceLocation(), SourceLocation());
2780 ReplaceStmt(Exp, castExpr);
2781 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump1eb44332009-09-09 15:08:12 +00002782 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00002783 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002784
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002785}
2786
Mike Stump1eb44332009-09-09 15:08:12 +00002787bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00002788 const char *endBuf) {
2789 while (startBuf < endBuf) {
2790 if (*startBuf == '#') {
2791 // Skip whitespace.
2792 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2793 ;
2794 if (!strncmp(startBuf, "if", strlen("if")) ||
2795 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2796 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2797 !strncmp(startBuf, "define", strlen("define")) ||
2798 !strncmp(startBuf, "undef", strlen("undef")) ||
2799 !strncmp(startBuf, "else", strlen("else")) ||
2800 !strncmp(startBuf, "elif", strlen("elif")) ||
2801 !strncmp(startBuf, "endif", strlen("endif")) ||
2802 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2803 !strncmp(startBuf, "include", strlen("include")) ||
2804 !strncmp(startBuf, "import", strlen("import")) ||
2805 !strncmp(startBuf, "include_next", strlen("include_next")))
2806 return true;
2807 }
2808 startBuf++;
2809 }
2810 return false;
2811}
2812
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002813/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002814/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002815void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002816 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002817 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Mike Stump1eb44332009-09-09 15:08:12 +00002818 assert(CDecl->getNameAsCString() &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002819 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002820 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002821 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002822 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002823 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002824 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002825 SourceLocation LocStart = CDecl->getLocStart();
2826 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00002827
Steve Narofffea763e82007-11-14 19:25:57 +00002828 const char *startBuf = SM->getCharacterData(LocStart);
2829 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00002830
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002831 // If no ivars and no root or if its root, directly or indirectly,
2832 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002833 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2834 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00002835 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Chris Lattneraadaf782008-01-31 19:51:04 +00002836 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002837 return;
2838 }
Mike Stump1eb44332009-09-09 15:08:12 +00002839
2840 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002841 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002842 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002843 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002844 if (LangOpts.Microsoft)
2845 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002846
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002847 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002848 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00002849 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002850 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00002851 // If the buffer contains preprocessor directives, we do more fine-grained
2852 // rewrites. This is intended to fix code that looks like (which occurs in
2853 // NSURL.h, for example):
2854 //
2855 // #ifdef XYZ
2856 // @interface Foo : NSObject
2857 // #else
2858 // @interface FooBar : NSObject
2859 // #endif
2860 // {
2861 // int i;
2862 // }
2863 // @end
2864 //
2865 // This clause is segregated to avoid breaking the common case.
2866 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002867 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffbaf58c32008-05-31 14:15:04 +00002868 CDecl->getClassLoc();
2869 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00002870 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002871
Chris Lattnercafeb352009-02-20 18:18:36 +00002872 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00002873 // advance to the end of the referenced protocols.
2874 while (endHeader < cursor && *endHeader != '>') endHeader++;
2875 endHeader++;
2876 }
2877 // rewrite the original header
2878 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2879 } else {
2880 // rewrite the original header *without* disturbing the '{'
Steve Naroff17c87782009-12-04 21:36:32 +00002881 ReplaceText(LocStart, cursor-startBuf, Result.c_str(), Result.size());
Steve Naroffbaf58c32008-05-31 14:15:04 +00002882 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002883 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002884 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002885 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002886 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002887 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002888 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002889
Steve Narofffea763e82007-11-14 19:25:57 +00002890 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002891 SourceLocation OnePastCurly =
2892 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2893 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002894 }
2895 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00002896
Steve Narofffea763e82007-11-14 19:25:57 +00002897 // Now comment out any visibility specifiers.
2898 while (cursor < endBuf) {
2899 if (*cursor == '@') {
2900 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002901 // Skip whitespace.
2902 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2903 /*scan*/;
2904
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002905 // FIXME: presence of @public, etc. inside comment results in
2906 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002907 if (!strncmp(cursor, "public", strlen("public")) ||
2908 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002909 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002910 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002911 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002912 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002913 // FIXME: If there are cases where '<' is used in ivar declaration part
2914 // of user code, then scan the ivar list and use needToScanForQualifiers
2915 // for type checking.
2916 else if (*cursor == '<') {
2917 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002918 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002919 cursor = strchr(cursor, '>');
2920 cursor++;
2921 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002922 InsertText(atLoc, " */", 3);
Steve Naroffced80a82008-10-30 12:09:33 +00002923 } else if (*cursor == '^') { // rewrite block specifier.
2924 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2925 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002926 }
Steve Narofffea763e82007-11-14 19:25:57 +00002927 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002928 }
Steve Narofffea763e82007-11-14 19:25:57 +00002929 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002930 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002931 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00002932 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00002933 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002934 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002935 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002936 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002937 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002938 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002939 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002940 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002941 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002942 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002943}
2944
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002945// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002946/// class methods.
Douglas Gregor653f1b12009-04-23 01:02:12 +00002947template<typename MethodIterator>
2948void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
2949 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002950 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002951 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002952 const char *ClassName,
2953 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002954 if (MethodBegin == MethodEnd) return;
Mike Stump1eb44332009-09-09 15:08:12 +00002955
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002956 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002957 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002958 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002959 SEL _cmd;
2960 char *method_types;
2961 void *_imp;
2962 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002963 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002964 Result += "\nstruct _objc_method {\n";
2965 Result += "\tSEL _cmd;\n";
2966 Result += "\tchar *method_types;\n";
2967 Result += "\tvoid *_imp;\n";
2968 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002969
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002970 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002971 }
Mike Stump1eb44332009-09-09 15:08:12 +00002972
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002973 // Build _objc_method_list for class's methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00002974
Steve Naroff946a6932008-03-11 00:12:29 +00002975 /* struct {
2976 struct _objc_method_list *next_method;
2977 int method_count;
2978 struct _objc_method method_list[];
2979 }
2980 */
Douglas Gregor653f1b12009-04-23 01:02:12 +00002981 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroff946a6932008-03-11 00:12:29 +00002982 Result += "\nstatic struct {\n";
2983 Result += "\tstruct _objc_method_list *next_method;\n";
2984 Result += "\tint method_count;\n";
2985 Result += "\tstruct _objc_method method_list[";
Douglas Gregor653f1b12009-04-23 01:02:12 +00002986 Result += utostr(NumMethods);
Steve Naroff946a6932008-03-11 00:12:29 +00002987 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002988 Result += prefix;
2989 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2990 Result += "_METHODS_";
2991 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002992 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002993 Result += IsInstanceMethod ? "inst" : "cls";
2994 Result += "_meth\")))= ";
Douglas Gregor653f1b12009-04-23 01:02:12 +00002995 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002996
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002997 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002998 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002999 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003000 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003001 Result += "\", \"";
3002 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003003 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003004 Result += MethodInternalNames[*MethodBegin];
3005 Result += "}\n";
3006 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3007 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003008 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003009 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003010 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003011 Result += "\", \"";
3012 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003013 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003014 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00003015 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003016 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003017 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003018}
3019
Steve Naroff621edce2009-04-29 16:37:50 +00003020/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00003021void RewriteObjC::
Steve Naroff621edce2009-04-29 16:37:50 +00003022RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
3023 const char *ClassName, std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003024 static bool objc_protocol_methods = false;
Steve Naroff621edce2009-04-29 16:37:50 +00003025
3026 // Output struct protocol_methods holder of method selector and type.
3027 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3028 /* struct protocol_methods {
3029 SEL _cmd;
3030 char *method_types;
3031 }
3032 */
3033 Result += "\nstruct _protocol_methods {\n";
3034 Result += "\tstruct objc_selector *_cmd;\n";
3035 Result += "\tchar *method_types;\n";
3036 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003037
Steve Naroff621edce2009-04-29 16:37:50 +00003038 objc_protocol_methods = true;
3039 }
3040 // Do not synthesize the protocol more than once.
3041 if (ObjCSynthesizedProtocols.count(PDecl))
3042 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003043
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003044 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3045 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3046 PDecl->instmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003047 /* struct _objc_protocol_method_list {
3048 int protocol_method_count;
3049 struct protocol_methods protocols[];
3050 }
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003051 */
Steve Naroff621edce2009-04-29 16:37:50 +00003052 Result += "\nstatic struct {\n";
3053 Result += "\tint protocol_method_count;\n";
3054 Result += "\tstruct _protocol_methods protocol_methods[";
3055 Result += utostr(NumMethods);
3056 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3057 Result += PDecl->getNameAsString();
3058 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3059 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003060
Steve Naroff621edce2009-04-29 16:37:50 +00003061 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003062 for (ObjCProtocolDecl::instmeth_iterator
3063 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003064 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003065 if (I == PDecl->instmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003066 Result += "\t ,{{(struct objc_selector *)\"";
3067 else
3068 Result += "\t ,{(struct objc_selector *)\"";
3069 Result += (*I)->getSelector().getAsString().c_str();
3070 std::string MethodTypeString;
3071 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3072 Result += "\", \"";
3073 Result += MethodTypeString;
3074 Result += "\"}\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003075 }
Steve Naroff621edce2009-04-29 16:37:50 +00003076 Result += "\t }\n};\n";
3077 }
Mike Stump1eb44332009-09-09 15:08:12 +00003078
Steve Naroff621edce2009-04-29 16:37:50 +00003079 // Output class methods declared in this protocol.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003080 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3081 PDecl->classmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003082 if (NumMethods > 0) {
3083 /* struct _objc_protocol_method_list {
3084 int protocol_method_count;
3085 struct protocol_methods protocols[];
3086 }
3087 */
3088 Result += "\nstatic struct {\n";
3089 Result += "\tint protocol_method_count;\n";
3090 Result += "\tstruct _protocol_methods protocol_methods[";
3091 Result += utostr(NumMethods);
3092 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3093 Result += PDecl->getNameAsString();
3094 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3095 "{\n\t";
3096 Result += utostr(NumMethods);
3097 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003098
Steve Naroff621edce2009-04-29 16:37:50 +00003099 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003100 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003101 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003102 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003103 if (I == PDecl->classmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003104 Result += "\t ,{{(struct objc_selector *)\"";
3105 else
3106 Result += "\t ,{(struct objc_selector *)\"";
3107 Result += (*I)->getSelector().getAsString().c_str();
3108 std::string MethodTypeString;
3109 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3110 Result += "\", \"";
3111 Result += MethodTypeString;
3112 Result += "\"}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003113 }
Steve Naroff621edce2009-04-29 16:37:50 +00003114 Result += "\t }\n};\n";
3115 }
3116
3117 // Output:
3118 /* struct _objc_protocol {
3119 // Objective-C 1.0 extensions
3120 struct _objc_protocol_extension *isa;
3121 char *protocol_name;
3122 struct _objc_protocol **protocol_list;
3123 struct _objc_protocol_method_list *instance_methods;
3124 struct _objc_protocol_method_list *class_methods;
Mike Stump1eb44332009-09-09 15:08:12 +00003125 };
Steve Naroff621edce2009-04-29 16:37:50 +00003126 */
3127 static bool objc_protocol = false;
3128 if (!objc_protocol) {
3129 Result += "\nstruct _objc_protocol {\n";
3130 Result += "\tstruct _objc_protocol_extension *isa;\n";
3131 Result += "\tchar *protocol_name;\n";
3132 Result += "\tstruct _objc_protocol **protocol_list;\n";
3133 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3134 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003135 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003136
Steve Naroff621edce2009-04-29 16:37:50 +00003137 objc_protocol = true;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003138 }
Mike Stump1eb44332009-09-09 15:08:12 +00003139
Steve Naroff621edce2009-04-29 16:37:50 +00003140 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3141 Result += PDecl->getNameAsString();
3142 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3143 "{\n\t0, \"";
3144 Result += PDecl->getNameAsString();
3145 Result += "\", 0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003146 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003147 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3148 Result += PDecl->getNameAsString();
3149 Result += ", ";
3150 }
3151 else
3152 Result += "0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003153 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003154 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3155 Result += PDecl->getNameAsString();
3156 Result += "\n";
3157 }
3158 else
3159 Result += "0\n";
3160 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003161
Steve Naroff621edce2009-04-29 16:37:50 +00003162 // Mark this protocol as having been generated.
3163 if (!ObjCSynthesizedProtocols.insert(PDecl))
3164 assert(false && "protocol already synthesized");
3165
3166}
3167
3168void RewriteObjC::
3169RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3170 const char *prefix, const char *ClassName,
3171 std::string &Result) {
3172 if (Protocols.empty()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003173
Steve Naroff621edce2009-04-29 16:37:50 +00003174 for (unsigned i = 0; i != Protocols.size(); i++)
3175 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3176
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003177 // Output the top lovel protocol meta-data for the class.
3178 /* struct _objc_protocol_list {
3179 struct _objc_protocol_list *next;
3180 int protocol_count;
3181 struct _objc_protocol *class_protocols[];
3182 }
3183 */
3184 Result += "\nstatic struct {\n";
3185 Result += "\tstruct _objc_protocol_list *next;\n";
3186 Result += "\tint protocol_count;\n";
3187 Result += "\tstruct _objc_protocol *class_protocols[";
3188 Result += utostr(Protocols.size());
3189 Result += "];\n} _OBJC_";
3190 Result += prefix;
3191 Result += "_PROTOCOLS_";
3192 Result += ClassName;
3193 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3194 "{\n\t0, ";
3195 Result += utostr(Protocols.size());
3196 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003197
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003198 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003199 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003200 Result += " \n";
Mike Stump1eb44332009-09-09 15:08:12 +00003201
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003202 for (unsigned i = 1; i != Protocols.size(); i++) {
3203 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003204 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003205 Result += "\n";
3206 }
3207 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003208}
3209
Steve Naroff621edce2009-04-29 16:37:50 +00003210
Mike Stump1eb44332009-09-09 15:08:12 +00003211/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003212/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003213void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003214 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003215 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003216 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003217 ObjCCategoryDecl *CDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00003218 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003219 CDecl = CDecl->getNextClassCategory())
3220 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3221 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003222
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003223 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003224 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003225 FullCategoryName += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003226
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003227 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003228 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003229 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003230
3231 // If any of our property implementations have associated getters or
3232 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003233 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3234 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003235 Prop != PropEnd; ++Prop) {
3236 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3237 continue;
3238 if (!(*Prop)->getPropertyIvarDecl())
3239 continue;
3240 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3241 if (!PD)
3242 continue;
3243 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3244 InstanceMethods.push_back(Getter);
3245 if (PD->isReadOnly())
3246 continue;
3247 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3248 InstanceMethods.push_back(Setter);
3249 }
3250 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003251 true, "CATEGORY_", FullCategoryName.c_str(),
3252 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003253
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003254 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003255 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003256 false, "CATEGORY_", FullCategoryName.c_str(),
3257 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003258
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003259 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003260 // Null CDecl is case of a category implementation with no category interface
3261 if (CDecl)
Steve Naroff621edce2009-04-29 16:37:50 +00003262 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3263 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003264 /* struct _objc_category {
3265 char *category_name;
3266 char *class_name;
3267 struct _objc_method_list *instance_methods;
3268 struct _objc_method_list *class_methods;
3269 struct _objc_protocol_list *protocols;
3270 // Objective-C 1.0 extensions
3271 uint32_t size; // sizeof (struct _objc_category)
Mike Stump1eb44332009-09-09 15:08:12 +00003272 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003273 // @property decl.
Mike Stump1eb44332009-09-09 15:08:12 +00003274 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003275 */
Mike Stump1eb44332009-09-09 15:08:12 +00003276
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003277 static bool objc_category = false;
3278 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003279 Result += "\nstruct _objc_category {\n";
3280 Result += "\tchar *category_name;\n";
3281 Result += "\tchar *class_name;\n";
3282 Result += "\tstruct _objc_method_list *instance_methods;\n";
3283 Result += "\tstruct _objc_method_list *class_methods;\n";
3284 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003285 Result += "\tunsigned int size;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003286 Result += "\tstruct _objc_property_list *instance_properties;\n";
3287 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003288 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003289 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003290 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3291 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003292 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003293 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003294 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003295 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003296 Result += "\"\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003297
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003298 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003299 Result += "\t, (struct _objc_method_list *)"
3300 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3301 Result += FullCategoryName;
3302 Result += "\n";
3303 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003304 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003305 Result += "\t, 0\n";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003306 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003307 Result += "\t, (struct _objc_method_list *)"
3308 "&_OBJC_CATEGORY_CLASS_METHODS_";
3309 Result += FullCategoryName;
3310 Result += "\n";
3311 }
3312 else
3313 Result += "\t, 0\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003314
Chris Lattnercafeb352009-02-20 18:18:36 +00003315 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003316 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003317 Result += FullCategoryName;
3318 Result += "\n";
3319 }
3320 else
3321 Result += "\t, 0\n";
3322 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003323}
3324
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003325/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3326/// ivar offset.
Mike Stump1eb44332009-09-09 15:08:12 +00003327void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
3328 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003329 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003330 if (ivar->isBitField()) {
3331 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3332 // place all bitfields at offset 0.
3333 Result += "0";
3334 } else {
3335 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003336 Result += IDecl->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003337 if (LangOpts.Microsoft)
3338 Result += "_IMPL";
3339 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003340 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003341 Result += ")";
3342 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003343}
3344
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003345//===----------------------------------------------------------------------===//
3346// Meta Data Emission
3347//===----------------------------------------------------------------------===//
3348
Steve Naroffb29b4272008-04-14 22:03:09 +00003349void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003350 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003351 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00003352
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003353 // Explictly declared @interface's are already synthesized.
Steve Naroff33feeb02009-04-20 20:09:33 +00003354 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003355 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003356 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003357 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003358 }
Mike Stump1eb44332009-09-09 15:08:12 +00003359
Chris Lattnerbe6df082007-12-12 07:56:42 +00003360 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003361 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump1eb44332009-09-09 15:08:12 +00003362 ? IDecl->ivar_size()
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003363 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003364 if (NumIvars > 0) {
3365 static bool objc_ivar = false;
3366 if (!objc_ivar) {
3367 /* struct _objc_ivar {
3368 char *ivar_name;
3369 char *ivar_type;
3370 int ivar_offset;
Mike Stump1eb44332009-09-09 15:08:12 +00003371 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003372 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003373 Result += "\nstruct _objc_ivar {\n";
3374 Result += "\tchar *ivar_name;\n";
3375 Result += "\tchar *ivar_type;\n";
3376 Result += "\tint ivar_offset;\n";
3377 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003378
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003379 objc_ivar = true;
3380 }
3381
Steve Naroff946a6932008-03-11 00:12:29 +00003382 /* struct {
3383 int ivar_count;
3384 struct _objc_ivar ivar_list[nIvars];
Mike Stump1eb44332009-09-09 15:08:12 +00003385 };
Steve Naroff946a6932008-03-11 00:12:29 +00003386 */
Mike Stump1eb44332009-09-09 15:08:12 +00003387 Result += "\nstatic struct {\n";
Steve Naroff946a6932008-03-11 00:12:29 +00003388 Result += "\tint ivar_count;\n";
3389 Result += "\tstruct _objc_ivar ivar_list[";
3390 Result += utostr(NumIvars);
3391 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003392 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003393 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003394 "{\n\t";
3395 Result += utostr(NumIvars);
3396 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003397
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003398 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003399 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003400 if (!IDecl->ivar_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003401 for (ObjCImplementationDecl::ivar_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003402 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003403 IV != IVEnd; ++IV)
3404 IVars.push_back(*IV);
3405 IVI = IVars.begin();
3406 IVE = IVars.end();
Chris Lattnerbe6df082007-12-12 07:56:42 +00003407 } else {
3408 IVI = CDecl->ivar_begin();
3409 IVE = CDecl->ivar_end();
3410 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003411 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003412 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003413 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003414 std::string TmpString, StrEncoding;
3415 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3416 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003417 Result += StrEncoding;
3418 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003419 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003420 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003421 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003422 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003423 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003424 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003425 std::string TmpString, StrEncoding;
3426 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3427 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003428 Result += StrEncoding;
3429 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003430 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003431 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003432 }
Mike Stump1eb44332009-09-09 15:08:12 +00003433
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003434 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003435 }
Mike Stump1eb44332009-09-09 15:08:12 +00003436
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003437 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003438 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003439 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003440
3441 // If any of our property implementations have associated getters or
3442 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003443 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3444 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003445 Prop != PropEnd; ++Prop) {
3446 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3447 continue;
3448 if (!(*Prop)->getPropertyIvarDecl())
3449 continue;
3450 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3451 if (!PD)
3452 continue;
3453 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3454 InstanceMethods.push_back(Getter);
3455 if (PD->isReadOnly())
3456 continue;
3457 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3458 InstanceMethods.push_back(Setter);
3459 }
3460 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003461 true, "", IDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003462
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003463 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003464 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003465 false, "", IDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003466
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003467 // Protocols referenced in class declaration?
Steve Naroff621edce2009-04-29 16:37:50 +00003468 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3469 "CLASS", CDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003470
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003471 // Declaration of class/meta-class metadata
3472 /* struct _objc_class {
3473 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003474 const char *super_class_name;
3475 char *name;
3476 long version;
3477 long info;
3478 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003479 struct _objc_ivar_list *ivars;
3480 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003481 struct objc_cache *cache;
3482 struct objc_protocol_list *protocols;
3483 const char *ivar_layout;
3484 struct _objc_class_ext *ext;
Mike Stump1eb44332009-09-09 15:08:12 +00003485 };
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003486 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003487 static bool objc_class = false;
3488 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003489 Result += "\nstruct _objc_class {\n";
3490 Result += "\tstruct _objc_class *isa;\n";
3491 Result += "\tconst char *super_class_name;\n";
3492 Result += "\tchar *name;\n";
3493 Result += "\tlong version;\n";
3494 Result += "\tlong info;\n";
3495 Result += "\tlong instance_size;\n";
3496 Result += "\tstruct _objc_ivar_list *ivars;\n";
3497 Result += "\tstruct _objc_method_list *methods;\n";
3498 Result += "\tstruct objc_cache *cache;\n";
3499 Result += "\tstruct _objc_protocol_list *protocols;\n";
3500 Result += "\tconst char *ivar_layout;\n";
3501 Result += "\tstruct _objc_class_ext *ext;\n";
3502 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003503 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003504 }
Mike Stump1eb44332009-09-09 15:08:12 +00003505
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003506 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003507 ObjCInterfaceDecl *RootClass = 0;
3508 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003509 while (SuperClass) {
3510 RootClass = SuperClass;
3511 SuperClass = SuperClass->getSuperClass();
3512 }
3513 SuperClass = CDecl->getSuperClass();
Mike Stump1eb44332009-09-09 15:08:12 +00003514
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003515 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003516 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003517 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003518 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003519 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003520 Result += "\"";
3521
3522 if (SuperClass) {
3523 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003524 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003525 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003526 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003527 Result += "\"";
3528 }
3529 else {
3530 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003531 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003532 Result += "\"";
3533 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003534 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003535 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003536 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003537 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff23f41272008-03-11 18:14:26 +00003538 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003539 Result += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003540 Result += "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003541 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003542 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003543 Result += ", 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00003544 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003545 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003546 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003547 Result += ",0,0\n";
3548 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003549 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003550 Result += "\t,0,0,0,0\n";
3551 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003552
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003553 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003554 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003555 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003556 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003557 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003558 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003559 if (SuperClass) {
3560 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003561 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003562 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003563 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003564 Result += "\"";
3565 }
3566 else {
3567 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003568 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003569 Result += "\"";
3570 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003571 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003572 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003573 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003574 Result += ",0";
3575 else {
3576 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003577 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003578 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003579 if (LangOpts.Microsoft)
3580 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003581 Result += ")";
3582 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003583 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003584 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003585 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003586 Result += "\n\t";
3587 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003588 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003589 Result += ",0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003590 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroff946a6932008-03-11 00:12:29 +00003591 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003592 Result += CDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003593 Result += ", 0\n\t";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003594 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003595 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003596 Result += ",0,0";
Chris Lattnercafeb352009-02-20 18:18:36 +00003597 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003598 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003599 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003600 Result += ", 0,0\n";
3601 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003602 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003603 Result += ",0,0,0\n";
3604 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003605}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003606
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003607/// RewriteImplementations - This routine rewrites all method implementations
3608/// and emits meta-data.
3609
Steve Narofface66252008-11-13 20:07:04 +00003610void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003611 int ClsDefCount = ClassImplementation.size();
3612 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003613
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003614 // Rewrite implemented methods
3615 for (int i = 0; i < ClsDefCount; i++)
3616 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00003617
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003618 for (int i = 0; i < CatDefCount; i++)
3619 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003620}
Mike Stump1eb44332009-09-09 15:08:12 +00003621
Steve Narofface66252008-11-13 20:07:04 +00003622void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3623 int ClsDefCount = ClassImplementation.size();
3624 int CatDefCount = CategoryImplementation.size();
3625
Steve Naroff5df5b762008-05-07 21:23:49 +00003626 // This is needed for determining instance variable offsets.
Fariborz Jahanianc98cbb42010-01-07 18:31:42 +00003627 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003628 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003629 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003630 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003631
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003632 // For each implemented category, write out all its meta data.
3633 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003634 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroff621edce2009-04-29 16:37:50 +00003635
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003636 // Write objc_symtab metadata
3637 /*
3638 struct _objc_symtab
3639 {
3640 long sel_ref_cnt;
3641 SEL *refs;
3642 short cls_def_cnt;
3643 short cat_def_cnt;
3644 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump1eb44332009-09-09 15:08:12 +00003645 };
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003646 */
Mike Stump1eb44332009-09-09 15:08:12 +00003647
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003648 Result += "\nstruct _objc_symtab {\n";
3649 Result += "\tlong sel_ref_cnt;\n";
3650 Result += "\tSEL *refs;\n";
3651 Result += "\tshort cls_def_cnt;\n";
3652 Result += "\tshort cat_def_cnt;\n";
3653 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3654 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003655
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003656 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003657 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003658 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003659 + ", " + utostr(CatDefCount) + "\n";
3660 for (int i = 0; i < ClsDefCount; i++) {
3661 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003662 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003663 Result += "\n";
3664 }
Mike Stump1eb44332009-09-09 15:08:12 +00003665
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003666 for (int i = 0; i < CatDefCount; i++) {
3667 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003668 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003669 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003670 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003671 Result += "\n";
3672 }
Mike Stump1eb44332009-09-09 15:08:12 +00003673
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003674 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003675
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003676 // Write objc_module metadata
Mike Stump1eb44332009-09-09 15:08:12 +00003677
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003678 /*
3679 struct _objc_module {
3680 long version;
3681 long size;
3682 const char *name;
3683 struct _objc_symtab *symtab;
3684 }
3685 */
Mike Stump1eb44332009-09-09 15:08:12 +00003686
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003687 Result += "\nstruct _objc_module {\n";
3688 Result += "\tlong version;\n";
3689 Result += "\tlong size;\n";
3690 Result += "\tconst char *name;\n";
3691 Result += "\tstruct _objc_symtab *symtab;\n";
3692 Result += "};\n\n";
3693 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003694 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003695 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003696 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003697 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003698
3699 if (LangOpts.Microsoft) {
Steve Naroff621edce2009-04-29 16:37:50 +00003700 if (ProtocolExprDecls.size()) {
3701 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
3702 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003703 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00003704 E = ProtocolExprDecls.end(); I != E; ++I) {
3705 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
3706 Result += (*I)->getNameAsString();
3707 Result += " = &_OBJC_PROTOCOL_";
3708 Result += (*I)->getNameAsString();
3709 Result += ";\n";
3710 }
3711 Result += "#pragma data_seg(pop)\n\n";
3712 }
Steve Naroff4f943c22008-03-10 20:43:59 +00003713 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003714 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003715 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3716 Result += "&_OBJC_MODULES;\n";
3717 Result += "#pragma data_seg(pop)\n\n";
3718 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003719}
Chris Lattner311ff022007-10-16 22:36:42 +00003720
Steve Naroff54055232008-10-27 17:20:55 +00003721std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3722 const char *funcName,
3723 std::string Tag) {
3724 const FunctionType *AFT = CE->getFunctionType();
3725 QualType RT = AFT->getResultType();
3726 std::string StructRef = "struct " + Tag;
3727 std::string S = "static " + RT.getAsString() + " __" +
3728 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003729
Steve Naroff54055232008-10-27 17:20:55 +00003730 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00003731
Douglas Gregor72564e72009-02-26 23:50:07 +00003732 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003733 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00003734 // block (to reference imported block decl refs).
3735 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00003736 } else if (BD->param_empty()) {
3737 S += "(" + StructRef + " *__cself)";
3738 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003739 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00003740 assert(FT && "SynthesizeBlockFunc: No function proto");
3741 S += '(';
3742 // first add the implicit argument.
3743 S += StructRef + " *__cself, ";
3744 std::string ParamStr;
3745 for (BlockDecl::param_iterator AI = BD->param_begin(),
3746 E = BD->param_end(); AI != E; ++AI) {
3747 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003748 ParamStr = (*AI)->getNameAsString();
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00003749 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00003750 S += ParamStr;
3751 }
3752 if (FT->isVariadic()) {
3753 if (!BD->param_empty()) S += ", ";
3754 S += "...";
3755 }
3756 S += ')';
3757 }
3758 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003759
Steve Naroff54055232008-10-27 17:20:55 +00003760 // Create local declarations to avoid rewriting all closure decl ref exprs.
3761 // First, emit a declaration for all "by ref" decls.
Mike Stump1eb44332009-09-09 15:08:12 +00003762 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003763 E = BlockByRefDecls.end(); I != E; ++I) {
3764 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003765 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003766 std::string TypeString = "struct __Block_byref_" + Name + " *";
3767 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003768 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003769 }
Steve Naroff54055232008-10-27 17:20:55 +00003770 // Next, emit a declaration for all "by copy" declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00003771 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003772 E = BlockByCopyDecls.end(); I != E; ++I) {
3773 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003774 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003775 // Handle nested closure invocation. For example:
3776 //
3777 // void (^myImportedClosure)(void);
3778 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003779 //
Steve Naroff54055232008-10-27 17:20:55 +00003780 // void (^anotherClosure)(void);
3781 // anotherClosure = ^(void) {
3782 // myImportedClosure(); // import and invoke the closure
3783 // };
3784 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003785 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003786 S += "struct __block_impl *";
3787 else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00003788 (*I)->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003789 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff54055232008-10-27 17:20:55 +00003790 }
3791 std::string RewrittenStr = RewrittenBlockExprs[CE];
3792 const char *cstr = RewrittenStr.c_str();
3793 while (*cstr++ != '{') ;
3794 S += cstr;
3795 S += "\n";
3796 return S;
3797}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003798
Steve Naroff54055232008-10-27 17:20:55 +00003799std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3800 const char *funcName,
3801 std::string Tag) {
3802 std::string StructRef = "struct " + Tag;
3803 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00003804
Steve Naroff54055232008-10-27 17:20:55 +00003805 S += funcName;
3806 S += "_block_copy_" + utostr(i);
3807 S += "(" + StructRef;
3808 S += "*dst, " + StructRef;
3809 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00003810 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003811 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00003812 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003813 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00003814 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003815 S += (*I)->getNameAsString();
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003816 if (BlockByRefDecls.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003817 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003818 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003819 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003820 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003821 S += "}\n";
3822
Steve Naroff54055232008-10-27 17:20:55 +00003823 S += "\nstatic void __";
3824 S += funcName;
3825 S += "_block_dispose_" + utostr(i);
3826 S += "(" + StructRef;
3827 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00003828 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003829 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00003830 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003831 S += (*I)->getNameAsString();
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003832 if (BlockByRefDecls.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003833 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003834 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003835 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003836 }
Mike Stump1eb44332009-09-09 15:08:12 +00003837 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00003838 return S;
3839}
3840
Steve Naroff01aec112009-12-06 21:14:13 +00003841std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3842 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00003843 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003844 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00003845
Steve Naroff54055232008-10-27 17:20:55 +00003846 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003847 S += " struct " + Desc;
3848 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003849
Steve Naroff01aec112009-12-06 21:14:13 +00003850 Constructor += "(void *fp, "; // Invoke function pointer.
3851 Constructor += "struct " + Desc; // Descriptor pointer.
3852 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00003853
Steve Naroff54055232008-10-27 17:20:55 +00003854 if (BlockDeclRefs.size()) {
3855 // Output all "by copy" declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00003856 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003857 E = BlockByCopyDecls.end(); I != E; ++I) {
3858 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003859 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003860 std::string ArgName = "_" + FieldName;
3861 // Handle nested closure invocation. For example:
3862 //
3863 // void (^myImportedBlock)(void);
3864 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003865 //
Steve Naroff54055232008-10-27 17:20:55 +00003866 // void (^anotherBlock)(void);
3867 // anotherBlock = ^(void) {
3868 // myImportedBlock(); // import and invoke the closure
3869 // };
3870 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003871 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003872 S += "struct __block_impl *";
3873 Constructor += ", void *" + ArgName;
3874 } else {
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00003875 (*I)->getType().getAsStringInternal(FieldName, Context->PrintingPolicy);
3876 (*I)->getType().getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00003877 Constructor += ", " + ArgName;
3878 }
3879 S += FieldName + ";\n";
3880 }
3881 // Output all "by ref" declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00003882 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003883 E = BlockByRefDecls.end(); I != E; ++I) {
3884 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003885 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003886 std::string ArgName = "_" + FieldName;
3887 // Handle nested closure invocation. For example:
3888 //
3889 // void (^myImportedBlock)(void);
3890 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003891 //
Steve Naroff54055232008-10-27 17:20:55 +00003892 // void (^anotherBlock)(void);
3893 // anotherBlock = ^(void) {
3894 // myImportedBlock(); // import and invoke the closure
3895 // };
3896 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003897 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003898 S += "struct __block_impl *";
3899 Constructor += ", void *" + ArgName;
3900 } else {
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003901 std::string TypeString = "struct __Block_byref_" + FieldName;
3902 TypeString += " *";
3903 FieldName = TypeString + FieldName;
3904 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00003905 Constructor += ", " + ArgName;
3906 }
3907 S += FieldName + "; // by ref\n";
3908 }
3909 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00003910 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003911 if (GlobalVarDecl)
3912 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3913 else
3914 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003915 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003916
Steve Naroff01aec112009-12-06 21:14:13 +00003917 Constructor += " Desc = desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003918
Steve Naroff54055232008-10-27 17:20:55 +00003919 // Initialize all "by copy" arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00003920 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003921 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003922 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003923 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003924 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003925 Constructor += Name + " = (struct __block_impl *)_";
3926 else
3927 Constructor += Name + " = _";
3928 Constructor += Name + ";\n";
3929 }
3930 // Initialize all "by ref" arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00003931 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003932 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003933 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003934 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003935 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003936 Constructor += Name + " = (struct __block_impl *)_";
3937 else
3938 Constructor += Name + " = _";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003939 Constructor += Name + "->__forwarding;\n";
Steve Naroff54055232008-10-27 17:20:55 +00003940 }
3941 } else {
3942 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00003943 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003944 if (GlobalVarDecl)
3945 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3946 else
3947 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003948 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3949 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00003950 }
3951 Constructor += " ";
3952 Constructor += "}\n";
3953 S += Constructor;
3954 S += "};\n";
3955 return S;
3956}
3957
Steve Naroff01aec112009-12-06 21:14:13 +00003958std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
3959 std::string ImplTag, int i,
3960 const char *FunName,
3961 unsigned hasCopy) {
3962 std::string S = "\nstatic struct " + DescTag;
3963
3964 S += " {\n unsigned long reserved;\n";
3965 S += " unsigned long Block_size;\n";
3966 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00003967 S += " void (*copy)(struct ";
3968 S += ImplTag; S += "*, struct ";
3969 S += ImplTag; S += "*);\n";
3970
3971 S += " void (*dispose)(struct ";
3972 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003973 }
3974 S += "} ";
3975
3976 S += DescTag + "_DATA = { 0, sizeof(struct ";
3977 S += ImplTag + ")";
3978 if (hasCopy) {
3979 S += ", __" + std::string(FunName) + "_block_copy_" + utostr(i);
3980 S += ", __" + std::string(FunName) + "_block_dispose_" + utostr(i);
3981 }
3982 S += "};\n";
3983 return S;
3984}
3985
Steve Naroff54055232008-10-27 17:20:55 +00003986void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3987 const char *FunName) {
3988 // Insert closures that were part of the function.
3989 for (unsigned i = 0; i < Blocks.size(); i++) {
3990
3991 CollectBlockDeclRefInfo(Blocks[i]);
3992
Steve Naroff01aec112009-12-06 21:14:13 +00003993 std::string ImplTag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3994 std::string DescTag = "__" + std::string(FunName) + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00003995
Steve Naroff01aec112009-12-06 21:14:13 +00003996 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00003997
3998 InsertText(FunLocStart, CI.c_str(), CI.size());
3999
Steve Naroff01aec112009-12-06 21:14:13 +00004000 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00004001
Steve Naroff54055232008-10-27 17:20:55 +00004002 InsertText(FunLocStart, CF.c_str(), CF.size());
4003
4004 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00004005 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Steve Naroff54055232008-10-27 17:20:55 +00004006 InsertText(FunLocStart, HF.c_str(), HF.size());
4007 }
Steve Naroff01aec112009-12-06 21:14:13 +00004008 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4009 ImportedBlockDecls.size() > 0);
4010 InsertText(FunLocStart, BD.c_str(), BD.size());
Mike Stump1eb44332009-09-09 15:08:12 +00004011
Steve Naroff54055232008-10-27 17:20:55 +00004012 BlockDeclRefs.clear();
4013 BlockByRefDecls.clear();
4014 BlockByCopyDecls.clear();
4015 BlockCallExprs.clear();
4016 ImportedBlockDecls.clear();
4017 }
4018 Blocks.clear();
4019 RewrittenBlockExprs.clear();
4020}
4021
4022void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4023 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner8ec03f52008-11-24 03:54:41 +00004024 const char *FuncName = FD->getNameAsCString();
Mike Stump1eb44332009-09-09 15:08:12 +00004025
Steve Naroff54055232008-10-27 17:20:55 +00004026 SynthesizeBlockLiterals(FunLocStart, FuncName);
4027}
4028
4029void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00004030 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4031 //SourceLocation FunLocStart = MD->getLocStart();
4032 // FIXME: This hack works around a bug in Rewrite.InsertText().
4033 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattner077bf5e2008-11-24 03:33:13 +00004034 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004035 // Convert colons to underscores.
4036 std::string::size_type loc = 0;
4037 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4038 FuncName.replace(loc, 1, "_");
Mike Stump1eb44332009-09-09 15:08:12 +00004039
Steve Naroff54055232008-10-27 17:20:55 +00004040 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
4041}
4042
4043void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4044 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4045 CI != E; ++CI)
4046 if (*CI) {
4047 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4048 GetBlockDeclRefExprs(CBE->getBody());
4049 else
4050 GetBlockDeclRefExprs(*CI);
4051 }
4052 // Handle specific things.
4053 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
4054 // FIXME: Handle enums.
4055 if (!isa<FunctionDecl>(CDRE->getDecl()))
4056 BlockDeclRefs.push_back(CDRE);
4057 return;
4058}
4059
4060void RewriteObjC::GetBlockCallExprs(Stmt *S) {
4061 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4062 CI != E; ++CI)
4063 if (*CI) {
4064 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4065 GetBlockCallExprs(CBE->getBody());
4066 else
4067 GetBlockCallExprs(*CI);
4068 }
Mike Stump1eb44332009-09-09 15:08:12 +00004069
Steve Naroff54055232008-10-27 17:20:55 +00004070 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4071 if (CE->getCallee()->getType()->isBlockPointerType()) {
4072 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
4073 }
4074 }
4075 return;
4076}
4077
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004078Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00004079 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00004080 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004081
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004082 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004083 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004084 } else if (const BlockDeclRefExpr *CDRE =
4085 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004086 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004087 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004088 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004089 }
4090 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4091 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4092 }
4093 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4094 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4095 else if (const ConditionalOperator *CEXPR =
4096 dyn_cast<ConditionalOperator>(BlockExp)) {
4097 Expr *LHSExp = CEXPR->getLHS();
4098 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4099 Expr *RHSExp = CEXPR->getRHS();
4100 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4101 Expr *CONDExp = CEXPR->getCond();
4102 ConditionalOperator *CondExpr =
4103 new (Context) ConditionalOperator(CONDExp,
4104 SourceLocation(), cast<Expr>(LHSStmt),
4105 SourceLocation(), cast<Expr>(RHSStmt),
4106 Exp->getType());
4107 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00004108 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4109 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004110 } else {
4111 assert(1 && "RewriteBlockClass: Bad type");
4112 }
4113 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00004114 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00004115 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00004116 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00004117 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004118
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004119 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4120 SourceLocation(),
4121 &Context->Idents.get("__block_impl"));
4122 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00004123
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004124 // Generate a funky cast.
4125 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004126
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004127 // Push the block argument type.
4128 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00004129 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004130 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004131 E = FTP->arg_type_end(); I && (I != E); ++I) {
4132 QualType t = *I;
4133 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004134 if (isTopLevelBlockPointerType(t)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004135 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004136 t = Context->getPointerType(BPT->getPointeeType());
4137 }
4138 ArgTypes.push_back(t);
4139 }
Steve Naroff54055232008-10-27 17:20:55 +00004140 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004141 // Now do the pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00004142 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004143 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00004144
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004145 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00004146
4147 CastExpr *BlkCast = new (Context) CStyleCastExpr(PtrBlock,
Anders Carlssoncdef2b72009-07-31 00:48:10 +00004148 CastExpr::CK_Unknown,
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004149 const_cast<Expr*>(BlockExp),
Ted Kremenek8189cde2009-02-07 01:47:29 +00004150 PtrBlock, SourceLocation(),
4151 SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004152 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004153 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4154 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004155 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00004156
Douglas Gregor44b43212008-12-11 16:49:14 +00004157 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00004158 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004159 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004160 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4161 FD->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00004162
Anders Carlssoncdef2b72009-07-31 00:48:10 +00004163 CastExpr *FunkCast = new (Context) CStyleCastExpr(PtrToFuncCastType,
4164 CastExpr::CK_Unknown, ME,
Ted Kremenek8189cde2009-02-07 01:47:29 +00004165 PtrToFuncCastType,
4166 SourceLocation(),
4167 SourceLocation());
4168 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00004169
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004170 llvm::SmallVector<Expr*, 8> BlkExprs;
4171 // Add the implicit argument.
4172 BlkExprs.push_back(BlkCast);
4173 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004174 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004175 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004176 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00004177 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004178 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4179 BlkExprs.size(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00004180 Exp->getType(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004181 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00004182}
4183
4184void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004185 Stmt *BlockCall = SynthesizeBlockCall(Exp, Exp->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004186 ReplaceStmt(Exp, BlockCall);
Steve Naroff54055232008-10-27 17:20:55 +00004187}
4188
Steve Naroff621edce2009-04-29 16:37:50 +00004189// We need to return the rewritten expression to handle cases where the
4190// BlockDeclRefExpr is embedded in another expression being rewritten.
4191// For example:
4192//
4193// int main() {
4194// __block Foo *f;
4195// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00004196//
Steve Naroff621edce2009-04-29 16:37:50 +00004197// void (^myblock)() = ^() {
4198// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4199// i = 77;
4200// };
4201//}
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004202Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00004203 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004204 // for each DeclRefExp where BYREFVAR is name of the variable.
4205 ValueDecl *VD;
4206 bool isArrow = true;
4207 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4208 VD = BDRE->getDecl();
4209 else {
4210 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4211 isArrow = false;
4212 }
4213
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004214 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4215 &Context->Idents.get("__forwarding"),
4216 Context->VoidPtrTy, 0,
4217 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004218 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4219 FD, SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004220 FD->getType());
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004221
4222 const char *Name = VD->getNameAsCString();
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004223 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4224 &Context->Idents.get(Name),
4225 Context->VoidPtrTy, 0,
4226 /*BitWidth=*/0, /*Mutable=*/true);
4227 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004228 DeclRefExp->getType());
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004229
4230
4231
Steve Naroffdf8570d2009-02-02 17:19:26 +00004232 // Need parens to enforce precedence.
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004233 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4234 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004235 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00004236 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00004237}
4238
Steve Naroffb2f9e512008-11-03 23:29:32 +00004239void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4240 SourceLocation LocStart = CE->getLParenLoc();
4241 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00004242
4243 // Need to avoid trying to rewrite synthesized casts.
4244 if (LocStart.isInvalid())
4245 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004246 // Need to avoid trying to rewrite casts contained in macros.
4247 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4248 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004249
Steve Naroff54055232008-10-27 17:20:55 +00004250 const char *startBuf = SM->getCharacterData(LocStart);
4251 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00004252
Steve Naroff54055232008-10-27 17:20:55 +00004253 // advance the location to startArgList.
4254 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004255
Steve Naroff54055232008-10-27 17:20:55 +00004256 while (*argPtr++ && (argPtr < endBuf)) {
4257 switch (*argPtr) {
Mike Stump1eb44332009-09-09 15:08:12 +00004258 case '^':
Steve Naroff54055232008-10-27 17:20:55 +00004259 // Replace the '^' with '*'.
4260 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
4261 ReplaceText(LocStart, 1, "*", 1);
4262 break;
4263 }
4264 }
4265 return;
4266}
4267
4268void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4269 SourceLocation DeclLoc = FD->getLocation();
4270 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004271
Steve Naroff54055232008-10-27 17:20:55 +00004272 // We have 1 or more arguments that have closure pointers.
4273 const char *startBuf = SM->getCharacterData(DeclLoc);
4274 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004275
Steve Naroff54055232008-10-27 17:20:55 +00004276 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004277
Steve Naroff54055232008-10-27 17:20:55 +00004278 parenCount++;
4279 // advance the location to startArgList.
4280 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4281 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004282
Steve Naroff54055232008-10-27 17:20:55 +00004283 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004284
Steve Naroff54055232008-10-27 17:20:55 +00004285 while (*argPtr++ && parenCount) {
4286 switch (*argPtr) {
Mike Stump1eb44332009-09-09 15:08:12 +00004287 case '^':
Steve Naroff54055232008-10-27 17:20:55 +00004288 // Replace the '^' with '*'.
4289 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
4290 ReplaceText(DeclLoc, 1, "*", 1);
4291 break;
Mike Stump1eb44332009-09-09 15:08:12 +00004292 case '(':
4293 parenCount++;
Steve Naroff54055232008-10-27 17:20:55 +00004294 break;
Mike Stump1eb44332009-09-09 15:08:12 +00004295 case ')':
Steve Naroff54055232008-10-27 17:20:55 +00004296 parenCount--;
4297 break;
4298 }
4299 }
4300 return;
4301}
4302
4303bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004304 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004305 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004306 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004307 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004308 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004309 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004310 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004311 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004312 }
4313 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004314 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004315 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004316 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004317 return true;
4318 }
4319 return false;
4320}
4321
Ted Kremenek8189cde2009-02-07 01:47:29 +00004322void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4323 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004324 const char *argPtr = strchr(Name, '(');
4325 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004326
Steve Naroff54055232008-10-27 17:20:55 +00004327 LParen = argPtr; // output the start.
4328 argPtr++; // skip past the left paren.
4329 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004330
Steve Naroff54055232008-10-27 17:20:55 +00004331 while (*argPtr && parenCount) {
4332 switch (*argPtr) {
4333 case '(': parenCount++; break;
4334 case ')': parenCount--; break;
4335 default: break;
4336 }
4337 if (parenCount) argPtr++;
4338 }
4339 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4340 RParen = argPtr; // output the end
4341}
4342
4343void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4344 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4345 RewriteBlockPointerFunctionArgs(FD);
4346 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004347 }
Steve Naroff54055232008-10-27 17:20:55 +00004348 // Handle Variables and Typedefs.
4349 SourceLocation DeclLoc = ND->getLocation();
4350 QualType DeclT;
4351 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4352 DeclT = VD->getType();
4353 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4354 DeclT = TDD->getUnderlyingType();
4355 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4356 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004357 else
Steve Naroff54055232008-10-27 17:20:55 +00004358 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00004359
Steve Naroff54055232008-10-27 17:20:55 +00004360 const char *startBuf = SM->getCharacterData(DeclLoc);
4361 const char *endBuf = startBuf;
4362 // scan backward (from the decl location) for the end of the previous decl.
4363 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4364 startBuf--;
Mike Stump1eb44332009-09-09 15:08:12 +00004365
Steve Naroff54055232008-10-27 17:20:55 +00004366 // *startBuf != '^' if we are dealing with a pointer to function that
4367 // may take block argument types (which will be handled below).
4368 if (*startBuf == '^') {
4369 // Replace the '^' with '*', computing a negative offset.
4370 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4371 ReplaceText(DeclLoc, 1, "*", 1);
4372 }
4373 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4374 // Replace the '^' with '*' for arguments.
4375 DeclLoc = ND->getLocation();
4376 startBuf = SM->getCharacterData(DeclLoc);
4377 const char *argListBegin, *argListEnd;
4378 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4379 while (argListBegin < argListEnd) {
4380 if (*argListBegin == '^') {
4381 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4382 ReplaceText(CaretLoc, 1, "*", 1);
4383 }
4384 argListBegin++;
4385 }
4386 }
4387 return;
4388}
4389
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004390
4391/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4392/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4393/// struct Block_byref_id_object *src) {
4394/// _Block_object_assign (&_dest->object, _src->object,
4395/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4396/// [|BLOCK_FIELD_IS_WEAK]) // object
4397/// _Block_object_assign(&_dest->object, _src->object,
4398/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4399/// [|BLOCK_FIELD_IS_WEAK]) // block
4400/// }
4401/// And:
4402/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4403/// _Block_object_dispose(_src->object,
4404/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4405/// [|BLOCK_FIELD_IS_WEAK]) // object
4406/// _Block_object_dispose(_src->object,
4407/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4408/// [|BLOCK_FIELD_IS_WEAK]) // block
4409/// }
4410
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004411std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4412 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004413 std::string S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004414 if (CopyDestroyCache.count(flag) > 0)
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004415 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004416 CopyDestroyCache.insert(flag);
4417 S = "static void __Block_byref_id_object_copy_";
4418 S += utostr(flag);
4419 S += "(void *dst, void *src) {\n";
4420
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004421 // offset into the object pointer is computed as:
4422 // void * + void* + int + int + void* + void *
4423 unsigned IntSize =
4424 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4425 unsigned VoidPtrSize =
4426 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4427
4428 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
4429 S += " _Block_object_assign((char*)dst + ";
4430 S += utostr(offset);
4431 S += ", *(void * *) ((char*)src + ";
4432 S += utostr(offset);
4433 S += "), ";
4434 S += utostr(flag);
4435 S += ");\n}\n";
4436
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004437 S += "static void __Block_byref_id_object_dispose_";
4438 S += utostr(flag);
4439 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004440 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4441 S += utostr(offset);
4442 S += "), ";
4443 S += utostr(flag);
4444 S += ");\n}\n";
4445 return S;
4446}
4447
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004448/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4449/// the declaration into:
4450/// struct __Block_byref_ND {
4451/// void *__isa; // NULL for everything except __weak pointers
4452/// struct __Block_byref_ND *__forwarding;
4453/// int32_t __flags;
4454/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004455/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4456/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004457/// typex ND;
4458/// };
4459///
4460/// It then replaces declaration of ND variable with:
4461/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4462/// __size=sizeof(struct __Block_byref_ND),
4463/// ND=initializer-if-any};
4464///
4465///
4466void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004467 int flag = 0;
4468 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004469 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4470 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00004471 SourceLocation X = ND->getLocEnd();
4472 X = SM->getInstantiationLoc(X);
4473 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004474 std::string Name(ND->getNameAsString());
4475 std::string ByrefType = "struct __Block_byref_";
4476 ByrefType += Name;
4477 ByrefType += " {\n";
4478 ByrefType += " void *__isa;\n";
4479 ByrefType += " struct __Block_byref_" + Name + " *__forwarding;\n";
4480 ByrefType += " int __flags;\n";
4481 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004482 // Add void *__Block_byref_id_object_copy;
4483 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004484 QualType Ty = ND->getType();
4485 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4486 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004487 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4488 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004489 }
4490
4491 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004492 ByrefType += " " + Name + ";\n";
4493 ByrefType += "};\n";
4494 // Insert this type in global scope. It is needed by helper function.
4495 assert(CurFunctionDef && "RewriteByRefVar - CurFunctionDef is null");
4496 SourceLocation FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4497 InsertText(FunLocStart, ByrefType.c_str(), ByrefType.size());
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004498 if (Ty.isObjCGCWeak()) {
4499 flag |= BLOCK_FIELD_IS_WEAK;
4500 isa = 1;
4501 }
4502
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004503 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004504 flag = BLOCK_BYREF_CALLER;
4505 QualType Ty = ND->getType();
4506 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4507 if (Ty->isBlockPointerType())
4508 flag |= BLOCK_FIELD_IS_BLOCK;
4509 else
4510 flag |= BLOCK_FIELD_IS_OBJECT;
4511 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004512 if (!HF.empty())
4513 InsertText(FunLocStart, HF.c_str(), HF.size());
4514 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004515
4516 // struct __Block_byref_ND ND =
4517 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4518 // initializer-if-any};
4519 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00004520 unsigned flags = 0;
4521 if (HasCopyAndDispose)
4522 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004523 Name = ND->getNameAsString();
4524 ByrefType = "struct __Block_byref_" + Name;
4525 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004526 ByrefType += " " + Name + " = {(void*)";
4527 ByrefType += utostr(isa);
4528 ByrefType += ", &" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004529 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004530 ByrefType += ", ";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004531 ByrefType += "sizeof(struct __Block_byref_" + Name + ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004532 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004533 ByrefType += ", __Block_byref_id_object_copy_";
4534 ByrefType += utostr(flag);
4535 ByrefType += ", __Block_byref_id_object_dispose_";
4536 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004537 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004538 ByrefType += "};\n";
4539 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(),
4540 ByrefType.c_str(), ByrefType.size());
4541 }
4542 else {
4543 SourceLocation startLoc = ND->getInit()->getLocStart();
Fariborz Jahanian791b10d2010-01-05 23:06:29 +00004544 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004545 ByrefType += " " + Name;
4546 ReplaceText(DeclLoc, endBuf-startBuf,
4547 ByrefType.c_str(), ByrefType.size());
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004548 ByrefType = " = {(void*)";
4549 ByrefType += utostr(isa);
4550 ByrefType += ", &" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004551 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004552 ByrefType += ", ";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004553 ByrefType += "sizeof(struct __Block_byref_" + Name + "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004554 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004555 ByrefType += "__Block_byref_id_object_copy_";
4556 ByrefType += utostr(flag);
4557 ByrefType += ", __Block_byref_id_object_dispose_";
4558 ByrefType += utostr(flag);
4559 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004560 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004561 InsertText(startLoc, ByrefType.c_str(), ByrefType.size());
Steve Naroffc5143c52009-12-23 17:24:33 +00004562
4563 // Complete the newly synthesized compound expression by inserting a right
4564 // curly brace before the end of the declaration.
4565 // FIXME: This approach avoids rewriting the initializer expression. It
4566 // also assumes there is only one declarator. For example, the following
4567 // isn't currently supported by this routine (in general):
4568 //
4569 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4570 //
4571 const char *startBuf = SM->getCharacterData(startLoc);
4572 const char *semiBuf = strchr(startBuf, ';');
4573 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4574 SourceLocation semiLoc =
4575 startLoc.getFileLocWithOffset(semiBuf-startBuf);
4576
4577 InsertText(semiLoc, "}", 1);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004578 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00004579 return;
4580}
4581
Mike Stump1eb44332009-09-09 15:08:12 +00004582void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00004583 // Add initializers for any closure decl refs.
4584 GetBlockDeclRefExprs(Exp->getBody());
4585 if (BlockDeclRefs.size()) {
4586 // Unique all "by copy" declarations.
4587 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4588 if (!BlockDeclRefs[i]->isByRef())
4589 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
4590 // Unique all "by ref" declarations.
4591 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4592 if (BlockDeclRefs[i]->isByRef()) {
4593 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4594 }
4595 // Find any imported blocks...they will need special attention.
4596 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004597 if (BlockDeclRefs[i]->isByRef() ||
4598 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4599 BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroff00072682008-11-13 17:40:07 +00004600 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff54055232008-10-27 17:20:55 +00004601 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4602 }
4603 }
4604}
4605
Steve Narofffa15fd92008-10-28 20:29:00 +00004606FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4607 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00004608 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump1eb44332009-09-09 15:08:12 +00004609 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004610 ID, FType, 0, FunctionDecl::Extern, false,
Douglas Gregor2224f842009-02-25 16:33:18 +00004611 false);
Steve Narofffa15fd92008-10-28 20:29:00 +00004612}
4613
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004614Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004615 Blocks.push_back(Exp);
4616
4617 CollectBlockDeclRefInfo(Exp);
4618 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00004619
Steve Narofffa15fd92008-10-28 20:29:00 +00004620 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00004621 FuncName = CurFunctionDef->getNameAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00004622 else if (CurMethodDef) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00004623 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00004624 // Convert colons to underscores.
4625 std::string::size_type loc = 0;
4626 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4627 FuncName.replace(loc, 1, "_");
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004628 } else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004629 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00004630
Steve Narofffa15fd92008-10-28 20:29:00 +00004631 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00004632
Steve Narofffa15fd92008-10-28 20:29:00 +00004633 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4634 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00004635
Steve Narofffa15fd92008-10-28 20:29:00 +00004636 // Get a pointer to the function type so we can cast appropriately.
4637 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4638
4639 FunctionDecl *FD;
4640 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00004641
Steve Narofffa15fd92008-10-28 20:29:00 +00004642 // Simulate a contructor call...
4643 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004644 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004645
Steve Narofffa15fd92008-10-28 20:29:00 +00004646 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00004647
Steve Narofffdc03722008-10-29 21:23:59 +00004648 // Initialize the block function.
Steve Narofffa15fd92008-10-28 20:29:00 +00004649 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004650 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4651 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004652 CastExpr *castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4653 CastExpr::CK_Unknown, Arg,
Ted Kremenek8189cde2009-02-07 01:47:29 +00004654 Context->VoidPtrTy, SourceLocation(),
4655 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004656 InitExprs.push_back(castExpr);
4657
Steve Naroff01aec112009-12-06 21:14:13 +00004658 // Initialize the block descriptor.
4659 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00004660
Steve Naroff01aec112009-12-06 21:14:13 +00004661 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
4662 &Context->Idents.get(DescData.c_str()),
4663 Context->VoidPtrTy, 0,
4664 VarDecl::Static);
4665 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
4666 new (Context) DeclRefExpr(NewVD,
4667 Context->VoidPtrTy, SourceLocation()),
4668 UnaryOperator::AddrOf,
4669 Context->getPointerType(Context->VoidPtrTy),
4670 SourceLocation());
4671 InitExprs.push_back(DescRefExpr);
4672
Steve Narofffa15fd92008-10-28 20:29:00 +00004673 // Add initializers for any closure decl refs.
4674 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00004675 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00004676 // Output all "by copy" declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00004677 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004678 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004679 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00004680 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner8ec03f52008-11-24 03:54:41 +00004681 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004682 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004683 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004684 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004685 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004686 Exp = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4687 CastExpr::CK_Unknown, Arg,
4688 Context->VoidPtrTy,
Anders Carlssoncdef2b72009-07-31 00:48:10 +00004689 SourceLocation(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00004690 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004691 } else {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004692 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004693 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004694 }
Mike Stump1eb44332009-09-09 15:08:12 +00004695 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004696 }
4697 // Output all "by ref" declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00004698 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004699 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004700 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004701 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4702 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00004703 Context->getPointerType(Exp->getType()),
Steve Narofffdc03722008-10-29 21:23:59 +00004704 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004705 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004706 }
4707 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00004708 if (ImportedBlockDecls.size()) {
4709 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4710 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00004711 unsigned IntSize =
4712 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanianff127882009-12-23 21:52:32 +00004713 Expr *FlagExp = new (Context) IntegerLiteral(llvm::APInt(IntSize, flag),
4714 Context->IntTy, SourceLocation());
4715 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00004716 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004717 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4718 FType, SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004719 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00004720 Context->getPointerType(NewRep->getType()),
Steve Narofffa15fd92008-10-28 20:29:00 +00004721 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004722 NewRep = new (Context) CStyleCastExpr(FType, CastExpr::CK_Unknown, NewRep,
Anders Carlssoncdef2b72009-07-31 00:48:10 +00004723 FType, SourceLocation(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00004724 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004725 BlockDeclRefs.clear();
4726 BlockByRefDecls.clear();
4727 BlockByCopyDecls.clear();
4728 ImportedBlockDecls.clear();
4729 return NewRep;
4730}
4731
4732//===----------------------------------------------------------------------===//
4733// Function Body / Expression rewriting
4734//===----------------------------------------------------------------------===//
4735
Steve Naroffc77a6362008-12-04 16:24:46 +00004736// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4737// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4738// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4739// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4740// Since the rewriter isn't capable of rewriting rewritten code, it's important
4741// we get this right.
4742void RewriteObjC::CollectPropertySetters(Stmt *S) {
4743 // Perform a bottom up traversal of all children.
4744 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4745 CI != E; ++CI)
4746 if (*CI)
4747 CollectPropertySetters(*CI);
4748
4749 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4750 if (BinOp->isAssignmentOp()) {
4751 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4752 PropSetters[PRE] = BinOp;
4753 }
4754 }
4755}
4756
Steve Narofffa15fd92008-10-28 20:29:00 +00004757Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00004758 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00004759 isa<DoStmt>(S) || isa<ForStmt>(S))
4760 Stmts.push_back(S);
4761 else if (isa<ObjCForCollectionStmt>(S)) {
4762 Stmts.push_back(S);
Anders Carlssonfc4020a2009-12-22 06:13:42 +00004763 ++BcLabelCount;
4764 ObjCBcLabelNo.push_back(BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00004765 }
Mike Stump1eb44332009-09-09 15:08:12 +00004766
Steve Narofffa15fd92008-10-28 20:29:00 +00004767 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00004768
Steve Narofffa15fd92008-10-28 20:29:00 +00004769 // Perform a bottom up rewrite of all children.
4770 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4771 CI != E; ++CI)
4772 if (*CI) {
4773 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Mike Stump1eb44332009-09-09 15:08:12 +00004774 if (newStmt)
Steve Narofffa15fd92008-10-28 20:29:00 +00004775 *CI = newStmt;
4776 }
Mike Stump1eb44332009-09-09 15:08:12 +00004777
Steve Narofffa15fd92008-10-28 20:29:00 +00004778 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4779 // Rewrite the block body in place.
4780 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Mike Stump1eb44332009-09-09 15:08:12 +00004781
Steve Narofffa15fd92008-10-28 20:29:00 +00004782 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenek6a12a142010-01-07 18:00:35 +00004783 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004784 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00004785
Steve Narofffa15fd92008-10-28 20:29:00 +00004786 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4787 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004788 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00004789 return blockTranscribed;
4790 }
4791 // Handle specific things.
4792 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4793 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00004794
Steve Narofffa15fd92008-10-28 20:29:00 +00004795 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4796 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4797
Steve Naroffc77a6362008-12-04 16:24:46 +00004798 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4799 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4800 if (BinOp) {
4801 // Because the rewriter doesn't allow us to rewrite rewritten code,
4802 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00004803 DisableReplaceStmt = true;
4804 // Save the source range. Even if we disable the replacement, the
4805 // rewritten node will have been inserted into the tree. If the synthesized
4806 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump1eb44332009-09-09 15:08:12 +00004807 // self.errorHandler = handler ? handler :
Steve Naroffb619d952008-12-09 12:56:34 +00004808 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4809 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00004810 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroffb619d952008-12-09 12:56:34 +00004811 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00004812 //
4813 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4814 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4815 // to see the original expression). Consider this example:
4816 //
4817 // Foo *obj1, *obj2;
4818 //
4819 // obj1.i = [obj2 rrrr];
4820 //
4821 // 'BinOp' for the previous expression looks like:
4822 //
4823 // (BinaryOperator 0x231ccf0 'int' '='
4824 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4825 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4826 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4827 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4828 //
4829 // 'newStmt' represents the rewritten message expression. For example:
4830 //
4831 // (CallExpr 0x231d300 'id':'struct objc_object *'
4832 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4833 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4834 // (CStyleCastExpr 0x231d220 'void *'
4835 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4836 //
4837 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4838 // can be used as the setter argument. ReplaceStmt() will still 'see'
4839 // the original RHS (since we haven't altered BinOp).
4840 //
Mike Stump1eb44332009-09-09 15:08:12 +00004841 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff4c3580e2008-12-04 23:50:32 +00004842 // node. As a result, we now leak the original AST nodes.
4843 //
Steve Naroffb619d952008-12-09 12:56:34 +00004844 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00004845 } else {
4846 return RewritePropertyGetter(PropRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00004847 }
4848 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004849 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4850 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00004851
Steve Narofffa15fd92008-10-28 20:29:00 +00004852 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4853 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00004854
Steve Narofffa15fd92008-10-28 20:29:00 +00004855 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00004856#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00004857 // Before we rewrite it, put the original message expression in a comment.
4858 SourceLocation startLoc = MessExpr->getLocStart();
4859 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00004860
Steve Narofffa15fd92008-10-28 20:29:00 +00004861 const char *startBuf = SM->getCharacterData(startLoc);
4862 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004863
Steve Narofffa15fd92008-10-28 20:29:00 +00004864 std::string messString;
4865 messString += "// ";
4866 messString.append(startBuf, endBuf-startBuf+1);
4867 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004868
4869 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00004870 // InsertText(clang::SourceLocation, char const*, unsigned int).
4871 // InsertText(startLoc, messString.c_str(), messString.size());
4872 // Tried this, but it didn't work either...
4873 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00004874#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00004875 return RewriteMessageExpr(MessExpr);
4876 }
Mike Stump1eb44332009-09-09 15:08:12 +00004877
Steve Narofffa15fd92008-10-28 20:29:00 +00004878 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4879 return RewriteObjCTryStmt(StmtTry);
4880
4881 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4882 return RewriteObjCSynchronizedStmt(StmtTry);
4883
4884 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4885 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00004886
Steve Narofffa15fd92008-10-28 20:29:00 +00004887 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4888 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00004889
4890 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00004891 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00004892 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00004893 OrigStmtRange.getEnd());
4894 if (BreakStmt *StmtBreakStmt =
4895 dyn_cast<BreakStmt>(S))
4896 return RewriteBreakStmt(StmtBreakStmt);
4897 if (ContinueStmt *StmtContinueStmt =
4898 dyn_cast<ContinueStmt>(S))
4899 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00004900
4901 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00004902 // and cast exprs.
4903 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4904 // FIXME: What we're doing here is modifying the type-specifier that
4905 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00004906 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00004907 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4908 // the context of an ObjCForCollectionStmt. For example:
4909 // NSArray *someArray;
4910 // for (id <FooProtocol> index in someArray) ;
4911 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4912 // and it depends on the original text locations/positions.
Benjamin Kramerb2041de2009-12-05 22:16:51 +00004913 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroff3d7e7862009-12-05 15:55:59 +00004914 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00004915
Steve Narofffa15fd92008-10-28 20:29:00 +00004916 // Blocks rewrite rules.
4917 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4918 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004919 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00004920 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004921 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004922 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00004923 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00004924 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004925 if (VarDecl *VD = dyn_cast<VarDecl>(SD))
4926 if (VD->hasAttr<BlocksAttr>())
4927 RewriteByRefVar(VD);
Steve Narofffa15fd92008-10-28 20:29:00 +00004928 }
4929 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004930 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004931 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00004932 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00004933 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4934 }
4935 }
4936 }
Mike Stump1eb44332009-09-09 15:08:12 +00004937
Steve Narofffa15fd92008-10-28 20:29:00 +00004938 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4939 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00004940
4941 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00004942 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4943 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00004944 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4945 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004946 && "Statement stack mismatch");
4947 Stmts.pop_back();
4948 }
4949 // Handle blocks rewriting.
4950 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4951 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00004952 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00004953 }
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004954 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4955 ValueDecl *VD = DRE->getDecl();
4956 if (VD->hasAttr<BlocksAttr>())
4957 return RewriteBlockDeclRefExpr(DRE);
4958 }
4959
Steve Narofffa15fd92008-10-28 20:29:00 +00004960 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004961 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004962 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004963 ReplaceStmt(S, BlockCall);
4964 return BlockCall;
4965 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004966 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00004967 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004968 RewriteCastExpr(CE);
4969 }
4970#if 0
4971 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00004972 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004973 // Get the new text.
4974 std::string SStr;
4975 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00004976 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00004977 const std::string &Str = Buf.str();
4978
4979 printf("CAST = %s\n", &Str[0]);
4980 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4981 delete S;
4982 return Replacement;
4983 }
4984#endif
4985 // Return this stmt unmodified.
4986 return S;
4987}
4988
Steve Naroff3d7e7862009-12-05 15:55:59 +00004989void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
4990 for (RecordDecl::field_iterator i = RD->field_begin(),
4991 e = RD->field_end(); i != e; ++i) {
4992 FieldDecl *FD = *i;
4993 if (isTopLevelBlockPointerType(FD->getType()))
4994 RewriteBlockPointerDecl(FD);
4995 if (FD->getType()->isObjCQualifiedIdType() ||
4996 FD->getType()->isObjCQualifiedInterfaceType())
4997 RewriteObjCQualifiedInterfaceTypes(FD);
4998 }
4999}
5000
Steve Narofffa15fd92008-10-28 20:29:00 +00005001/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5002/// main file of the input.
5003void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5004 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00005005 if (FD->isOverloadedOperator())
5006 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005007
Steve Narofffa15fd92008-10-28 20:29:00 +00005008 // Since function prototypes don't have ParmDecl's, we check the function
5009 // prototype. This enables us to rewrite function declarations and
5010 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00005011 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005012
Sebastian Redld3a413d2009-04-26 20:35:05 +00005013 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005014 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005015 CurFunctionDef = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005016 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005017 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005018 Body =
5019 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5020 FD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005021 CurrentBody = 0;
5022 if (PropParentMap) {
5023 delete PropParentMap;
5024 PropParentMap = 0;
5025 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005026 // This synthesizes and inserts the block "impl" struct, invoke function,
5027 // and any copy/dispose helper functions.
5028 InsertBlockLiteralsWithinFunction(FD);
5029 CurFunctionDef = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005030 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005031 return;
5032 }
5033 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005034 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005035 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005036 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005037 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005038 Body =
5039 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5040 MD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005041 CurrentBody = 0;
5042 if (PropParentMap) {
5043 delete PropParentMap;
5044 PropParentMap = 0;
5045 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005046 InsertBlockLiteralsWithinMethod(MD);
5047 CurMethodDef = 0;
5048 }
5049 }
5050 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5051 ClassImplementation.push_back(CI);
5052 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5053 CategoryImplementation.push_back(CI);
5054 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5055 RewriteForwardClassDecl(CD);
5056 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5057 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005058 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005059 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005060 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005061 CheckFunctionPointerDecl(VD->getType(), VD);
5062 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00005063 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005064 RewriteCastExpr(CE);
5065 }
5066 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00005067 } else if (VD->getType()->isRecordType()) {
5068 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5069 if (RD->isDefinition())
5070 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005071 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005072 if (VD->getInit()) {
5073 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005074 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005075 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005076 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005077 CurrentBody = 0;
5078 if (PropParentMap) {
5079 delete PropParentMap;
5080 PropParentMap = 0;
5081 }
Mike Stump1eb44332009-09-09 15:08:12 +00005082 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00005083 VD->getNameAsCString());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005084 GlobalVarDecl = 0;
5085
5086 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00005087 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005088 RewriteCastExpr(CE);
5089 }
5090 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005091 return;
5092 }
5093 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005094 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005095 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005096 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005097 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Steve Naroff3d7e7862009-12-05 15:55:59 +00005098 else if (TD->getUnderlyingType()->isRecordType()) {
5099 RecordDecl *RD = TD->getUnderlyingType()->getAs<RecordType>()->getDecl();
5100 if (RD->isDefinition())
5101 RewriteRecordBody(RD);
5102 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005103 return;
5104 }
5105 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroff3d7e7862009-12-05 15:55:59 +00005106 if (RD->isDefinition())
5107 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005108 return;
5109 }
5110 // Nothing yet.
5111}
5112
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00005113void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005114 // Get the top-level buffer that this corresponds to.
Mike Stump1eb44332009-09-09 15:08:12 +00005115
Steve Narofffa15fd92008-10-28 20:29:00 +00005116 // Rewrite tabs if we care.
5117 //RewriteTabs();
Mike Stump1eb44332009-09-09 15:08:12 +00005118
Steve Narofffa15fd92008-10-28 20:29:00 +00005119 if (Diags.hasErrorOccurred())
5120 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005121
Steve Narofffa15fd92008-10-28 20:29:00 +00005122 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00005123
Steve Naroff621edce2009-04-29 16:37:50 +00005124 // Here's a great place to add any extra declarations that may be needed.
5125 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00005126 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00005127 E = ProtocolExprDecls.end(); I != E; ++I)
5128 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5129
Mike Stump1eb44332009-09-09 15:08:12 +00005130 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Narofffa15fd92008-10-28 20:29:00 +00005131 Preamble.c_str(), Preamble.size(), false);
Steve Naroff0aab7962008-11-14 14:10:01 +00005132 if (ClassImplementation.size() || CategoryImplementation.size())
5133 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00005134
Steve Narofffa15fd92008-10-28 20:29:00 +00005135 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5136 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00005137 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00005138 Rewrite.getRewriteBufferFor(MainFileID)) {
5139 //printf("Changed:\n");
5140 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5141 } else {
5142 fprintf(stderr, "No changes\n");
5143 }
Steve Narofface66252008-11-13 20:07:04 +00005144
Steve Naroff621edce2009-04-29 16:37:50 +00005145 if (ClassImplementation.size() || CategoryImplementation.size() ||
5146 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00005147 // Rewrite Objective-c meta data*
5148 std::string ResultStr;
5149 SynthesizeMetaDataIntoBuffer(ResultStr);
5150 // Emit metadata.
5151 *OutFile << ResultStr;
5152 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005153 OutFile->flush();
5154}
5155