blob: be07a6aadf4d598ab0e391fa8c4e1f2b8204a576 [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;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000117 bool objc_impl_method;
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000118
Steve Naroffba92b2e2008-03-27 22:29:16 +0000119 std::string Preamble;
Steve Naroff54055232008-10-27 17:20:55 +0000120
121 // Block expressions.
122 llvm::SmallVector<BlockExpr *, 32> Blocks;
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000123 llvm::SmallVector<int, 32> InnerDeclRefsCount;
124 llvm::SmallVector<BlockDeclRefExpr *, 32> InnerDeclRefs;
125
Steve Naroff54055232008-10-27 17:20:55 +0000126 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
Mike Stump1eb44332009-09-09 15:08:12 +0000127
Steve Naroff54055232008-10-27 17:20:55 +0000128 // Block related declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000129 llvm::SmallVector<ValueDecl *, 8> BlockByCopyDecls;
130 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
131 llvm::SmallVector<ValueDecl *, 8> BlockByRefDecls;
132 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000133 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff54055232008-10-27 17:20:55 +0000134 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
135
136 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
137
Steve Naroffc77a6362008-12-04 16:24:46 +0000138 // This maps a property to it's assignment statement.
139 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Naroff8599e7a2008-12-08 16:43:47 +0000140 // This maps a property to it's synthesied message expression.
141 // This allows us to rewrite chained getters (e.g. o.a.b.c).
142 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
Mike Stump1eb44332009-09-09 15:08:12 +0000143
Steve Naroff4c3580e2008-12-04 23:50:32 +0000144 // This maps an original source AST to it's rewritten form. This allows
145 // us to avoid rewriting the same node twice (which is very uncommon).
146 // This is needed to support some of the exotic property rewriting.
147 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000148
Steve Naroff54055232008-10-27 17:20:55 +0000149 FunctionDecl *CurFunctionDef;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000150 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000151 VarDecl *GlobalVarDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000152
Steve Naroffb619d952008-12-09 12:56:34 +0000153 bool DisableReplaceStmt;
Mike Stump1eb44332009-09-09 15:08:12 +0000154
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000155 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000156 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000157 virtual void Initialize(ASTContext &context);
158
Chris Lattnerf04da132007-10-24 17:06:59 +0000159 // Top Level Driver code.
Chris Lattner682bf922009-03-29 16:50:03 +0000160 virtual void HandleTopLevelDecl(DeclGroupRef D) {
161 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
162 HandleTopLevelSingleDecl(*I);
163 }
164 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000165 void HandleDeclInMainFile(Decl *D);
Eli Friedman66d6f042009-05-18 22:20:00 +0000166 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000167 Diagnostic &D, const LangOptions &LOpts,
168 bool silenceMacroWarn);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000169
170 ~RewriteObjC() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000171
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000172 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump1eb44332009-09-09 15:08:12 +0000173
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000174 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000175 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump1eb44332009-09-09 15:08:12 +0000176
Steve Naroff4c3580e2008-12-04 23:50:32 +0000177 if (ReplacingStmt)
178 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000179
Steve Naroffb619d952008-12-09 12:56:34 +0000180 if (DisableReplaceStmt)
181 return; // Used when rewriting the assignment of a property setter.
182
Steve Naroff4c3580e2008-12-04 23:50:32 +0000183 // If replacement succeeded or warning disabled return with no warning.
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000184 if (!Rewrite.ReplaceStmt(Old, New)) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000185 ReplacedNodes[Old] = New;
186 return;
187 }
188 if (SilenceRewriteMacroWarning)
189 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000190 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
191 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000192 }
Steve Naroffb619d952008-12-09 12:56:34 +0000193
194 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
195 // Measaure the old text.
196 int Size = Rewrite.getRangeSize(SrcRange);
197 if (Size == -1) {
198 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
199 << Old->getSourceRange();
200 return;
201 }
202 // Get the new text.
203 std::string SStr;
204 llvm::raw_string_ostream S(SStr);
Chris Lattnere4f21422009-06-30 01:26:17 +0000205 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroffb619d952008-12-09 12:56:34 +0000206 const std::string &Str = S.str();
207
208 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000209 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroffb619d952008-12-09 12:56:34 +0000210 ReplacedNodes[Old] = New;
211 return;
212 }
213 if (SilenceRewriteMacroWarning)
214 return;
215 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
216 << Old->getSourceRange();
217 }
218
Benjamin Kramerd999b372010-02-14 14:14:16 +0000219 void InsertText(SourceLocation Loc, llvm::StringRef Str,
Steve Naroffba92b2e2008-03-27 22:29:16 +0000220 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000221 // If insertion succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000222 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000223 SilenceRewriteMacroWarning)
224 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000225
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000226 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
227 }
Mike Stump1eb44332009-09-09 15:08:12 +0000228
Chris Lattneraadaf782008-01-31 19:51:04 +0000229 void RemoveText(SourceLocation Loc, unsigned StrLen) {
230 // If removal succeeded or warning disabled return with no warning.
231 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
232 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000233
Chris Lattneraadaf782008-01-31 19:51:04 +0000234 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
235 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000236
Chris Lattneraadaf782008-01-31 19:51:04 +0000237 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Benjamin Kramerd999b372010-02-14 14:14:16 +0000238 llvm::StringRef Str) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000239 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000240 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattneraadaf782008-01-31 19:51:04 +0000241 SilenceRewriteMacroWarning)
242 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000243
Chris Lattneraadaf782008-01-31 19:51:04 +0000244 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
245 }
Mike Stump1eb44332009-09-09 15:08:12 +0000246
Chris Lattnerf04da132007-10-24 17:06:59 +0000247 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000248 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000249 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000250 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000251 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffa0876e82008-12-02 17:36:43 +0000252 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
253 ObjCImplementationDecl *IMD,
254 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000255 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000256 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000257 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000258 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
259 const FunctionType *&FPRetType);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000260 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
261 ValueDecl *VD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000262 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
263 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
264 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
265 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000266 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000267 void RewriteFunctionDecl(FunctionDecl *FD);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000268 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000269 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +0000270 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff4f95b752008-07-29 18:15:38 +0000271 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000272 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000273 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000274 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000275 QualType getConstantStringStructType();
Steve Naroffbaf58c32008-05-31 14:15:04 +0000276 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump1eb44332009-09-09 15:08:12 +0000277
Chris Lattnerf04da132007-10-24 17:06:59 +0000278 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000279 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroffc77a6362008-12-04 16:24:46 +0000280 void CollectPropertySetters(Stmt *S);
Mike Stump1eb44332009-09-09 15:08:12 +0000281
Steve Naroff8599e7a2008-12-08 16:43:47 +0000282 Stmt *CurrentBody;
283 ParentMap *PropParentMap; // created lazily.
Mike Stump1eb44332009-09-09 15:08:12 +0000284
Chris Lattnere64b7772007-10-24 16:57:36 +0000285 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +0000286 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart,
287 bool &replaced);
288 Stmt *RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced);
Steve Naroffc77a6362008-12-04 16:24:46 +0000289 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Mike Stump1eb44332009-09-09 15:08:12 +0000290 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroffb619d952008-12-09 12:56:34 +0000291 SourceRange SrcRange);
Steve Naroffb42f8412007-11-05 14:50:49 +0000292 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000293 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000294 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000295 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffb85e77a2009-12-05 21:43:12 +0000296 void WarnAboutReturnGotoStmts(Stmt *S);
297 void HasReturnStmts(Stmt *S, bool &hasReturns);
298 void RewriteTryReturnStmts(Stmt *S);
299 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000300 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000301 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000302 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
303 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
304 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000305 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
306 SourceLocation OrigEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000307 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +0000308 Expr **args, unsigned nargs,
309 SourceLocation StartLoc=SourceLocation(),
310 SourceLocation EndLoc=SourceLocation());
311 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
312 SourceLocation StartLoc=SourceLocation(),
313 SourceLocation EndLoc=SourceLocation());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000314 Stmt *RewriteBreakStmt(BreakStmt *S);
315 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000316 void SynthCountByEnumWithState(std::string &buf);
Mike Stump1eb44332009-09-09 15:08:12 +0000317
Steve Naroff09b266e2007-10-30 23:14:51 +0000318 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000319 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000320 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000321 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000322 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000323 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000324 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000325 void SynthSelGetUidFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000326 void SynthSuperContructorFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000327
Chris Lattnerf04da132007-10-24 17:06:59 +0000328 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000329 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000330 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000331
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000332 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000333 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000334
Douglas Gregor653f1b12009-04-23 01:02:12 +0000335 template<typename MethodIterator>
336 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
337 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000338 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000339 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000340 const char *ClassName,
341 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000342
Steve Naroff621edce2009-04-29 16:37:50 +0000343 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
344 const char *prefix,
345 const char *ClassName,
346 std::string &Result);
347 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Mike Stump1eb44332009-09-09 15:08:12 +0000348 const char *prefix,
Steve Naroff621edce2009-04-29 16:37:50 +0000349 const char *ClassName,
350 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000351 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000352 std::string &Result);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000353 void SynthesizeIvarOffsetComputation(ObjCContainerDecl *IDecl,
Mike Stump1eb44332009-09-09 15:08:12 +0000354 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000355 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000356 void RewriteImplementations();
357 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000358
Steve Naroff54055232008-10-27 17:20:55 +0000359 // Block rewriting.
Mike Stump1eb44332009-09-09 15:08:12 +0000360 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff54055232008-10-27 17:20:55 +0000361 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump1eb44332009-09-09 15:08:12 +0000362
Steve Naroff54055232008-10-27 17:20:55 +0000363 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
364 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump1eb44332009-09-09 15:08:12 +0000365
366 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000367 void RewriteBlockCall(CallExpr *Exp);
368 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000369 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +0000370 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +0000371 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Steve Naroff54055232008-10-27 17:20:55 +0000372 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000373
374 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Steve Naroff54055232008-10-27 17:20:55 +0000375 const char *funcName, std::string Tag);
Mike Stump1eb44332009-09-09 15:08:12 +0000376 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Steve Naroff54055232008-10-27 17:20:55 +0000377 const char *funcName, std::string Tag);
Steve Naroff01aec112009-12-06 21:14:13 +0000378 std::string SynthesizeBlockImpl(BlockExpr *CE,
379 std::string Tag, std::string Desc);
380 std::string SynthesizeBlockDescriptor(std::string DescTag,
381 std::string ImplTag,
382 int i, const char *funcName,
383 unsigned hasCopy);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +0000384 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff54055232008-10-27 17:20:55 +0000385 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000386 const char *FunName);
Steve Naroff3d7e7862009-12-05 15:55:59 +0000387 void RewriteRecordBody(RecordDecl *RD);
Mike Stump1eb44332009-09-09 15:08:12 +0000388
Steve Naroff54055232008-10-27 17:20:55 +0000389 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000390 void GetBlockDeclRefExprs(Stmt *S);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000391 void GetInnerBlockDeclRefExprs(Stmt *S,
392 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
393 llvm::SmallPtrSet<ValueDecl *, 8> &InnerBlockValueDecls);
Mike Stump1eb44332009-09-09 15:08:12 +0000394
Steve Naroff54055232008-10-27 17:20:55 +0000395 // We avoid calling Type::isBlockPointerType(), since it operates on the
396 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000397 bool isTopLevelBlockPointerType(QualType T) {
398 return isa<BlockPointerType>(T);
399 }
Mike Stump1eb44332009-09-09 15:08:12 +0000400
Steve Naroff54055232008-10-27 17:20:55 +0000401 // FIXME: This predicate seems like it would be useful to add to ASTContext.
402 bool isObjCType(QualType T) {
403 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
404 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000405
Steve Naroff54055232008-10-27 17:20:55 +0000406 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000407
Steve Naroff54055232008-10-27 17:20:55 +0000408 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
409 OCT == Context->getCanonicalType(Context->getObjCClassType()))
410 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000411
Ted Kremenek6217b802009-07-29 21:53:49 +0000412 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000413 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000414 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000415 return true;
416 }
417 return false;
418 }
419 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000420 void GetExtentOfArgList(const char *Name, const char *&LParen,
421 const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000422 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump1eb44332009-09-09 15:08:12 +0000423
Steve Narofffa15fd92008-10-28 20:29:00 +0000424 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000425 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
426 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
Mike Stump1eb44332009-09-09 15:08:12 +0000427
Steve Naroff621edce2009-04-29 16:37:50 +0000428 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000429 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000430 if (From[i] == '"')
431 To += "\\\"";
432 else
433 To += From[i];
434 }
435 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000436 };
John McCall9d125032010-01-15 18:39:57 +0000437
438 // Helper function: create a CStyleCastExpr with trivial type source info.
439 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
440 CastExpr::CastKind Kind, Expr *E) {
441 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
442 return new (Ctx) CStyleCastExpr(Ty, Kind, E, TInfo,
443 SourceLocation(), SourceLocation());
444 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000445}
446
Mike Stump1eb44332009-09-09 15:08:12 +0000447void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
448 NamedDecl *D) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000449 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000450 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000451 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000452 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000453 // All the args are checked/rewritten. Don't call twice!
454 RewriteBlockPointerDecl(D);
455 break;
456 }
457 }
458}
459
460void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000461 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000462 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000463 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000464}
465
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000466static bool IsHeaderFile(const std::string &Filename) {
467 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000468
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000469 if (DotPos == std::string::npos) {
470 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000471 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000472 }
Mike Stump1eb44332009-09-09 15:08:12 +0000473
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000474 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
475 // C header: .h
476 // C++ header: .hh or .H;
477 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000478}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000479
Eli Friedman66d6f042009-05-18 22:20:00 +0000480RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000481 Diagnostic &D, const LangOptions &LOpts,
482 bool silenceMacroWarn)
483 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
484 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000485 IsHeader = IsHeaderFile(inFile);
Mike Stump1eb44332009-09-09 15:08:12 +0000486 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000487 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump1eb44332009-09-09 15:08:12 +0000488 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000489 "rewriter doesn't support user-specified control flow semantics "
490 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000491}
492
Eli Friedmanbce831b2009-05-18 22:29:17 +0000493ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
494 llvm::raw_ostream* OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000495 Diagnostic &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000496 const LangOptions &LOpts,
497 bool SilenceRewriteMacroWarning) {
498 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000499}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000500
Steve Naroffb29b4272008-04-14 22:03:09 +0000501void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000502 Context = &context;
503 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000504 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000505 MsgSendFunctionDecl = 0;
506 MsgSendSuperFunctionDecl = 0;
507 MsgSendStretFunctionDecl = 0;
508 MsgSendSuperStretFunctionDecl = 0;
509 MsgSendFpretFunctionDecl = 0;
510 GetClassFunctionDecl = 0;
511 GetMetaClassFunctionDecl = 0;
512 SelGetUidFunctionDecl = 0;
513 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000514 ConstantStringClassReference = 0;
515 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000516 CurMethodDef = 0;
517 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000518 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000519 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000520 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000521 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000522 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000523 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000524 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000525 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000526 PropParentMap = 0;
527 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000528 DisableReplaceStmt = false;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000529 objc_impl_method = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000530
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000531 // Get the ID and start/end of the main file.
532 MainFileID = SM->getMainFileID();
533 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
534 MainFileStart = MainBuf->getBufferStart();
535 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000536
Chris Lattner2c78b872009-04-14 23:22:57 +0000537 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump1eb44332009-09-09 15:08:12 +0000538
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000539 // declaring objc_selector outside the parameter list removes a silly
540 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000541 if (IsHeader)
Steve Naroff62c26322009-02-03 20:39:18 +0000542 Preamble = "#pragma once\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000543 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000544 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000545 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000546 if (LangOpts.Microsoft) {
547 // Add a constructor for creating temporary objects.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000548 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
549 ": ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000550 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000551 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000552 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000553 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
554 Preamble += "typedef struct objc_object Protocol;\n";
555 Preamble += "#define _REWRITER_typedef_Protocol\n";
556 Preamble += "#endif\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000557 if (LangOpts.Microsoft) {
558 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
559 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
560 } else
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000561 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000562 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000563 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000564 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000565 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000566 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000567 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000568 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000569 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000570 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000571 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000572 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000573 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000574 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000575 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000576 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
577 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
578 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
579 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
580 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000581 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000582 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000583 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
584 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
585 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000586 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
587 Preamble += "struct __objcFastEnumerationState {\n\t";
588 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000589 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000590 Preamble += "unsigned long *mutationsPtr;\n\t";
591 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000592 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000593 Preamble += "#define __FASTENUMERATIONSTATE\n";
594 Preamble += "#endif\n";
595 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
596 Preamble += "struct __NSConstantStringImpl {\n";
597 Preamble += " int *isa;\n";
598 Preamble += " int flags;\n";
599 Preamble += " char *str;\n";
600 Preamble += " long length;\n";
601 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000602 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
603 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
604 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000605 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000606 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000607 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
608 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000609 // Blocks preamble.
610 Preamble += "#ifndef BLOCK_IMPL\n";
611 Preamble += "#define BLOCK_IMPL\n";
612 Preamble += "struct __block_impl {\n";
613 Preamble += " void *isa;\n";
614 Preamble += " int Flags;\n";
Steve Naroff01aec112009-12-06 21:14:13 +0000615 Preamble += " int Reserved;\n";
Steve Naroff54055232008-10-27 17:20:55 +0000616 Preamble += " void *FuncPtr;\n";
617 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000618 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroffc9c1e9c2009-12-06 01:52:22 +0000619 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000620 Preamble += "extern \"C\" __declspec(dllexport) "
621 "void _Block_object_assign(void *, const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000622 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
623 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
624 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
625 Preamble += "#else\n";
Steve Naroffcd826372010-01-05 18:09:31 +0000626 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
627 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000628 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
629 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
630 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000631 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000632 if (LangOpts.Microsoft) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000633 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
634 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000635 Preamble += "#define __attribute__(X)\n";
Fariborz Jahanian34204192010-01-15 22:29:39 +0000636 Preamble += "#define __weak\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000637 }
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000638 else {
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000639 Preamble += "#define __block\n";
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000640 Preamble += "#define __weak\n";
641 }
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000642 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long) &((TYPE *)0)->MEMBER)\n";
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000643}
644
645
Chris Lattnerf04da132007-10-24 17:06:59 +0000646//===----------------------------------------------------------------------===//
647// Top Level Driver Code
648//===----------------------------------------------------------------------===//
649
Chris Lattner682bf922009-03-29 16:50:03 +0000650void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremeneke50187a2010-02-05 21:28:51 +0000651 if (Diags.hasErrorOccurred())
652 return;
653
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000654 // Two cases: either the decl could be in the main file, or it could be in a
655 // #included file. If the former, rewrite it now. If the later, check to see
656 // if we rewrote the #include/#import.
657 SourceLocation Loc = D->getLocation();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000658 Loc = SM->getInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000659
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000660 // If this is for a builtin, ignore it.
661 if (Loc.isInvalid()) return;
662
Steve Naroffebf2b562007-10-23 23:50:29 +0000663 // Look for built-in declarations that we need to refer during the rewrite.
664 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000665 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000666 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000667 // declared in <Foundation/NSString.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +0000668 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000669 ConstantStringClassReference = FVD;
670 return;
671 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000672 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000673 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000674 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000675 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000676 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000677 RewriteProtocolDecl(PD);
Mike Stump1eb44332009-09-09 15:08:12 +0000678 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000679 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000680 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000681 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
682 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000683 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
684 DIEnd = LSD->decls_end();
Douglas Gregord0434102009-01-09 00:49:46 +0000685 DI != DIEnd; ++DI)
Chris Lattner682bf922009-03-29 16:50:03 +0000686 HandleTopLevelSingleDecl(*DI);
Steve Naroffebf2b562007-10-23 23:50:29 +0000687 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000688 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000689 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000690 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000691}
692
Chris Lattnerf04da132007-10-24 17:06:59 +0000693//===----------------------------------------------------------------------===//
694// Syntactic (non-AST) Rewriting Code
695//===----------------------------------------------------------------------===//
696
Steve Naroffb29b4272008-04-14 22:03:09 +0000697void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000698 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000699 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
700 const char *MainBufStart = MainBuf.first;
701 const char *MainBufEnd = MainBuf.second;
702 size_t ImportLen = strlen("import");
Mike Stump1eb44332009-09-09 15:08:12 +0000703
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000704 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000705 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
706 if (*BufPtr == '#') {
707 if (++BufPtr == MainBufEnd)
708 return;
709 while (*BufPtr == ' ' || *BufPtr == '\t')
710 if (++BufPtr == MainBufEnd)
711 return;
712 if (!strncmp(BufPtr, "import", ImportLen)) {
713 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000714 SourceLocation ImportLoc =
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000715 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000716 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000717 BufPtr += ImportLen;
718 }
719 }
720 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000721}
722
Steve Naroffb29b4272008-04-14 22:03:09 +0000723void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000724 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
725 const char *MainBufStart = MainBuf.first;
726 const char *MainBufEnd = MainBuf.second;
Mike Stump1eb44332009-09-09 15:08:12 +0000727
Chris Lattnerf04da132007-10-24 17:06:59 +0000728 // Loop over the whole file, looking for tabs.
729 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
730 if (*BufPtr != '\t')
731 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000732
Chris Lattnerf04da132007-10-24 17:06:59 +0000733 // Okay, we found a tab. This tab will turn into at least one character,
734 // but it depends on which 'virtual column' it is in. Compute that now.
735 unsigned VCol = 0;
736 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
737 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
738 ++VCol;
Mike Stump1eb44332009-09-09 15:08:12 +0000739
Chris Lattnerf04da132007-10-24 17:06:59 +0000740 // Okay, now that we know the virtual column, we know how many spaces to
741 // insert. We assume 8-character tab-stops.
742 unsigned Spaces = 8-(VCol & 7);
Mike Stump1eb44332009-09-09 15:08:12 +0000743
Chris Lattnerf04da132007-10-24 17:06:59 +0000744 // Get the location of the tab.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000745 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
746 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Mike Stump1eb44332009-09-09 15:08:12 +0000747
Chris Lattnerf04da132007-10-24 17:06:59 +0000748 // Rewrite the single tab character into a sequence of spaces.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000749 ReplaceText(TabLoc, 1, llvm::StringRef(" ", Spaces));
Chris Lattnerf04da132007-10-24 17:06:59 +0000750 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000751}
752
Steve Naroffeb0646c2008-12-02 15:48:25 +0000753static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
754 ObjCIvarDecl *OID) {
755 std::string S;
756 S = "((struct ";
757 S += ClassDecl->getIdentifier()->getName();
758 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000759 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000760 return S;
761}
762
Steve Naroffa0876e82008-12-02 17:36:43 +0000763void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
764 ObjCImplementationDecl *IMD,
765 ObjCCategoryImplDecl *CID) {
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000766 static bool objcGetPropertyDefined = false;
767 static bool objcSetPropertyDefined = false;
Steve Naroffd40910b2008-12-01 20:33:01 +0000768 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000769 InsertText(startLoc, "// ");
Steve Naroffeb0646c2008-12-02 15:48:25 +0000770 const char *startBuf = SM->getCharacterData(startLoc);
771 assert((*startBuf == '@') && "bogus @synthesize location");
772 const char *semiBuf = strchr(startBuf, ';');
773 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000774 SourceLocation onePastSemiLoc =
775 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000776
777 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
778 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000779
Steve Naroffeb0646c2008-12-02 15:48:25 +0000780 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000781 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000782 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000783 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000784
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000785 if (!OID)
786 return;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000787 unsigned Attributes = PD->getPropertyAttributes();
788 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
789 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
790 ObjCPropertyDecl::OBJC_PR_copy));
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000791 std::string Getr;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000792 if (GenGetProperty && !objcGetPropertyDefined) {
793 objcGetPropertyDefined = true;
794 // FIXME. Is this attribute correct in all cases?
795 Getr = "\nextern \"C\" __declspec(dllimport) "
796 "id objc_getProperty(id, SEL, long, bool);\n";
797 }
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000798 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
799 Getr += "{ ";
800 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff3539cdb2008-12-02 17:54:50 +0000801 // See objc-act.c:objc_synthesize_new_getter() for details.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000802 if (GenGetProperty) {
803 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
804 Getr += "typedef ";
805 const FunctionType *FPRetType = 0;
806 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
807 FPRetType);
808 Getr += " _TYPE";
809 if (FPRetType) {
810 Getr += ")"; // close the precedence "scope" for "*".
811
812 // Now, emit the argument types (if any).
813 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
814 Getr += "(";
815 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
816 if (i) Getr += ", ";
817 std::string ParamStr = FT->getArgType(i).getAsString();
818 Getr += ParamStr;
819 }
820 if (FT->isVariadic()) {
821 if (FT->getNumArgs()) Getr += ", ";
822 Getr += "...";
823 }
824 Getr += ")";
825 } else
826 Getr += "()";
827 }
828 Getr += ";\n";
829 Getr += "return (_TYPE)";
830 Getr += "objc_getProperty(self, _cmd, ";
831 SynthesizeIvarOffsetComputation(ClassDecl, OID, Getr);
832 Getr += ", 1)";
833 }
834 else
835 Getr += "return " + getIvarAccessString(ClassDecl, OID);
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000836 Getr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000837 InsertText(onePastSemiLoc, Getr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000838 if (PD->isReadOnly())
839 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000840
Steve Naroffeb0646c2008-12-02 15:48:25 +0000841 // Generate the 'setter' function.
842 std::string Setr;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000843 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
844 ObjCPropertyDecl::OBJC_PR_copy);
845 if (GenSetProperty && !objcSetPropertyDefined) {
846 objcSetPropertyDefined = true;
847 // FIXME. Is this attribute correct in all cases?
848 Setr = "\nextern \"C\" __declspec(dllimport) "
849 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
850 }
851
Steve Naroffeb0646c2008-12-02 15:48:25 +0000852 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000853 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000854 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff15f081d2008-12-03 00:56:33 +0000855 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000856 if (GenSetProperty) {
857 Setr += "objc_setProperty (self, _cmd, ";
858 SynthesizeIvarOffsetComputation(ClassDecl, OID, Setr);
859 Setr += ", (id)";
860 Setr += PD->getNameAsCString();
861 Setr += ", ";
862 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
863 Setr += "0, ";
864 else
865 Setr += "1, ";
866 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
867 Setr += "1)";
868 else
869 Setr += "0)";
870 }
871 else {
872 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
873 Setr += PD->getNameAsCString();
874 }
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000875 Setr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000876 InsertText(onePastSemiLoc, Setr);
Steve Naroffd40910b2008-12-01 20:33:01 +0000877}
Chris Lattner8a12c272007-10-11 18:38:32 +0000878
Steve Naroffb29b4272008-04-14 22:03:09 +0000879void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000880 // Get the start location and compute the semi location.
881 SourceLocation startLoc = ClassDecl->getLocation();
882 const char *startBuf = SM->getCharacterData(startLoc);
883 const char *semiPtr = strchr(startBuf, ';');
Mike Stump1eb44332009-09-09 15:08:12 +0000884
Chris Lattnerf04da132007-10-24 17:06:59 +0000885 // Translate to typedef's that forward reference structs with the same name
886 // as the class. As a convenience, we include the original declaration
887 // as a comment.
888 std::string typedefString;
Fariborz Jahanian91fbd122010-01-11 22:48:40 +0000889 typedefString += "// @class ";
890 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
891 I != E; ++I) {
892 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
893 typedefString += ForwardDecl->getNameAsString();
894 if (I+1 != E)
895 typedefString += ", ";
896 else
897 typedefString += ";\n";
898 }
899
Chris Lattner67956052009-02-20 18:04:31 +0000900 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
901 I != E; ++I) {
Ted Kremenek321c22f2009-11-18 00:28:11 +0000902 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff32174822007-11-09 12:50:28 +0000903 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000904 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000905 typedefString += "\n";
906 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000907 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000908 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000909 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000910 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000911 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000912 }
Mike Stump1eb44332009-09-09 15:08:12 +0000913
Steve Naroff934f2762007-10-24 22:48:43 +0000914 // Replace the @class with typedefs corresponding to the classes.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000915 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
Chris Lattnerf04da132007-10-24 17:06:59 +0000916}
917
Steve Naroffb29b4272008-04-14 22:03:09 +0000918void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000919 // When method is a synthesized one, such as a getter/setter there is
920 // nothing to rewrite.
921 if (Method->isSynthesized())
922 return;
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000923 SourceLocation LocStart = Method->getLocStart();
924 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000925
Chris Lattner30fc9332009-02-04 01:06:56 +0000926 if (SM->getInstantiationLineNumber(LocEnd) >
927 SM->getInstantiationLineNumber(LocStart)) {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000928 InsertText(LocStart, "#if 0\n");
929 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000930 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000931 InsertText(LocStart, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +0000932 }
933}
934
Mike Stump1eb44332009-09-09 15:08:12 +0000935void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000936 SourceLocation Loc = prop->getAtLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000937
Benjamin Kramerd999b372010-02-14 14:14:16 +0000938 ReplaceText(Loc, 0, "// ");
Steve Naroff6327e0d2009-01-11 01:06:09 +0000939 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000940}
941
Steve Naroffb29b4272008-04-14 22:03:09 +0000942void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000943 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000944
Steve Naroff423cb562007-10-30 13:30:57 +0000945 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000946 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000947
Fariborz Jahanian13751e32010-02-10 01:15:09 +0000948 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
949 E = CatDecl->prop_end(); I != E; ++I)
950 RewriteProperty(*I);
951
Mike Stump1eb44332009-09-09 15:08:12 +0000952 for (ObjCCategoryDecl::instmeth_iterator
953 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000954 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000955 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +0000956 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000957 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000958 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000959 RewriteMethodDeclaration(*I);
960
Steve Naroff423cb562007-10-30 13:30:57 +0000961 // Lastly, comment out the @end.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000962 ReplaceText(CatDecl->getAtEndRange().getBegin(), 0, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +0000963}
964
Steve Naroffb29b4272008-04-14 22:03:09 +0000965void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000966 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Mike Stump1eb44332009-09-09 15:08:12 +0000967
Steve Naroff752d6ef2007-10-30 16:42:30 +0000968 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000969
Steve Naroff752d6ef2007-10-30 16:42:30 +0000970 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000971 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000972
973 for (ObjCProtocolDecl::instmeth_iterator
974 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000975 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000976 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000977 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000978 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000979 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000980 RewriteMethodDeclaration(*I);
981
Steve Naroff752d6ef2007-10-30 16:42:30 +0000982 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +0000983 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000984 ReplaceText(LocEnd, 0, "// ");
Steve Naroff8cc764c2007-11-14 15:03:57 +0000985
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000986 // Must comment out @optional/@required
987 const char *startBuf = SM->getCharacterData(LocStart);
988 const char *endBuf = SM->getCharacterData(LocEnd);
989 for (const char *p = startBuf; p < endBuf; p++) {
990 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Steve Naroff8cc764c2007-11-14 15:03:57 +0000991 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000992 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump1eb44332009-09-09 15:08:12 +0000993
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000994 }
995 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Steve Naroff8cc764c2007-11-14 15:03:57 +0000996 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000997 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump1eb44332009-09-09 15:08:12 +0000998
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000999 }
1000 }
Steve Naroff752d6ef2007-10-30 16:42:30 +00001001}
1002
Steve Naroffb29b4272008-04-14 22:03:09 +00001003void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001004 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +00001005 if (LocStart.isInvalid())
1006 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001007 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001008 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001009}
1010
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001011void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1012 const FunctionType *&FPRetType) {
1013 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001014 ResultStr += "id";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001015 else if (T->isFunctionPointerType() ||
1016 T->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001017 // needs special handling, since pointer-to-functions have special
1018 // syntax (where a decaration models use).
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001019 QualType retType = T;
Steve Narofff4312dc2008-12-11 19:29:16 +00001020 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001021 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001022 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001023 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001024 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001025 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Steve Narofff4312dc2008-12-11 19:29:16 +00001026 ResultStr += FPRetType->getResultType().getAsString();
1027 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +00001028 }
1029 } else
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001030 ResultStr += T.getAsString();
1031}
1032
1033void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
1034 std::string &ResultStr) {
1035 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1036 const FunctionType *FPRetType = 0;
1037 ResultStr += "\nstatic ";
1038 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001039 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +00001040
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001041 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001042 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001043
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001044 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001045 NameStr += "_I_";
1046 else
1047 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +00001048
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001049 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001050 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +00001051
1052 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +00001053 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001054 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001055 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001056 }
Mike Stump1eb44332009-09-09 15:08:12 +00001057 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +00001058 {
1059 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001060 int len = selString.size();
1061 for (int i = 0; i < len; i++)
1062 if (selString[i] == ':')
1063 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001064 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001065 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001066 // Remember this name for metadata emission
1067 MethodInternalNames[OMD] = NameStr;
1068 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001069
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001070 // Rewrite arguments
1071 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +00001072
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001073 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001074 if (OMD->isInstanceMethod()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001075 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001076 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +00001077 if (!LangOpts.Microsoft) {
1078 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
1079 ResultStr += "struct ";
1080 }
1081 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001082 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001083 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001084 }
1085 else
Steve Naroff621edce2009-04-29 16:37:50 +00001086 ResultStr += Context->getObjCClassType().getAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00001087
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001088 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001089 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001090 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +00001091
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001092 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +00001093 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1094 E = OMD->param_end(); PI != E; ++PI) {
1095 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001096 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +00001097 if (PDecl->getType()->isObjCQualifiedIdType()) {
1098 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001099 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +00001100 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001101 std::string Name = PDecl->getNameAsString();
Steve Naroff01f2ffa2008-12-11 21:05:33 +00001102 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroffc8ad87b2008-10-30 14:45:29 +00001103 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Ted Kremenek6217b802009-07-29 21:53:49 +00001104 const BlockPointerType *BPT = PDecl->getType()->getAs<BlockPointerType>();
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001105 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name,
1106 Context->PrintingPolicy);
Steve Naroffc8ad87b2008-10-30 14:45:29 +00001107 } else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001108 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroff543409e2008-04-18 21:13:19 +00001109 ResultStr += Name;
1110 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001111 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001112 if (OMD->isVariadic())
1113 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001114 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001115
Steve Naroff76e429d2008-07-16 14:40:40 +00001116 if (FPRetType) {
1117 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001118
Steve Naroff76e429d2008-07-16 14:40:40 +00001119 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001120 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001121 ResultStr += "(";
1122 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1123 if (i) ResultStr += ", ";
1124 std::string ParamStr = FT->getArgType(i).getAsString();
1125 ResultStr += ParamStr;
1126 }
1127 if (FT->isVariadic()) {
1128 if (FT->getNumArgs()) ResultStr += ", ";
1129 ResultStr += "...";
1130 }
1131 ResultStr += ")";
1132 } else {
1133 ResultStr += "()";
1134 }
1135 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001136}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001137void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001138 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1139 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001140
Fariborz Jahaniana1352162010-02-15 21:11:41 +00001141 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001142
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001143 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001144 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1145 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001146 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001147 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001148 ObjCMethodDecl *OMD = *I;
1149 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001150 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001151 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001152
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001153 const char *startBuf = SM->getCharacterData(LocStart);
1154 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001155 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001156 }
Mike Stump1eb44332009-09-09 15:08:12 +00001157
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001158 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001159 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1160 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001161 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001162 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001163 ObjCMethodDecl *OMD = *I;
1164 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001165 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001166 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001167
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001168 const char *startBuf = SM->getCharacterData(LocStart);
1169 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001170 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001171 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001172 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001173 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001174 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001175 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001176 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001177 }
1178
Benjamin Kramerd999b372010-02-14 14:14:16 +00001179 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001180}
1181
Steve Naroffb29b4272008-04-14 22:03:09 +00001182void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001183 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001184 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001185 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001186 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001187 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001188 ResultStr += "\n";
1189 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001190 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001191 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001192 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001193 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001194 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001195 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001196 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001197 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001198 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001199
1200 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001201 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001202 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001203 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001204 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001205 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001206 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001207 for (ObjCInterfaceDecl::classmeth_iterator
1208 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001209 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001210 RewriteMethodDeclaration(*I);
1211
Steve Naroff2feac5e2007-10-30 03:43:13 +00001212 // Lastly, comment out the @end.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001213 ReplaceText(ClassDecl->getAtEndRange().getBegin(), 0, "// ");
Steve Naroffbef11852007-10-26 20:53:56 +00001214}
1215
Steve Naroffb619d952008-12-09 12:56:34 +00001216Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1217 SourceRange SrcRange) {
Steve Naroffc77a6362008-12-04 16:24:46 +00001218 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1219 // This allows us to reuse all the fun and games in SynthMessageExpr().
1220 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1221 ObjCMessageExpr *MsgExpr;
1222 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1223 llvm::SmallVector<Expr *, 1> ExprVec;
1224 ExprVec.push_back(newStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001225
Steve Naroff8599e7a2008-12-08 16:43:47 +00001226 Stmt *Receiver = PropRefExpr->getBase();
1227 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1228 if (PRE && PropGetters[PRE]) {
1229 // This allows us to handle chain/nested property getters.
1230 Receiver = PropGetters[PRE];
1231 }
Ted Kremenekeb3b3242010-02-11 22:41:21 +00001232 MsgExpr = new (Context) ObjCMessageExpr(*Context, dyn_cast<Expr>(Receiver),
Mike Stump1eb44332009-09-09 15:08:12 +00001233 PDecl->getSetterName(), PDecl->getType(),
1234 PDecl->getSetterMethodDecl(),
1235 SourceLocation(), SourceLocation(),
Steve Naroffc77a6362008-12-04 16:24:46 +00001236 &ExprVec[0], 1);
1237 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001238
Steve Naroffc77a6362008-12-04 16:24:46 +00001239 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001240 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001241 //delete BinOp;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001242 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1243 // to things that stay around.
1244 Context->Deallocate(MsgExpr);
Steve Naroffc77a6362008-12-04 16:24:46 +00001245 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001246}
1247
Steve Naroffc77a6362008-12-04 16:24:46 +00001248Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Naroff15f081d2008-12-03 00:56:33 +00001249 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1250 // This allows us to reuse all the fun and games in SynthMessageExpr().
1251 ObjCMessageExpr *MsgExpr;
1252 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
Mike Stump1eb44332009-09-09 15:08:12 +00001253
Steve Naroff8599e7a2008-12-08 16:43:47 +00001254 Stmt *Receiver = PropRefExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00001255
Steve Naroff8599e7a2008-12-08 16:43:47 +00001256 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1257 if (PRE && PropGetters[PRE]) {
1258 // This allows us to handle chain/nested property getters.
1259 Receiver = PropGetters[PRE];
1260 }
Ted Kremenekeb3b3242010-02-11 22:41:21 +00001261 MsgExpr = new (Context) ObjCMessageExpr(*Context, dyn_cast<Expr>(Receiver),
Mike Stump1eb44332009-09-09 15:08:12 +00001262 PDecl->getGetterName(), PDecl->getType(),
1263 PDecl->getGetterMethodDecl(),
1264 SourceLocation(), SourceLocation(),
Steve Naroff15f081d2008-12-03 00:56:33 +00001265 0, 0);
1266
Steve Naroff4c3580e2008-12-04 23:50:32 +00001267 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001268
1269 if (!PropParentMap)
1270 PropParentMap = new ParentMap(CurrentBody);
1271
1272 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1273 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1274 // We stash away the ReplacingStmt since actually doing the
1275 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1276 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001277 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1278 // to things that stay around.
1279 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001280 return PropRefExpr; // return the original...
1281 } else {
1282 ReplaceStmt(PropRefExpr, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001283 // delete PropRefExpr; elsewhere...
Ted Kremenek8189cde2009-02-07 01:47:29 +00001284 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1285 // to things that stay around.
1286 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001287 return ReplacingStmt;
1288 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001289}
1290
Mike Stump1eb44332009-09-09 15:08:12 +00001291Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001292 SourceLocation OrigStart,
1293 bool &replaced) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001294 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001295 const Expr *BaseExpr = IV->getBase();
Steve Naroff54055232008-10-27 17:20:55 +00001296 if (CurMethodDef) {
Fariborz Jahanian8f095432010-01-26 18:28:51 +00001297 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001298 ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001299 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianffbdead2010-01-26 20:37:44 +00001300 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Narofff0757612008-05-08 17:52:16 +00001301 // lookup which class implements the instance variable.
1302 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001303 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001304 clsDeclared);
Steve Narofff0757612008-05-08 17:52:16 +00001305 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001306
Steve Narofff0757612008-05-08 17:52:16 +00001307 // Synthesize an explicit cast to gain access to the ivar.
1308 std::string RecName = clsDeclared->getIdentifier()->getName();
1309 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001310 IdentifierInfo *II = &Context->Idents.get(RecName);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001311 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001312 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001313 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1314 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001315 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1316 CastExpr::CK_Unknown,
1317 IV->getBase());
Steve Narofff0757612008-05-08 17:52:16 +00001318 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001319 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1320 IV->getBase()->getLocEnd(),
1321 castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001322 replaced = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001323 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001324 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001325 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1326 IV->getLocation(),
1327 D->getType());
Steve Naroff4c3580e2008-12-04 23:50:32 +00001328 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001329 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001330 }
Fariborz Jahanian7e20ffe2010-01-28 01:41:20 +00001331 // Get the new text
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001332 // Cannot delete IV->getBase(), since PE points to it.
1333 // Replace the old base with the cast. This is important when doing
1334 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001335 IV->setBase(PE);
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001336 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001337 }
Steve Naroff84472a82008-04-18 21:55:08 +00001338 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001339 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump1eb44332009-09-09 15:08:12 +00001340
Steve Naroff9f525972008-05-06 23:20:07 +00001341 // Explicit ivar refs need to have a cast inserted.
1342 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian26337b22010-01-12 17:31:23 +00001343 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Fariborz Jahanianc374cd92010-01-11 17:50:35 +00001344 ObjCInterfaceType *iFaceDecl =
1345 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001346 // lookup which class implements the instance variable.
1347 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001348 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001349 clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001350 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001351
Steve Naroff9f525972008-05-06 23:20:07 +00001352 // Synthesize an explicit cast to gain access to the ivar.
1353 std::string RecName = clsDeclared->getIdentifier()->getName();
1354 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001355 IdentifierInfo *II = &Context->Idents.get(RecName);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001356 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001357 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001358 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1359 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001360 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1361 CastExpr::CK_Unknown,
1362 IV->getBase());
Steve Naroff9f525972008-05-06 23:20:07 +00001363 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001364 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner8d366162008-05-28 16:38:23 +00001365 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001366 replaced = true;
Steve Naroff9f525972008-05-06 23:20:07 +00001367 // Cannot delete IV->getBase(), since PE points to it.
1368 // Replace the old base with the cast. This is important when doing
1369 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001370 IV->setBase(PE);
Steve Naroff9f525972008-05-06 23:20:07 +00001371 return IV;
1372 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001373 }
Steve Naroff84472a82008-04-18 21:55:08 +00001374 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001375}
1376
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001377Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
1378 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1379 CI != E; ++CI) {
1380 if (*CI) {
1381 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1382 if (newStmt)
1383 *CI = newStmt;
1384 }
1385 }
1386 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1387 SourceRange OrigStmtRange = S->getSourceRange();
1388 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1389 replaced);
1390 return newStmt;
Fariborz Jahanian376338a2010-02-05 17:48:10 +00001391 }
1392 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1393 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1394 return newStmt;
1395 }
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001396 return S;
1397}
1398
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001399/// SynthCountByEnumWithState - To print:
1400/// ((unsigned int (*)
1401/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001402/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001403/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001404/// "countByEnumeratingWithState:objects:count:"),
1405/// &enumState,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001406/// (id *)items, (unsigned int)16)
1407///
Steve Naroffb29b4272008-04-14 22:03:09 +00001408void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001409 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1410 "id *, unsigned int))(void *)objc_msgSend)";
1411 buf += "\n\t\t";
1412 buf += "((id)l_collection,\n\t\t";
1413 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1414 buf += "\n\t\t";
1415 buf += "&enumState, "
1416 "(id *)items, (unsigned int)16)";
1417}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001418
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001419/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1420/// statement to exit to its outer synthesized loop.
1421///
Steve Naroffb29b4272008-04-14 22:03:09 +00001422Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001423 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1424 return S;
1425 // replace break with goto __break_label
1426 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001427
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001428 SourceLocation startLoc = S->getLocStart();
1429 buf = "goto __break_label_";
1430 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001431 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001432
1433 return 0;
1434}
1435
1436/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1437/// statement to continue with its inner synthesized loop.
1438///
Steve Naroffb29b4272008-04-14 22:03:09 +00001439Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001440 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1441 return S;
1442 // replace continue with goto __continue_label
1443 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001444
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001445 SourceLocation startLoc = S->getLocStart();
1446 buf = "goto __continue_label_";
1447 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001448 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001449
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001450 return 0;
1451}
1452
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001453/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001454/// It rewrites:
1455/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001456
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001457/// Into:
1458/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001459/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001460/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001461/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001462/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001463/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001464/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001465/// if (limit) {
1466/// unsigned long startMutations = *enumState.mutationsPtr;
1467/// do {
1468/// unsigned long counter = 0;
1469/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001470/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001471/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001472/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001473/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001474/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001475/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001476/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001477/// objects:items count:16]);
1478/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001479/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001480/// }
1481/// else
1482/// elem = nil;
1483/// }
1484///
Steve Naroffb29b4272008-04-14 22:03:09 +00001485Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001486 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001487 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001488 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001489 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001490 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001491 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001492
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001493 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001494 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001495 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001496 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001497 std::string buf;
1498 buf = "\n{\n\t";
1499 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1500 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001501 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001502 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001503 if (ElementType->isObjCQualifiedIdType() ||
1504 ElementType->isObjCQualifiedInterfaceType())
1505 // Simply use 'id' for all qualified types.
1506 elementTypeAsString = "id";
1507 else
1508 elementTypeAsString = ElementType.getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001509 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001510 buf += " ";
Chris Lattner8ec03f52008-11-24 03:54:41 +00001511 elementName = D->getNameAsCString();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001512 buf += elementName;
1513 buf += ";\n\t";
1514 }
Chris Lattner06767512008-04-08 05:52:18 +00001515 else {
1516 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001517 elementName = DR->getDecl()->getNameAsCString();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001518 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1519 if (VD->getType()->isObjCQualifiedIdType() ||
1520 VD->getType()->isObjCQualifiedInterfaceType())
1521 // Simply use 'id' for all qualified types.
1522 elementTypeAsString = "id";
1523 else
1524 elementTypeAsString = VD->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001525 }
Mike Stump1eb44332009-09-09 15:08:12 +00001526
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001527 // struct __objcFastEnumerationState enumState = { 0 };
1528 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1529 // id items[16];
1530 buf += "id items[16];\n\t";
1531 // id l_collection = (id)
1532 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001533 // Find start location of 'collection' the hard way!
1534 const char *startCollectionBuf = startBuf;
1535 startCollectionBuf += 3; // skip 'for'
1536 startCollectionBuf = strchr(startCollectionBuf, '(');
1537 startCollectionBuf++; // skip '('
1538 // find 'in' and skip it.
1539 while (*startCollectionBuf != ' ' ||
1540 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1541 (*(startCollectionBuf+3) != ' ' &&
1542 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1543 startCollectionBuf++;
1544 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001545
1546 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001547 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001548 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001549 SourceLocation rightParenLoc = S->getRParenLoc();
1550 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1551 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001552 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001553
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001554 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1555 // objects:items count:16];
1556 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001557 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001558 // ((unsigned int (*)
1559 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001560 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001561 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001562 // "countByEnumeratingWithState:objects:count:"),
1563 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001564 // (id *)items, (unsigned int)16);
1565 buf += "unsigned long limit =\n\t\t";
1566 SynthCountByEnumWithState(buf);
1567 buf += ";\n\t";
1568 /// if (limit) {
1569 /// unsigned long startMutations = *enumState.mutationsPtr;
1570 /// do {
1571 /// unsigned long counter = 0;
1572 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001573 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001574 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001575 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001576 buf += "if (limit) {\n\t";
1577 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1578 buf += "do {\n\t\t";
1579 buf += "unsigned long counter = 0;\n\t\t";
1580 buf += "do {\n\t\t\t";
1581 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1582 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1583 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001584 buf += " = (";
1585 buf += elementTypeAsString;
1586 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001587 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001588 ReplaceText(lparenLoc, 1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001589
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001590 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001591 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001592 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001593 /// objects:items count:16]);
1594 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001595 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001596 /// }
1597 /// else
1598 /// elem = nil;
1599 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001600 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001601 buf = ";\n\t";
1602 buf += "__continue_label_";
1603 buf += utostr(ObjCBcLabelNo.back());
1604 buf += ": ;";
1605 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001606 buf += "} while (counter < limit);\n\t";
1607 buf += "} while (limit = ";
1608 SynthCountByEnumWithState(buf);
1609 buf += ");\n\t";
1610 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001611 buf += " = ((";
1612 buf += elementTypeAsString;
1613 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001614 buf += "__break_label_";
1615 buf += utostr(ObjCBcLabelNo.back());
1616 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001617 buf += "}\n\t";
1618 buf += "else\n\t\t";
1619 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001620 buf += " = ((";
1621 buf += elementTypeAsString;
1622 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001623 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001624
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001625 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001626 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001627 if (isa<CompoundStmt>(S->getBody())) {
1628 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001629 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001630 } else {
1631 /* Need to treat single statements specially. For example:
1632 *
1633 * for (A *a in b) if (stuff()) break;
1634 * for (A *a in b) xxxyy;
1635 *
1636 * The following code simply scans ahead to the semi to find the actual end.
1637 */
1638 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1639 const char *semiBuf = strchr(stmtBuf, ';');
1640 assert(semiBuf && "Can't find ';'");
1641 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001642 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001643 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001644 Stmts.pop_back();
1645 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001646 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001647}
1648
Mike Stump1eb44332009-09-09 15:08:12 +00001649/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001650/// This routine rewrites @synchronized(expr) stmt;
1651/// into:
1652/// objc_sync_enter(expr);
1653/// @try stmt @finally { objc_sync_exit(expr); }
1654///
Steve Naroffb29b4272008-04-14 22:03:09 +00001655Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001656 // Get the start location and compute the semi location.
1657 SourceLocation startLoc = S->getLocStart();
1658 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001659
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001660 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001661
1662 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001663 buf = "objc_sync_enter((id)";
1664 const char *lparenBuf = startBuf;
1665 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramerd999b372010-02-14 14:14:16 +00001666 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001667 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1668 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001669 // been rewritten! (which implies the SourceLocation's are invalid).
1670 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001671 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001672 while (*endBuf != ')') endBuf--;
1673 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001674 buf = ");\n";
1675 // declare a new scope with two variables, _stack and _rethrow.
1676 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1677 buf += "int buf[18/*32-bit i386*/];\n";
1678 buf += "char *pointers[4];} _stack;\n";
1679 buf += "id volatile _rethrow = 0;\n";
1680 buf += "objc_exception_try_enter(&_stack);\n";
1681 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001682 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001683 startLoc = S->getSynchBody()->getLocEnd();
1684 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001685
Steve Naroffc7089f12008-08-19 13:04:19 +00001686 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001687 SourceLocation lastCurlyLoc = startLoc;
1688 buf = "}\nelse {\n";
1689 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001690 buf += "}\n";
1691 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001692 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001693
1694 std::string syncBuf;
1695 syncBuf += " objc_sync_exit(";
John McCall9d125032010-01-15 18:39:57 +00001696 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1697 CastExpr::CK_Unknown,
1698 S->getSynchExpr());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001699 std::string syncExprBufS;
1700 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001701 syncExpr->printPretty(syncExprBuf, *Context, 0,
1702 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001703 syncBuf += syncExprBuf.str();
1704 syncBuf += ");";
1705
1706 buf += syncBuf;
1707 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001708 buf += "}\n";
1709 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001710
Benjamin Kramerd999b372010-02-14 14:14:16 +00001711 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001712
1713 bool hasReturns = false;
1714 HasReturnStmts(S->getSynchBody(), hasReturns);
1715 if (hasReturns)
1716 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1717
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001718 return 0;
1719}
1720
Steve Naroffb85e77a2009-12-05 21:43:12 +00001721void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1722{
Steve Naroff8c565152008-12-05 17:03:39 +00001723 // Perform a bottom up traversal of all children.
1724 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1725 CI != E; ++CI)
1726 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001727 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001728
Steve Naroffb85e77a2009-12-05 21:43:12 +00001729 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001730 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001731 TryFinallyContainsReturnDiag);
1732 }
1733 return;
1734}
1735
Steve Naroffb85e77a2009-12-05 21:43:12 +00001736void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1737{
1738 // Perform a bottom up traversal of all children.
1739 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1740 CI != E; ++CI)
1741 if (*CI)
1742 HasReturnStmts(*CI, hasReturns);
1743
1744 if (isa<ReturnStmt>(S))
1745 hasReturns = true;
1746 return;
1747}
1748
1749void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1750 // Perform a bottom up traversal of all children.
1751 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1752 CI != E; ++CI)
1753 if (*CI) {
1754 RewriteTryReturnStmts(*CI);
1755 }
1756 if (isa<ReturnStmt>(S)) {
1757 SourceLocation startLoc = S->getLocStart();
1758 const char *startBuf = SM->getCharacterData(startLoc);
1759
1760 const char *semiBuf = strchr(startBuf, ';');
1761 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1762 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1763
1764 std::string buf;
1765 buf = "{ objc_exception_try_exit(&_stack); return";
1766
Benjamin Kramerd999b372010-02-14 14:14:16 +00001767 ReplaceText(startLoc, 6, buf);
1768 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001769 }
1770 return;
1771}
1772
1773void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1774 // Perform a bottom up traversal of all children.
1775 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1776 CI != E; ++CI)
1777 if (*CI) {
1778 RewriteSyncReturnStmts(*CI, syncExitBuf);
1779 }
1780 if (isa<ReturnStmt>(S)) {
1781 SourceLocation startLoc = S->getLocStart();
1782 const char *startBuf = SM->getCharacterData(startLoc);
1783
1784 const char *semiBuf = strchr(startBuf, ';');
1785 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1786 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1787
1788 std::string buf;
1789 buf = "{ objc_exception_try_exit(&_stack);";
1790 buf += syncExitBuf;
1791 buf += " return";
1792
Benjamin Kramerd999b372010-02-14 14:14:16 +00001793 ReplaceText(startLoc, 6, buf);
1794 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001795 }
1796 return;
1797}
1798
Steve Naroffb29b4272008-04-14 22:03:09 +00001799Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001800 // Get the start location and compute the semi location.
1801 SourceLocation startLoc = S->getLocStart();
1802 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001803
Steve Naroff75730982007-11-07 04:08:17 +00001804 assert((*startBuf == '@') && "bogus @try location");
1805
1806 std::string buf;
1807 // declare a new scope with two variables, _stack and _rethrow.
1808 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1809 buf += "int buf[18/*32-bit i386*/];\n";
1810 buf += "char *pointers[4];} _stack;\n";
1811 buf += "id volatile _rethrow = 0;\n";
1812 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001813 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001814
Benjamin Kramerd999b372010-02-14 14:14:16 +00001815 ReplaceText(startLoc, 4, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001816
Steve Naroff75730982007-11-07 04:08:17 +00001817 startLoc = S->getTryBody()->getLocEnd();
1818 startBuf = SM->getCharacterData(startLoc);
1819
1820 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001821
Steve Naroff75730982007-11-07 04:08:17 +00001822 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001823 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1824 if (catchList) {
1825 startLoc = startLoc.getFileLocWithOffset(1);
1826 buf = " /* @catch begin */ else {\n";
1827 buf += " id _caught = objc_exception_extract(&_stack);\n";
1828 buf += " objc_exception_try_enter (&_stack);\n";
1829 buf += " if (_setjmp(_stack.buf))\n";
1830 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1831 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001832
Benjamin Kramerd999b372010-02-14 14:14:16 +00001833 InsertText(startLoc, buf);
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001834 } else { /* no catch list */
1835 buf = "}\nelse {\n";
1836 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1837 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001838 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001839 }
Steve Naroff75730982007-11-07 04:08:17 +00001840 bool sawIdTypedCatch = false;
1841 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001842 while (catchList) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00001843 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001844
Mike Stump1eb44332009-09-09 15:08:12 +00001845 if (catchList == S->getCatchStmts())
Steve Naroff75730982007-11-07 04:08:17 +00001846 buf = "if ("; // we are generating code for the first catch clause
1847 else
1848 buf = "else if (";
1849 startLoc = catchList->getLocStart();
1850 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001851
Steve Naroff75730982007-11-07 04:08:17 +00001852 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001853
Steve Naroff75730982007-11-07 04:08:17 +00001854 const char *lParenLoc = strchr(startBuf, '(');
1855
Steve Naroffbe4b3332008-02-01 22:08:12 +00001856 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001857 // Now rewrite the body...
1858 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001859 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1860 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001861 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1862 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001863 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001864
Steve Naroffe12e6922008-02-01 20:02:07 +00001865 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00001866 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00001867 } else if (catchDecl) {
1868 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001869 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001870 buf += "1) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001871 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001872 sawIdTypedCatch = true;
Fariborz Jahanian66867c52010-01-12 01:22:23 +00001873 } else if (t->isObjCObjectPointerType()) {
1874 QualType InterfaceTy = t->getPointeeType();
1875 const ObjCInterfaceType *cls = // Should be a pointer to a class.
1876 InterfaceTy->getAs<ObjCInterfaceType>();
Steve Naroff75730982007-11-07 04:08:17 +00001877 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001878 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001879 buf += cls->getDecl()->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001880 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001881 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001882 }
1883 }
1884 // Now rewrite the body...
1885 lastCatchBody = catchList->getCatchBody();
1886 SourceLocation rParenLoc = catchList->getRParenLoc();
1887 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1888 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1889 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1890 assert((*rParenBuf == ')') && "bogus @catch paren location");
1891 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001892
Mike Stump1eb44332009-09-09 15:08:12 +00001893 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00001894 // declares the @catch parameter).
Benjamin Kramerd999b372010-02-14 14:14:16 +00001895 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff7ba138a2009-03-03 19:52:17 +00001896 } else {
Steve Naroff75730982007-11-07 04:08:17 +00001897 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001898 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001899 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001900 catchList = catchList->getNextCatchStmt();
1901 }
1902 // Complete the catch list...
1903 if (lastCatchBody) {
1904 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001905 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1906 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001907
Steve Naroff378f47a2008-09-11 15:29:03 +00001908 // Insert the last (implicit) else clause *before* the right curly brace.
1909 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1910 buf = "} /* last catch end */\n";
1911 buf += "else {\n";
1912 buf += " _rethrow = _caught;\n";
1913 buf += " objc_exception_try_exit(&_stack);\n";
1914 buf += "} } /* @catch end */\n";
1915 if (!S->getFinallyStmt())
1916 buf += "}\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001917 InsertText(bodyLoc, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001918
Steve Naroff75730982007-11-07 04:08:17 +00001919 // Set lastCurlyLoc
1920 lastCurlyLoc = lastCatchBody->getLocEnd();
1921 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001922 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001923 startLoc = finalStmt->getLocStart();
1924 startBuf = SM->getCharacterData(startLoc);
1925 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00001926
Benjamin Kramerd999b372010-02-14 14:14:16 +00001927 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump1eb44332009-09-09 15:08:12 +00001928
Steve Naroff75730982007-11-07 04:08:17 +00001929 Stmt *body = finalStmt->getFinallyBody();
1930 SourceLocation startLoc = body->getLocStart();
1931 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001932 assert(*SM->getCharacterData(startLoc) == '{' &&
1933 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001934 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00001935 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001936
Steve Naroff75730982007-11-07 04:08:17 +00001937 startLoc = startLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001938 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Steve Naroff75730982007-11-07 04:08:17 +00001939 endLoc = endLoc.getFileLocWithOffset(-1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001940 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump1eb44332009-09-09 15:08:12 +00001941
Steve Naroff75730982007-11-07 04:08:17 +00001942 // Set lastCurlyLoc
1943 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00001944
Steve Naroff8c565152008-12-05 17:03:39 +00001945 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00001946 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001947 } else { /* no finally clause - make sure we synthesize an implicit one */
1948 buf = "{ /* implicit finally clause */\n";
1949 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1950 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1951 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001952 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001953
1954 // Now check for any return/continue/go statements within the @try.
1955 // The implicit finally clause won't called if the @try contains any
1956 // jump statements.
1957 bool hasReturns = false;
1958 HasReturnStmts(S->getTryBody(), hasReturns);
1959 if (hasReturns)
1960 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00001961 }
1962 // Now emit the final closing curly brace...
1963 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001964 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001965 return 0;
1966}
1967
Steve Naroffb29b4272008-04-14 22:03:09 +00001968Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001969 return 0;
1970}
1971
Steve Naroffb29b4272008-04-14 22:03:09 +00001972Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001973 return 0;
1974}
1975
Mike Stump1eb44332009-09-09 15:08:12 +00001976// This can't be done with ReplaceStmt(S, ThrowExpr), since
1977// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00001978// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001979Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001980 // Get the start location and compute the semi location.
1981 SourceLocation startLoc = S->getLocStart();
1982 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001983
Steve Naroff2bd03922007-11-07 15:32:26 +00001984 assert((*startBuf == '@') && "bogus @throw location");
1985
1986 std::string buf;
1987 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001988 if (S->getThrowExpr())
1989 buf = "objc_exception_throw(";
1990 else // add an implicit argument
1991 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00001992
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001993 // handle "@ throw" correctly.
1994 const char *wBuf = strchr(startBuf, 'w');
1995 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramerd999b372010-02-14 14:14:16 +00001996 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001997
Steve Naroff2bd03922007-11-07 15:32:26 +00001998 const char *semiBuf = strchr(startBuf, ';');
1999 assert((*semiBuf == ';') && "@throw: can't find ';'");
2000 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002001 ReplaceText(semiLoc, 1, ");");
Steve Naroff2bd03922007-11-07 15:32:26 +00002002 return 0;
2003}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002004
Steve Naroffb29b4272008-04-14 22:03:09 +00002005Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00002006 // Create a new string expression.
2007 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002008 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002009 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattner2085fd62009-02-18 06:40:38 +00002010 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
2011 StrEncoding.length(), false,StrType,
2012 SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002013 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00002014
Chris Lattner07506182007-11-30 22:53:43 +00002015 // Replace this subexpr in the parent.
Steve Naroff4c3580e2008-12-04 23:50:32 +00002016 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00002017 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00002018}
2019
Steve Naroffb29b4272008-04-14 22:03:09 +00002020Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00002021 if (!SelGetUidFunctionDecl)
2022 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00002023 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2024 // Create a call to sel_registerName("selName").
2025 llvm::SmallVector<Expr*, 8> SelExprs;
2026 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002027 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002028 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002029 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002030 false, argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00002031 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2032 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002033 ReplaceStmt(Exp, SelExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002034 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00002035 return SelExp;
2036}
2037
Steve Naroffb29b4272008-04-14 22:03:09 +00002038CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002039 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2040 SourceLocation EndLoc) {
Steve Naroffebf2b562007-10-23 23:50:29 +00002041 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00002042 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002043
Steve Naroffebf2b562007-10-23 23:50:29 +00002044 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002045 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002046
Steve Naroffebf2b562007-10-23 23:50:29 +00002047 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00002048 QualType pToFunc = Context->getPointerType(msgSendType);
Mike Stump1eb44332009-09-09 15:08:12 +00002049 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc,
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002050 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002051 DRE,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002052 /*isLvalue=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002053
John McCall183700f2009-09-21 23:43:11 +00002054 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002055
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002056 CallExpr *Exp =
2057 new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
2058 EndLoc);
2059 return Exp;
Steve Naroff934f2762007-10-24 22:48:43 +00002060}
2061
Steve Naroffd5255f52007-11-01 13:24:47 +00002062static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2063 const char *&startRef, const char *&endRef) {
2064 while (startBuf < endBuf) {
2065 if (*startBuf == '<')
2066 startRef = startBuf; // mark the start.
2067 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00002068 if (startRef && *startRef == '<') {
2069 endRef = startBuf; // mark the end.
2070 return true;
2071 }
2072 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002073 }
2074 startBuf++;
2075 }
2076 return false;
2077}
2078
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002079static void scanToNextArgument(const char *&argRef) {
2080 int angle = 0;
2081 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2082 if (*argRef == '<')
2083 angle++;
2084 else if (*argRef == '>')
2085 angle--;
2086 argRef++;
2087 }
2088 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2089}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002090
Steve Naroffb29b4272008-04-14 22:03:09 +00002091bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002092 if (T->isObjCQualifiedIdType())
2093 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002094 if (const PointerType *PT = T->getAs<PointerType>()) {
2095 if (PT->getPointeeType()->isObjCQualifiedIdType())
2096 return true;
2097 }
2098 if (T->isObjCObjectPointerType()) {
2099 T = T->getPointeeType();
2100 return T->isObjCQualifiedInterfaceType();
2101 }
2102 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002103}
2104
Steve Naroff4f95b752008-07-29 18:15:38 +00002105void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2106 QualType Type = E->getType();
2107 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002108 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002109
Steve Naroffcda658e2008-11-19 21:15:47 +00002110 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2111 Loc = ECE->getLParenLoc();
2112 EndLoc = ECE->getRParenLoc();
2113 } else {
2114 Loc = E->getLocStart();
2115 EndLoc = E->getLocEnd();
2116 }
2117 // This will defend against trying to rewrite synthesized expressions.
2118 if (Loc.isInvalid() || EndLoc.isInvalid())
2119 return;
2120
Steve Naroff4f95b752008-07-29 18:15:38 +00002121 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002122 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002123 const char *startRef = 0, *endRef = 0;
2124 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2125 // Get the locations of the startRef, endRef.
2126 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2127 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2128 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002129 InsertText(LessLoc, "/*");
2130 InsertText(GreaterLoc, "*/");
Steve Naroff4f95b752008-07-29 18:15:38 +00002131 }
2132 }
2133}
2134
Steve Naroffb29b4272008-04-14 22:03:09 +00002135void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002136 SourceLocation Loc;
2137 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002138 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002139 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2140 Loc = VD->getLocation();
2141 Type = VD->getType();
2142 }
2143 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2144 Loc = FD->getLocation();
2145 // Check for ObjC 'id' and class types that have been adorned with protocol
2146 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002147 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002148 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002149 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002150 if (!proto)
2151 return;
2152 Type = proto->getResultType();
2153 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002154 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2155 Loc = FD->getLocation();
2156 Type = FD->getType();
2157 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002158 else
2159 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002160
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002161 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002162 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002163
Steve Naroffd5255f52007-11-01 13:24:47 +00002164 const char *endBuf = SM->getCharacterData(Loc);
2165 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002166 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002167 startBuf--; // scan backward (from the decl location) for return type.
2168 const char *startRef = 0, *endRef = 0;
2169 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2170 // Get the locations of the startRef, endRef.
2171 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2172 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2173 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002174 InsertText(LessLoc, "/*");
2175 InsertText(GreaterLoc, "*/");
Steve Naroff9165ad32007-10-31 04:38:33 +00002176 }
2177 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002178 if (!proto)
2179 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002180 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002181 const char *startBuf = SM->getCharacterData(Loc);
2182 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002183 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2184 if (needToScanForQualifiers(proto->getArgType(i))) {
2185 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002186
Steve Naroffd5255f52007-11-01 13:24:47 +00002187 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002188 // scan forward (from the decl location) for argument types.
2189 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002190 const char *startRef = 0, *endRef = 0;
2191 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2192 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002193 SourceLocation LessLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002194 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002195 SourceLocation GreaterLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002196 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002197 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002198 InsertText(LessLoc, "/*");
2199 InsertText(GreaterLoc, "*/");
Steve Naroffd5255f52007-11-01 13:24:47 +00002200 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002201 startBuf = ++endBuf;
2202 }
2203 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002204 // If the function name is derived from a macro expansion, then the
2205 // argument buffer will not follow the name. Need to speak with Chris.
2206 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002207 startBuf++; // scan forward (from the decl location) for argument types.
2208 startBuf++;
2209 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002210 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002211}
2212
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002213void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2214 QualType QT = ND->getType();
2215 const Type* TypePtr = QT->getAs<Type>();
2216 if (!isa<TypeOfExprType>(TypePtr))
2217 return;
2218 while (isa<TypeOfExprType>(TypePtr)) {
2219 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2220 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2221 TypePtr = QT->getAs<Type>();
2222 }
2223 // FIXME. This will not work for multiple declarators; as in:
2224 // __typeof__(a) b,c,d;
2225 std::string TypeAsString(QT.getAsString());
2226 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2227 const char *startBuf = SM->getCharacterData(DeclLoc);
2228 if (ND->getInit()) {
2229 std::string Name(ND->getNameAsString());
2230 TypeAsString += " " + Name + " = ";
2231 Expr *E = ND->getInit();
2232 SourceLocation startLoc;
2233 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2234 startLoc = ECE->getLParenLoc();
2235 else
2236 startLoc = E->getLocStart();
2237 startLoc = SM->getInstantiationLoc(startLoc);
2238 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002239 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002240 }
2241 else {
2242 SourceLocation X = ND->getLocEnd();
2243 X = SM->getInstantiationLoc(X);
2244 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002245 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002246 }
2247}
2248
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002249// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002250void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002251 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2252 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002253 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002254 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002255 &ArgTys[0], ArgTys.size(),
2256 false /*isVariadic*/, 0,
2257 false, false, 0, 0, false,
2258 CC_Default);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002259 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002260 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002261 SelGetUidIdent, getFuncType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002262 FunctionDecl::Extern, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002263}
2264
Steve Naroffb29b4272008-04-14 22:03:09 +00002265void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002266 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002267 if (FD->getIdentifier() &&
2268 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002269 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002270 return;
2271 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002272 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002273}
2274
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002275static void RewriteBlockPointerType(std::string& Str, QualType Type) {
2276 std::string TypeString(Type.getAsString());
2277 const char *argPtr = TypeString.c_str();
2278 if (!strchr(argPtr, '^')) {
2279 Str += TypeString;
2280 return;
2281 }
2282 while (*argPtr) {
2283 Str += (*argPtr == '^' ? '*' : *argPtr);
2284 argPtr++;
2285 }
2286}
2287
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002288// FIXME. Consolidate this routine with RewriteBlockPointerType.
2289static void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD) {
2290 QualType Type = VD->getType();
2291 std::string TypeString(Type.getAsString());
2292 const char *argPtr = TypeString.c_str();
2293 int paren = 0;
2294 while (*argPtr) {
2295 switch (*argPtr) {
2296 case '(':
2297 Str += *argPtr;
2298 paren++;
2299 break;
2300 case ')':
2301 Str += *argPtr;
2302 paren--;
2303 break;
2304 case '^':
2305 Str += '*';
2306 if (paren == 1)
2307 Str += VD->getNameAsString();
2308 break;
2309 default:
2310 Str += *argPtr;
2311 break;
2312 }
2313 argPtr++;
2314 }
2315}
2316
2317
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002318void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2319 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2320 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2321 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2322 if (!proto)
2323 return;
2324 QualType Type = proto->getResultType();
2325 std::string FdStr = Type.getAsString();
2326 FdStr += " ";
2327 FdStr += FD->getNameAsCString();
2328 FdStr += "(";
2329 unsigned numArgs = proto->getNumArgs();
2330 for (unsigned i = 0; i < numArgs; i++) {
2331 QualType ArgType = proto->getArgType(i);
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002332 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002333 if (i+1 < numArgs)
2334 FdStr += ", ";
2335 }
2336 FdStr += ");\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002337 InsertText(FunLocStart, FdStr);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002338 CurFunctionDeclToDeclareForBlock = 0;
2339}
2340
Steve Naroffc0a123c2008-03-11 17:37:02 +00002341// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002342void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002343 if (SuperContructorFunctionDecl)
2344 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002345 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroffc0a123c2008-03-11 17:37:02 +00002346 llvm::SmallVector<QualType, 16> ArgTys;
2347 QualType argT = Context->getObjCIdType();
2348 assert(!argT.isNull() && "Can't find 'id' type");
2349 ArgTys.push_back(argT);
2350 ArgTys.push_back(argT);
2351 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2352 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002353 false, 0,
2354 false, false, 0, 0, false,
2355 CC_Default);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002356 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002357 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002358 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002359 FunctionDecl::Extern, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002360}
2361
Steve Naroff09b266e2007-10-30 23:14:51 +00002362// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002363void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002364 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2365 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002366 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002367 assert(!argT.isNull() && "Can't find 'id' type");
2368 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002369 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002370 assert(!argT.isNull() && "Can't find 'SEL' type");
2371 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002372 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002373 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002374 true /*isVariadic*/, 0,
2375 false, false, 0, 0, false,
2376 CC_Default);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002377 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002378 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002379 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002380 FunctionDecl::Extern, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002381}
2382
Steve Naroff874e2322007-11-15 10:28:18 +00002383// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002384void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002385 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2386 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002387 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002388 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002389 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002390 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2391 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2392 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002393 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002394 assert(!argT.isNull() && "Can't find 'SEL' type");
2395 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002396 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00002397 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002398 true /*isVariadic*/, 0,
2399 false, false, 0, 0, false,
2400 CC_Default);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002401 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002402 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002403 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002404 FunctionDecl::Extern, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002405}
2406
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002407// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002408void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002409 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2410 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002411 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002412 assert(!argT.isNull() && "Can't find 'id' type");
2413 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002414 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002415 assert(!argT.isNull() && "Can't find 'SEL' type");
2416 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002417 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002418 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002419 true /*isVariadic*/, 0,
2420 false, false, 0, 0, false,
2421 CC_Default);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002422 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002423 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002424 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002425 FunctionDecl::Extern, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002426}
2427
Mike Stump1eb44332009-09-09 15:08:12 +00002428// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002429// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002430void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002431 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002432 &Context->Idents.get("objc_msgSendSuper_stret");
2433 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002434 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002435 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002436 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002437 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2438 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2439 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002440 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002441 assert(!argT.isNull() && "Can't find 'SEL' type");
2442 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002443 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002444 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002445 true /*isVariadic*/, 0,
2446 false, false, 0, 0, false,
2447 CC_Default);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002448 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002449 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002450 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002451 FunctionDecl::Extern, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002452}
2453
Steve Naroff1284db82008-05-08 22:02:18 +00002454// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002455void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002456 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2457 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002458 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002459 assert(!argT.isNull() && "Can't find 'id' type");
2460 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002461 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002462 assert(!argT.isNull() && "Can't find 'SEL' type");
2463 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00002464 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002465 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002466 true /*isVariadic*/, 0,
2467 false, false, 0, 0, false,
2468 CC_Default);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002469 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002470 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002471 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002472 FunctionDecl::Extern, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002473}
2474
Steve Naroff09b266e2007-10-30 23:14:51 +00002475// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002476void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002477 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2478 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002479 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002480 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002481 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002482 false /*isVariadic*/, 0,
2483 false, false, 0, 0, false,
2484 CC_Default);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002485 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002486 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002487 getClassIdent, getClassType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002488 FunctionDecl::Extern, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002489}
2490
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002491// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002492void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002493 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2494 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002495 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002496 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002497 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002498 false /*isVariadic*/, 0,
2499 false, false, 0, 0, false,
2500 CC_Default);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002501 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002502 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002503 getClassIdent, getClassType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002504 FunctionDecl::Extern, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002505}
2506
Steve Naroffb29b4272008-04-14 22:03:09 +00002507Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002508 QualType strType = getConstantStringStructType();
2509
2510 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002511
2512 std::string tmpName = InFileName;
2513 unsigned i;
2514 for (i=0; i < tmpName.length(); i++) {
2515 char c = tmpName.at(i);
2516 // replace any non alphanumeric characters with '_'.
2517 if (!isalpha(c) && (c < '0' || c > '9'))
2518 tmpName[i] = '_';
2519 }
2520 S += tmpName;
2521 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002522 S += utostr(NumObjCStringLiterals++);
2523
Steve Naroffba92b2e2008-03-27 22:29:16 +00002524 Preamble += "static __NSConstantStringImpl " + S;
2525 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2526 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002527 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002528 std::string prettyBufS;
2529 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002530 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2531 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002532 Preamble += prettyBuf.str();
2533 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002534 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002535
2536 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Benjamin Kramerd999b372010-02-14 14:14:16 +00002537 &Context->Idents.get(S), strType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002538 VarDecl::Static);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002539 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2540 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002541 Context->getPointerType(DRE->getType()),
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002542 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002543 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002544 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2545 CastExpr::CK_Unknown, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002546 ReplaceStmt(Exp, cast);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002547 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002548 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002549}
2550
Steve Naroffb29b4272008-04-14 22:03:09 +00002551ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002552 // check if we are sending a message to 'super'
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002553 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002554
Douglas Gregorcd9b46e2008-11-04 14:56:14 +00002555 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002556 const ObjCObjectPointerType *OPT =
John McCall183700f2009-09-21 23:43:11 +00002557 Super->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00002558 assert(OPT);
2559 const ObjCInterfaceType *IT = OPT->getInterfaceType();
Chris Lattner0d17f6f2008-06-21 18:04:54 +00002560 return IT->getDecl();
2561 }
2562 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00002563}
2564
2565// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002566QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002567 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002568 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002569 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002570 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002571 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002572
Steve Naroff874e2322007-11-15 10:28:18 +00002573 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002574 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002575 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002576 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002577
Steve Naroff874e2322007-11-15 10:28:18 +00002578 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002579 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002580 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2581 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002582 FieldTypes[i], 0,
2583 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002584 /*Mutable=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002585 }
Mike Stump1eb44332009-09-09 15:08:12 +00002586
Douglas Gregor838db382010-02-11 01:19:42 +00002587 SuperStructDecl->completeDefinition();
Steve Naroff874e2322007-11-15 10:28:18 +00002588 }
2589 return Context->getTagDeclType(SuperStructDecl);
2590}
2591
Steve Naroffb29b4272008-04-14 22:03:09 +00002592QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002593 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002594 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002595 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002596 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002597 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002598
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002599 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002600 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002601 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002602 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002603 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002604 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002605 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002606 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002607
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002608 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002609 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002610 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2611 ConstantStringDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002612 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002613 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002614 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002615 /*Mutable=*/true));
Douglas Gregor44b43212008-12-11 16:49:14 +00002616 }
2617
Douglas Gregor838db382010-02-11 01:19:42 +00002618 ConstantStringDecl->completeDefinition();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002619 }
2620 return Context->getTagDeclType(ConstantStringDecl);
2621}
2622
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002623Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2624 SourceLocation StartLoc,
2625 SourceLocation EndLoc) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002626 if (!SelGetUidFunctionDecl)
2627 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002628 if (!MsgSendFunctionDecl)
2629 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002630 if (!MsgSendSuperFunctionDecl)
2631 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002632 if (!MsgSendStretFunctionDecl)
2633 SynthMsgSendStretFunctionDecl();
2634 if (!MsgSendSuperStretFunctionDecl)
2635 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002636 if (!MsgSendFpretFunctionDecl)
2637 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002638 if (!GetClassFunctionDecl)
2639 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002640 if (!GetMetaClassFunctionDecl)
2641 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002642
Steve Naroff874e2322007-11-15 10:28:18 +00002643 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002644 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2645 // May need to use objc_msgSend_stret() as well.
2646 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002647 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2648 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002649 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002650 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002651 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002652 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002653 }
Mike Stump1eb44332009-09-09 15:08:12 +00002654
Steve Naroff934f2762007-10-24 22:48:43 +00002655 // Synthesize a call to objc_msgSend().
2656 llvm::SmallVector<Expr*, 8> MsgExprs;
2657 IdentifierInfo *clsName = Exp->getClassName();
Mike Stump1eb44332009-09-09 15:08:12 +00002658
Steve Naroff934f2762007-10-24 22:48:43 +00002659 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2660 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002661 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2662 // the 'super' idiom within a class method.
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00002663 if (clsName->getName() == "super") {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002664 MsgSendFlavor = MsgSendSuperFunctionDecl;
2665 if (MsgSendStretFlavor)
2666 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2667 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002668
2669 ObjCInterfaceDecl *SuperDecl =
Steve Naroff54055232008-10-27 17:20:55 +00002670 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002671
2672 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00002673
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002674 // set the receiver to self, the first argument to all methods.
Steve Naroff621edce2009-04-29 16:37:50 +00002675 InitExprs.push_back(
John McCall9d125032010-01-15 18:39:57 +00002676 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2677 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002678 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff621edce2009-04-29 16:37:50 +00002679 Context->getObjCIdType(),
John McCall9d125032010-01-15 18:39:57 +00002680 SourceLocation()))
2681 ); // set the 'receiver'.
Steve Naroff621edce2009-04-29 16:37:50 +00002682
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002683 llvm::SmallVector<Expr*, 8> ClsExprs;
2684 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002685 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbare013d682009-10-18 20:26:12 +00002686 SuperDecl->getIdentifier()->getNameStart(),
2687 SuperDecl->getIdentifier()->getLength(),
2688 false, argType, SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002689 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002690 &ClsExprs[0],
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002691 ClsExprs.size(),
2692 StartLoc,
2693 EndLoc);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002694 // To turn off a warning, type-cast to 'id'
Douglas Gregor49badde2008-10-27 19:41:14 +00002695 InitExprs.push_back( // set 'super class', using objc_getClass().
John McCall9d125032010-01-15 18:39:57 +00002696 NoTypeInfoCStyleCastExpr(Context,
2697 Context->getObjCIdType(),
2698 CastExpr::CK_Unknown, Cls));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002699 // struct objc_super
2700 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002701 Expr *SuperRep;
Mike Stump1eb44332009-09-09 15:08:12 +00002702
Steve Naroff23f41272008-03-11 18:14:26 +00002703 if (LangOpts.Microsoft) {
2704 SynthSuperContructorFunctionDecl();
2705 // Simulate a contructor call...
Mike Stump1eb44332009-09-09 15:08:12 +00002706 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff23f41272008-03-11 18:14:26 +00002707 superType, SourceLocation());
Ted Kremenek668bf912009-02-09 20:51:47 +00002708 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002709 InitExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002710 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002711 // The code for super is a little tricky to prevent collision with
2712 // the structure definition in the header. The rewriter has it's own
2713 // internal definition (__rw_objc_super) that is uses. This is why
2714 // we need the cast below. For example:
2715 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2716 //
Ted Kremenek8189cde2009-02-07 01:47:29 +00002717 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002718 Context->getPointerType(SuperRep->getType()),
Steve Naroff46a98a72008-12-23 20:11:22 +00002719 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00002720 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2721 Context->getPointerType(superType),
2722 CastExpr::CK_Unknown, SuperRep);
Mike Stump1eb44332009-09-09 15:08:12 +00002723 } else {
Steve Naroff23f41272008-03-11 18:14:26 +00002724 // (struct objc_super) { <exprs from above> }
Ted Kremenekba7bc552010-02-19 01:50:18 +00002725 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2726 &InitExprs[0], InitExprs.size(),
2727 SourceLocation());
John McCall42f56b52010-01-18 19:35:47 +00002728 TypeSourceInfo *superTInfo
2729 = Context->getTrivialTypeSourceInfo(superType);
John McCall1d7d8d62010-01-19 22:33:45 +00002730 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2731 superType, ILE, false);
Steve Naroff46a98a72008-12-23 20:11:22 +00002732 // struct objc_super *
Ted Kremenek8189cde2009-02-07 01:47:29 +00002733 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002734 Context->getPointerType(SuperRep->getType()),
Steve Naroff46a98a72008-12-23 20:11:22 +00002735 SourceLocation());
Steve Naroff23f41272008-03-11 18:14:26 +00002736 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002737 MsgExprs.push_back(SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002738 } else {
2739 llvm::SmallVector<Expr*, 8> ClsExprs;
2740 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002741 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbare013d682009-10-18 20:26:12 +00002742 clsName->getNameStart(),
Chris Lattner2085fd62009-02-18 06:40:38 +00002743 clsName->getLength(),
2744 false, argType,
2745 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002746 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002747 &ClsExprs[0],
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002748 ClsExprs.size(),
2749 StartLoc, EndLoc);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002750 MsgExprs.push_back(Cls);
2751 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002752 } else { // instance message.
2753 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002754
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002755 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002756 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002757 if (MsgSendStretFlavor)
2758 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002759 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002760
Steve Naroff874e2322007-11-15 10:28:18 +00002761 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00002762
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002763 InitExprs.push_back(
John McCall9d125032010-01-15 18:39:57 +00002764 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2765 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002766 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002767 Context->getObjCIdType(),
John McCall9d125032010-01-15 18:39:57 +00002768 SourceLocation()))
2769 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002770
Steve Naroff874e2322007-11-15 10:28:18 +00002771 llvm::SmallVector<Expr*, 8> ClsExprs;
2772 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002773 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbare013d682009-10-18 20:26:12 +00002774 SuperDecl->getIdentifier()->getNameStart(),
2775 SuperDecl->getIdentifier()->getLength(),
2776 false, argType, SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002777 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002778 &ClsExprs[0],
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002779 ClsExprs.size(),
2780 StartLoc, EndLoc);
Fariborz Jahanian71274312007-12-05 17:29:46 +00002781 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002782 InitExprs.push_back(
Douglas Gregor49badde2008-10-27 19:41:14 +00002783 // set 'super class', using objc_getClass().
John McCall9d125032010-01-15 18:39:57 +00002784 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2785 CastExpr::CK_Unknown, Cls));
Steve Naroff874e2322007-11-15 10:28:18 +00002786 // struct objc_super
2787 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002788 Expr *SuperRep;
Mike Stump1eb44332009-09-09 15:08:12 +00002789
Steve Naroffc0a123c2008-03-11 17:37:02 +00002790 if (LangOpts.Microsoft) {
2791 SynthSuperContructorFunctionDecl();
2792 // Simulate a contructor call...
Mike Stump1eb44332009-09-09 15:08:12 +00002793 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroffc0a123c2008-03-11 17:37:02 +00002794 superType, SourceLocation());
Ted Kremenek668bf912009-02-09 20:51:47 +00002795 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002796 InitExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002797 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002798 // The code for super is a little tricky to prevent collision with
2799 // the structure definition in the header. The rewriter has it's own
2800 // internal definition (__rw_objc_super) that is uses. This is why
2801 // we need the cast below. For example:
2802 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2803 //
Ted Kremenek8189cde2009-02-07 01:47:29 +00002804 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002805 Context->getPointerType(SuperRep->getType()),
Steve Naroff46a98a72008-12-23 20:11:22 +00002806 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00002807 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2808 Context->getPointerType(superType),
2809 CastExpr::CK_Unknown, SuperRep);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002810 } else {
2811 // (struct objc_super) { <exprs from above> }
Ted Kremenekba7bc552010-02-19 01:50:18 +00002812 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2813 &InitExprs[0], InitExprs.size(),
2814 SourceLocation());
John McCall42f56b52010-01-18 19:35:47 +00002815 TypeSourceInfo *superTInfo
2816 = Context->getTrivialTypeSourceInfo(superType);
John McCall1d7d8d62010-01-19 22:33:45 +00002817 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2818 superType, ILE, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002819 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002820 MsgExprs.push_back(SuperRep);
Steve Naroff874e2322007-11-15 10:28:18 +00002821 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002822 // Remove all type-casts because it may contain objc-style types; e.g.
2823 // Foo<Proto> *.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002824 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002825 recExpr = CE->getSubExpr();
John McCall9d125032010-01-15 18:39:57 +00002826 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2827 CastExpr::CK_Unknown, recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +00002828 MsgExprs.push_back(recExpr);
2829 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002830 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002831 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002832 llvm::SmallVector<Expr*, 8> SelExprs;
2833 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002834 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002835 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002836 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002837 false, argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00002838 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002839 &SelExprs[0], SelExprs.size(),
2840 StartLoc,
2841 EndLoc);
Steve Naroff934f2762007-10-24 22:48:43 +00002842 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002843
Steve Naroff934f2762007-10-24 22:48:43 +00002844 // Now push any user supplied arguments.
2845 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002846 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002847 // Make all implicit casts explicit...ICE comes in handy:-)
2848 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2849 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002850 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002851 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002852 : ICE->getType();
John McCall9d125032010-01-15 18:39:57 +00002853 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CastExpr::CK_Unknown,
2854 userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002855 }
2856 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002857 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002858 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002859 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002860 userExpr = CE->getSubExpr();
John McCall9d125032010-01-15 18:39:57 +00002861 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2862 CastExpr::CK_Unknown, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002863 }
Mike Stump1eb44332009-09-09 15:08:12 +00002864 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002865 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00002866 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2867 // out the argument in the original expression (since we aren't deleting
2868 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2869 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00002870 }
Steve Naroffab972d32007-11-04 22:37:50 +00002871 // Generate the funky cast.
2872 CastExpr *cast;
2873 llvm::SmallVector<QualType, 8> ArgTypes;
2874 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00002875
Steve Naroffab972d32007-11-04 22:37:50 +00002876 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002877 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2878 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2879 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002880 ArgTypes.push_back(Context->getObjCIdType());
2881 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00002882 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002883 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00002884 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2885 E = OMD->param_end(); PI != E; ++PI) {
2886 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00002887 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00002888 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002889 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00002890 if (isTopLevelBlockPointerType(t)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002891 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroffa206b062008-10-29 14:49:46 +00002892 t = Context->getPointerType(BPT->getPointeeType());
2893 }
Steve Naroff352336b2007-11-05 14:36:37 +00002894 ArgTypes.push_back(t);
2895 }
Chris Lattner89951a82009-02-20 18:43:26 +00002896 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2897 ? Context->getObjCIdType() : OMD->getResultType();
Fariborz Jahanian86aa9fd2010-02-24 01:25:40 +00002898 if (isTopLevelBlockPointerType(returnType)) {
2899 const BlockPointerType *BPT = returnType->getAs<BlockPointerType>();
2900 returnType = Context->getPointerType(BPT->getPointeeType());
2901 }
Steve Naroffab972d32007-11-04 22:37:50 +00002902 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002903 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002904 }
2905 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002906 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002907
Steve Naroffab972d32007-11-04 22:37:50 +00002908 // Create a reference to the objc_msgSend() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002909 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002910 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002911
Mike Stump1eb44332009-09-09 15:08:12 +00002912 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00002913 // If we don't do this cast, we get the following bizarre warning/note:
2914 // xx.m:13: warning: function called through a non-compatible type
2915 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00002916 cast = NoTypeInfoCStyleCastExpr(Context,
2917 Context->getPointerType(Context->VoidTy),
2918 CastExpr::CK_Unknown, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00002919
Steve Naroffab972d32007-11-04 22:37:50 +00002920 // Now do the "normal" pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00002921 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002922 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002923 // If we don't have a method decl, force a variadic cast.
Douglas Gregorce056bc2010-02-21 22:15:06 +00002924 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0,
2925 false, false, 0, 0, false,
2926 CC_Default);
Steve Naroffab972d32007-11-04 22:37:50 +00002927 castType = Context->getPointerType(castType);
John McCall9d125032010-01-15 18:39:57 +00002928 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
2929 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00002930
2931 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002932 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump1eb44332009-09-09 15:08:12 +00002933
John McCall183700f2009-09-21 23:43:11 +00002934 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00002935 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002936 MsgExprs.size(),
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002937 FT->getResultType(), EndLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002938 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002939 if (MsgSendStretFlavor) {
2940 // We have the method which returns a struct/union. Must also generate
2941 // call to objc_msgSend_stret and hang both varieties on a conditional
2942 // expression which dictate which one to envoke depending on size of
2943 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00002944
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002945 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002946 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002947 SourceLocation());
2948 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall9d125032010-01-15 18:39:57 +00002949 cast = NoTypeInfoCStyleCastExpr(Context,
2950 Context->getPointerType(Context->VoidTy),
2951 CastExpr::CK_Unknown, STDRE);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002952 // Now do the "normal" pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00002953 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002954 &ArgTypes[0], ArgTypes.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002955 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0,
2956 false, false, 0, 0, false,
2957 CC_Default);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002958 castType = Context->getPointerType(castType);
John McCall9d125032010-01-15 18:39:57 +00002959 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
2960 cast);
Mike Stump1eb44332009-09-09 15:08:12 +00002961
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002962 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002963 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00002964
John McCall183700f2009-09-21 23:43:11 +00002965 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00002966 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002967 MsgExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002968 FT->getResultType(), SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002969
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002970 // Build sizeof(returnType)
Mike Stump1eb44332009-09-09 15:08:12 +00002971 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCalla93c9342009-12-07 02:54:59 +00002972 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl05189992008-11-11 17:56:53 +00002973 Context->getSizeType(),
2974 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002975 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2976 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2977 // For X86 it is more complicated and some kind of target specific routine
2978 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00002979 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00002980 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Mike Stump1eb44332009-09-09 15:08:12 +00002981 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002982 Context->IntTy,
2983 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002984 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
2985 BinaryOperator::LE,
2986 Context->IntTy,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002987 SourceLocation());
2988 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00002989 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00002990 new (Context) ConditionalOperator(lessThanExpr,
2991 SourceLocation(), CE,
2992 SourceLocation(), STCE, returnType);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002993 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002994 }
Mike Stump1eb44332009-09-09 15:08:12 +00002995 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002996 return ReplacingStmt;
2997}
2998
Steve Naroffb29b4272008-04-14 22:03:09 +00002999Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003000 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3001 Exp->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00003002
Steve Naroff934f2762007-10-24 22:48:43 +00003003 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00003004 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00003005
3006 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003007 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00003008}
3009
Steve Naroff621edce2009-04-29 16:37:50 +00003010// typedef struct objc_object Protocol;
3011QualType RewriteObjC::getProtocolType() {
3012 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00003013 TypeSourceInfo *TInfo
3014 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00003015 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00003016 SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00003017 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00003018 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00003019 }
3020 return Context->getTypeDeclType(ProtocolTypeDecl);
3021}
3022
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003023/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00003024/// a synthesized/forward data reference (to the protocol's metadata).
3025/// The forward references (and metadata) are generated in
3026/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00003027Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00003028 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3029 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00003030 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregor0da76df2009-11-23 11:41:28 +00003031 ID, getProtocolType(), 0, VarDecl::Extern);
Steve Naroff621edce2009-04-29 16:37:50 +00003032 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
3033 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
3034 Context->getPointerType(DRE->getType()),
3035 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00003036 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3037 CastExpr::CK_Unknown,
3038 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003039 ReplaceStmt(Exp, castExpr);
3040 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump1eb44332009-09-09 15:08:12 +00003041 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003042 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003043
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003044}
3045
Mike Stump1eb44332009-09-09 15:08:12 +00003046bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00003047 const char *endBuf) {
3048 while (startBuf < endBuf) {
3049 if (*startBuf == '#') {
3050 // Skip whitespace.
3051 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3052 ;
3053 if (!strncmp(startBuf, "if", strlen("if")) ||
3054 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3055 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3056 !strncmp(startBuf, "define", strlen("define")) ||
3057 !strncmp(startBuf, "undef", strlen("undef")) ||
3058 !strncmp(startBuf, "else", strlen("else")) ||
3059 !strncmp(startBuf, "elif", strlen("elif")) ||
3060 !strncmp(startBuf, "endif", strlen("endif")) ||
3061 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3062 !strncmp(startBuf, "include", strlen("include")) ||
3063 !strncmp(startBuf, "import", strlen("import")) ||
3064 !strncmp(startBuf, "include_next", strlen("include_next")))
3065 return true;
3066 }
3067 startBuf++;
3068 }
3069 return false;
3070}
3071
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003072/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003073/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00003074void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003075 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003076 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Mike Stump1eb44332009-09-09 15:08:12 +00003077 assert(CDecl->getNameAsCString() &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003078 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003079 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003080 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003081 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003082 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003083 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00003084 SourceLocation LocStart = CDecl->getLocStart();
3085 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00003086
Steve Narofffea763e82007-11-14 19:25:57 +00003087 const char *startBuf = SM->getCharacterData(LocStart);
3088 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00003089
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003090 // If no ivars and no root or if its root, directly or indirectly,
3091 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003092 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3093 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00003094 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003095 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003096 return;
3097 }
Mike Stump1eb44332009-09-09 15:08:12 +00003098
3099 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003100 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003101 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003102 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00003103 if (LangOpts.Microsoft)
3104 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00003105
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003106 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00003107 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00003108 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003109 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00003110 // If the buffer contains preprocessor directives, we do more fine-grained
3111 // rewrites. This is intended to fix code that looks like (which occurs in
3112 // NSURL.h, for example):
3113 //
3114 // #ifdef XYZ
3115 // @interface Foo : NSObject
3116 // #else
3117 // @interface FooBar : NSObject
3118 // #endif
3119 // {
3120 // int i;
3121 // }
3122 // @end
3123 //
3124 // This clause is segregated to avoid breaking the common case.
3125 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003126 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffbaf58c32008-05-31 14:15:04 +00003127 CDecl->getClassLoc();
3128 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00003129 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003130
Chris Lattnercafeb352009-02-20 18:18:36 +00003131 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00003132 // advance to the end of the referenced protocols.
3133 while (endHeader < cursor && *endHeader != '>') endHeader++;
3134 endHeader++;
3135 }
3136 // rewrite the original header
Benjamin Kramerd999b372010-02-14 14:14:16 +00003137 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003138 } else {
3139 // rewrite the original header *without* disturbing the '{'
Benjamin Kramerd999b372010-02-14 14:14:16 +00003140 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003141 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003142 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00003143 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003144 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003145 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003146 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003147 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003148
Steve Narofffea763e82007-11-14 19:25:57 +00003149 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00003150 SourceLocation OnePastCurly =
3151 LocStart.getFileLocWithOffset(cursor-startBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003152 InsertText(OnePastCurly, Result);
Steve Narofffea763e82007-11-14 19:25:57 +00003153 }
3154 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00003155
Steve Narofffea763e82007-11-14 19:25:57 +00003156 // Now comment out any visibility specifiers.
3157 while (cursor < endBuf) {
3158 if (*cursor == '@') {
3159 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00003160 // Skip whitespace.
3161 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3162 /*scan*/;
3163
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003164 // FIXME: presence of @public, etc. inside comment results in
3165 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00003166 if (!strncmp(cursor, "public", strlen("public")) ||
3167 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00003168 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00003169 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramerd999b372010-02-14 14:14:16 +00003170 InsertText(atLoc, "// ");
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003171 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00003172 // FIXME: If there are cases where '<' is used in ivar declaration part
3173 // of user code, then scan the ivar list and use needToScanForQualifiers
3174 // for type checking.
3175 else if (*cursor == '<') {
3176 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003177 InsertText(atLoc, "/* ");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003178 cursor = strchr(cursor, '>');
3179 cursor++;
3180 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003181 InsertText(atLoc, " */");
Steve Naroffced80a82008-10-30 12:09:33 +00003182 } else if (*cursor == '^') { // rewrite block specifier.
3183 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003184 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003185 }
Steve Narofffea763e82007-11-14 19:25:57 +00003186 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003187 }
Steve Narofffea763e82007-11-14 19:25:57 +00003188 // Don't forget to add a ';'!!
Benjamin Kramerd999b372010-02-14 14:14:16 +00003189 InsertText(LocEnd.getFileLocWithOffset(1), ";");
Steve Narofffea763e82007-11-14 19:25:57 +00003190 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003191 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003192 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003193 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003194 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003195 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003196 Result += "_IVARS;\n};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003197 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003198 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003199 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003200 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00003201 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003202}
3203
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003204// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003205/// class methods.
Douglas Gregor653f1b12009-04-23 01:02:12 +00003206template<typename MethodIterator>
3207void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3208 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00003209 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003210 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00003211 const char *ClassName,
3212 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003213 if (MethodBegin == MethodEnd) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003214
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003215 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003216 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003217 SEL _cmd;
3218 char *method_types;
3219 void *_imp;
3220 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003221 */
Chris Lattner158ecb92007-10-25 17:07:24 +00003222 Result += "\nstruct _objc_method {\n";
3223 Result += "\tSEL _cmd;\n";
3224 Result += "\tchar *method_types;\n";
3225 Result += "\tvoid *_imp;\n";
3226 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003227
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003228 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00003229 }
Mike Stump1eb44332009-09-09 15:08:12 +00003230
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003231 // Build _objc_method_list for class's methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003232
Steve Naroff946a6932008-03-11 00:12:29 +00003233 /* struct {
3234 struct _objc_method_list *next_method;
3235 int method_count;
3236 struct _objc_method method_list[];
3237 }
3238 */
Douglas Gregor653f1b12009-04-23 01:02:12 +00003239 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroff946a6932008-03-11 00:12:29 +00003240 Result += "\nstatic struct {\n";
3241 Result += "\tstruct _objc_method_list *next_method;\n";
3242 Result += "\tint method_count;\n";
3243 Result += "\tstruct _objc_method method_list[";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003244 Result += utostr(NumMethods);
Steve Naroff946a6932008-03-11 00:12:29 +00003245 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003246 Result += prefix;
3247 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3248 Result += "_METHODS_";
3249 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003250 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003251 Result += IsInstanceMethod ? "inst" : "cls";
3252 Result += "_meth\")))= ";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003253 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003254
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003255 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003256 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003257 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003258 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003259 Result += "\", \"";
3260 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003261 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003262 Result += MethodInternalNames[*MethodBegin];
3263 Result += "}\n";
3264 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3265 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003266 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003267 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003268 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003269 Result += "\", \"";
3270 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003271 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003272 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00003273 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003274 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003275 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003276}
3277
Steve Naroff621edce2009-04-29 16:37:50 +00003278/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00003279void RewriteObjC::
Steve Naroff621edce2009-04-29 16:37:50 +00003280RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
3281 const char *ClassName, std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003282 static bool objc_protocol_methods = false;
Steve Naroff621edce2009-04-29 16:37:50 +00003283
3284 // Output struct protocol_methods holder of method selector and type.
3285 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3286 /* struct protocol_methods {
3287 SEL _cmd;
3288 char *method_types;
3289 }
3290 */
3291 Result += "\nstruct _protocol_methods {\n";
3292 Result += "\tstruct objc_selector *_cmd;\n";
3293 Result += "\tchar *method_types;\n";
3294 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003295
Steve Naroff621edce2009-04-29 16:37:50 +00003296 objc_protocol_methods = true;
3297 }
3298 // Do not synthesize the protocol more than once.
3299 if (ObjCSynthesizedProtocols.count(PDecl))
3300 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003301
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003302 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3303 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3304 PDecl->instmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003305 /* struct _objc_protocol_method_list {
3306 int protocol_method_count;
3307 struct protocol_methods protocols[];
3308 }
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003309 */
Steve Naroff621edce2009-04-29 16:37:50 +00003310 Result += "\nstatic struct {\n";
3311 Result += "\tint protocol_method_count;\n";
3312 Result += "\tstruct _protocol_methods protocol_methods[";
3313 Result += utostr(NumMethods);
3314 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3315 Result += PDecl->getNameAsString();
3316 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3317 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003318
Steve Naroff621edce2009-04-29 16:37:50 +00003319 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003320 for (ObjCProtocolDecl::instmeth_iterator
3321 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003322 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003323 if (I == PDecl->instmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003324 Result += "\t ,{{(struct objc_selector *)\"";
3325 else
3326 Result += "\t ,{(struct objc_selector *)\"";
3327 Result += (*I)->getSelector().getAsString().c_str();
3328 std::string MethodTypeString;
3329 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3330 Result += "\", \"";
3331 Result += MethodTypeString;
3332 Result += "\"}\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003333 }
Steve Naroff621edce2009-04-29 16:37:50 +00003334 Result += "\t }\n};\n";
3335 }
Mike Stump1eb44332009-09-09 15:08:12 +00003336
Steve Naroff621edce2009-04-29 16:37:50 +00003337 // Output class methods declared in this protocol.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003338 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3339 PDecl->classmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003340 if (NumMethods > 0) {
3341 /* struct _objc_protocol_method_list {
3342 int protocol_method_count;
3343 struct protocol_methods protocols[];
3344 }
3345 */
3346 Result += "\nstatic struct {\n";
3347 Result += "\tint protocol_method_count;\n";
3348 Result += "\tstruct _protocol_methods protocol_methods[";
3349 Result += utostr(NumMethods);
3350 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3351 Result += PDecl->getNameAsString();
3352 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3353 "{\n\t";
3354 Result += utostr(NumMethods);
3355 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003356
Steve Naroff621edce2009-04-29 16:37:50 +00003357 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003358 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003359 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003360 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003361 if (I == PDecl->classmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003362 Result += "\t ,{{(struct objc_selector *)\"";
3363 else
3364 Result += "\t ,{(struct objc_selector *)\"";
3365 Result += (*I)->getSelector().getAsString().c_str();
3366 std::string MethodTypeString;
3367 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3368 Result += "\", \"";
3369 Result += MethodTypeString;
3370 Result += "\"}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003371 }
Steve Naroff621edce2009-04-29 16:37:50 +00003372 Result += "\t }\n};\n";
3373 }
3374
3375 // Output:
3376 /* struct _objc_protocol {
3377 // Objective-C 1.0 extensions
3378 struct _objc_protocol_extension *isa;
3379 char *protocol_name;
3380 struct _objc_protocol **protocol_list;
3381 struct _objc_protocol_method_list *instance_methods;
3382 struct _objc_protocol_method_list *class_methods;
Mike Stump1eb44332009-09-09 15:08:12 +00003383 };
Steve Naroff621edce2009-04-29 16:37:50 +00003384 */
3385 static bool objc_protocol = false;
3386 if (!objc_protocol) {
3387 Result += "\nstruct _objc_protocol {\n";
3388 Result += "\tstruct _objc_protocol_extension *isa;\n";
3389 Result += "\tchar *protocol_name;\n";
3390 Result += "\tstruct _objc_protocol **protocol_list;\n";
3391 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3392 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003393 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003394
Steve Naroff621edce2009-04-29 16:37:50 +00003395 objc_protocol = true;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003396 }
Mike Stump1eb44332009-09-09 15:08:12 +00003397
Steve Naroff621edce2009-04-29 16:37:50 +00003398 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3399 Result += PDecl->getNameAsString();
3400 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3401 "{\n\t0, \"";
3402 Result += PDecl->getNameAsString();
3403 Result += "\", 0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003404 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003405 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3406 Result += PDecl->getNameAsString();
3407 Result += ", ";
3408 }
3409 else
3410 Result += "0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003411 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003412 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3413 Result += PDecl->getNameAsString();
3414 Result += "\n";
3415 }
3416 else
3417 Result += "0\n";
3418 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003419
Steve Naroff621edce2009-04-29 16:37:50 +00003420 // Mark this protocol as having been generated.
3421 if (!ObjCSynthesizedProtocols.insert(PDecl))
3422 assert(false && "protocol already synthesized");
3423
3424}
3425
3426void RewriteObjC::
3427RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3428 const char *prefix, const char *ClassName,
3429 std::string &Result) {
3430 if (Protocols.empty()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003431
Steve Naroff621edce2009-04-29 16:37:50 +00003432 for (unsigned i = 0; i != Protocols.size(); i++)
3433 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3434
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003435 // Output the top lovel protocol meta-data for the class.
3436 /* struct _objc_protocol_list {
3437 struct _objc_protocol_list *next;
3438 int protocol_count;
3439 struct _objc_protocol *class_protocols[];
3440 }
3441 */
3442 Result += "\nstatic struct {\n";
3443 Result += "\tstruct _objc_protocol_list *next;\n";
3444 Result += "\tint protocol_count;\n";
3445 Result += "\tstruct _objc_protocol *class_protocols[";
3446 Result += utostr(Protocols.size());
3447 Result += "];\n} _OBJC_";
3448 Result += prefix;
3449 Result += "_PROTOCOLS_";
3450 Result += ClassName;
3451 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3452 "{\n\t0, ";
3453 Result += utostr(Protocols.size());
3454 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003455
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003456 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003457 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003458 Result += " \n";
Mike Stump1eb44332009-09-09 15:08:12 +00003459
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003460 for (unsigned i = 1; i != Protocols.size(); i++) {
3461 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003462 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003463 Result += "\n";
3464 }
3465 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003466}
3467
Steve Naroff621edce2009-04-29 16:37:50 +00003468
Mike Stump1eb44332009-09-09 15:08:12 +00003469/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003470/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003471void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003472 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003473 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003474 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003475 ObjCCategoryDecl *CDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00003476 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003477 CDecl = CDecl->getNextClassCategory())
3478 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3479 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003480
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003481 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003482 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003483 FullCategoryName += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003484
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003485 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003486 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003487 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003488
3489 // If any of our property implementations have associated getters or
3490 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003491 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3492 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003493 Prop != PropEnd; ++Prop) {
3494 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3495 continue;
3496 if (!(*Prop)->getPropertyIvarDecl())
3497 continue;
3498 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3499 if (!PD)
3500 continue;
3501 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3502 InstanceMethods.push_back(Getter);
3503 if (PD->isReadOnly())
3504 continue;
3505 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3506 InstanceMethods.push_back(Setter);
3507 }
3508 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003509 true, "CATEGORY_", FullCategoryName.c_str(),
3510 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003511
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003512 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003513 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003514 false, "CATEGORY_", FullCategoryName.c_str(),
3515 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003516
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003517 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003518 // Null CDecl is case of a category implementation with no category interface
3519 if (CDecl)
Steve Naroff621edce2009-04-29 16:37:50 +00003520 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3521 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003522 /* struct _objc_category {
3523 char *category_name;
3524 char *class_name;
3525 struct _objc_method_list *instance_methods;
3526 struct _objc_method_list *class_methods;
3527 struct _objc_protocol_list *protocols;
3528 // Objective-C 1.0 extensions
3529 uint32_t size; // sizeof (struct _objc_category)
Mike Stump1eb44332009-09-09 15:08:12 +00003530 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003531 // @property decl.
Mike Stump1eb44332009-09-09 15:08:12 +00003532 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003533 */
Mike Stump1eb44332009-09-09 15:08:12 +00003534
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003535 static bool objc_category = false;
3536 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003537 Result += "\nstruct _objc_category {\n";
3538 Result += "\tchar *category_name;\n";
3539 Result += "\tchar *class_name;\n";
3540 Result += "\tstruct _objc_method_list *instance_methods;\n";
3541 Result += "\tstruct _objc_method_list *class_methods;\n";
3542 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003543 Result += "\tunsigned int size;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003544 Result += "\tstruct _objc_property_list *instance_properties;\n";
3545 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003546 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003547 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003548 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3549 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003550 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003551 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003552 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003553 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003554 Result += "\"\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003555
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003556 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003557 Result += "\t, (struct _objc_method_list *)"
3558 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3559 Result += FullCategoryName;
3560 Result += "\n";
3561 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003562 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003563 Result += "\t, 0\n";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003564 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003565 Result += "\t, (struct _objc_method_list *)"
3566 "&_OBJC_CATEGORY_CLASS_METHODS_";
3567 Result += FullCategoryName;
3568 Result += "\n";
3569 }
3570 else
3571 Result += "\t, 0\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003572
Chris Lattnercafeb352009-02-20 18:18:36 +00003573 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003574 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003575 Result += FullCategoryName;
3576 Result += "\n";
3577 }
3578 else
3579 Result += "\t, 0\n";
3580 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003581}
3582
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003583/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3584/// ivar offset.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00003585void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCContainerDecl *IDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00003586 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003587 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003588 if (ivar->isBitField()) {
3589 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3590 // place all bitfields at offset 0.
3591 Result += "0";
3592 } else {
3593 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003594 Result += IDecl->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003595 if (LangOpts.Microsoft)
3596 Result += "_IMPL";
3597 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003598 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003599 Result += ")";
3600 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003601}
3602
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003603//===----------------------------------------------------------------------===//
3604// Meta Data Emission
3605//===----------------------------------------------------------------------===//
3606
Steve Naroffb29b4272008-04-14 22:03:09 +00003607void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003608 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003609 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00003610
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003611 // Explictly declared @interface's are already synthesized.
Steve Naroff33feeb02009-04-20 20:09:33 +00003612 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003613 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003614 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003615 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003616 }
Mike Stump1eb44332009-09-09 15:08:12 +00003617
Chris Lattnerbe6df082007-12-12 07:56:42 +00003618 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003619 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump1eb44332009-09-09 15:08:12 +00003620 ? IDecl->ivar_size()
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003621 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003622 if (NumIvars > 0) {
3623 static bool objc_ivar = false;
3624 if (!objc_ivar) {
3625 /* struct _objc_ivar {
3626 char *ivar_name;
3627 char *ivar_type;
3628 int ivar_offset;
Mike Stump1eb44332009-09-09 15:08:12 +00003629 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003630 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003631 Result += "\nstruct _objc_ivar {\n";
3632 Result += "\tchar *ivar_name;\n";
3633 Result += "\tchar *ivar_type;\n";
3634 Result += "\tint ivar_offset;\n";
3635 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003636
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003637 objc_ivar = true;
3638 }
3639
Steve Naroff946a6932008-03-11 00:12:29 +00003640 /* struct {
3641 int ivar_count;
3642 struct _objc_ivar ivar_list[nIvars];
Mike Stump1eb44332009-09-09 15:08:12 +00003643 };
Steve Naroff946a6932008-03-11 00:12:29 +00003644 */
Mike Stump1eb44332009-09-09 15:08:12 +00003645 Result += "\nstatic struct {\n";
Steve Naroff946a6932008-03-11 00:12:29 +00003646 Result += "\tint ivar_count;\n";
3647 Result += "\tstruct _objc_ivar ivar_list[";
3648 Result += utostr(NumIvars);
3649 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003650 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003651 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003652 "{\n\t";
3653 Result += utostr(NumIvars);
3654 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003655
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003656 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003657 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003658 if (!IDecl->ivar_empty()) {
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003659 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003660 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003661 IV != IVEnd; ++IV)
3662 IVars.push_back(*IV);
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003663 IVI = IDecl->ivar_begin();
3664 IVE = IDecl->ivar_end();
Chris Lattnerbe6df082007-12-12 07:56:42 +00003665 } else {
3666 IVI = CDecl->ivar_begin();
3667 IVE = CDecl->ivar_end();
3668 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003669 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003670 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003671 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003672 std::string TmpString, StrEncoding;
3673 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3674 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003675 Result += StrEncoding;
3676 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003677 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003678 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003679 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003680 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003681 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003682 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003683 std::string TmpString, StrEncoding;
3684 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3685 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003686 Result += StrEncoding;
3687 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003688 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003689 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003690 }
Mike Stump1eb44332009-09-09 15:08:12 +00003691
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003692 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003693 }
Mike Stump1eb44332009-09-09 15:08:12 +00003694
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003695 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003696 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003697 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003698
3699 // If any of our property implementations have associated getters or
3700 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003701 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3702 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003703 Prop != PropEnd; ++Prop) {
3704 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3705 continue;
3706 if (!(*Prop)->getPropertyIvarDecl())
3707 continue;
3708 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3709 if (!PD)
3710 continue;
3711 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3712 InstanceMethods.push_back(Getter);
3713 if (PD->isReadOnly())
3714 continue;
3715 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3716 InstanceMethods.push_back(Setter);
3717 }
3718 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003719 true, "", IDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003720
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003721 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003722 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003723 false, "", IDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003724
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003725 // Protocols referenced in class declaration?
Steve Naroff621edce2009-04-29 16:37:50 +00003726 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3727 "CLASS", CDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003728
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003729 // Declaration of class/meta-class metadata
3730 /* struct _objc_class {
3731 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003732 const char *super_class_name;
3733 char *name;
3734 long version;
3735 long info;
3736 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003737 struct _objc_ivar_list *ivars;
3738 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003739 struct objc_cache *cache;
3740 struct objc_protocol_list *protocols;
3741 const char *ivar_layout;
3742 struct _objc_class_ext *ext;
Mike Stump1eb44332009-09-09 15:08:12 +00003743 };
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003744 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003745 static bool objc_class = false;
3746 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003747 Result += "\nstruct _objc_class {\n";
3748 Result += "\tstruct _objc_class *isa;\n";
3749 Result += "\tconst char *super_class_name;\n";
3750 Result += "\tchar *name;\n";
3751 Result += "\tlong version;\n";
3752 Result += "\tlong info;\n";
3753 Result += "\tlong instance_size;\n";
3754 Result += "\tstruct _objc_ivar_list *ivars;\n";
3755 Result += "\tstruct _objc_method_list *methods;\n";
3756 Result += "\tstruct objc_cache *cache;\n";
3757 Result += "\tstruct _objc_protocol_list *protocols;\n";
3758 Result += "\tconst char *ivar_layout;\n";
3759 Result += "\tstruct _objc_class_ext *ext;\n";
3760 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003761 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003762 }
Mike Stump1eb44332009-09-09 15:08:12 +00003763
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003764 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003765 ObjCInterfaceDecl *RootClass = 0;
3766 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003767 while (SuperClass) {
3768 RootClass = SuperClass;
3769 SuperClass = SuperClass->getSuperClass();
3770 }
3771 SuperClass = CDecl->getSuperClass();
Mike Stump1eb44332009-09-09 15:08:12 +00003772
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003773 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003774 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003775 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003776 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003777 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003778 Result += "\"";
3779
3780 if (SuperClass) {
3781 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003782 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003783 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003784 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003785 Result += "\"";
3786 }
3787 else {
3788 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003789 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003790 Result += "\"";
3791 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003792 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003793 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003794 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003795 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff23f41272008-03-11 18:14:26 +00003796 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003797 Result += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003798 Result += "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003799 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003800 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003801 Result += ", 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00003802 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003803 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003804 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003805 Result += ",0,0\n";
3806 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003807 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003808 Result += "\t,0,0,0,0\n";
3809 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003810
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003811 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003812 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003813 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003814 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003815 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003816 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003817 if (SuperClass) {
3818 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003819 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003820 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003821 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003822 Result += "\"";
3823 }
3824 else {
3825 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003826 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003827 Result += "\"";
3828 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003829 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003830 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003831 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003832 Result += ",0";
3833 else {
3834 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003835 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003836 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003837 if (LangOpts.Microsoft)
3838 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003839 Result += ")";
3840 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003841 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003842 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003843 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003844 Result += "\n\t";
3845 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003846 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003847 Result += ",0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003848 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroff946a6932008-03-11 00:12:29 +00003849 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003850 Result += CDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003851 Result += ", 0\n\t";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003852 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003853 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003854 Result += ",0,0";
Chris Lattnercafeb352009-02-20 18:18:36 +00003855 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003856 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003857 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003858 Result += ", 0,0\n";
3859 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003860 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003861 Result += ",0,0,0\n";
3862 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003863}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003864
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003865/// RewriteImplementations - This routine rewrites all method implementations
3866/// and emits meta-data.
3867
Steve Narofface66252008-11-13 20:07:04 +00003868void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003869 int ClsDefCount = ClassImplementation.size();
3870 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003871
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003872 // Rewrite implemented methods
3873 for (int i = 0; i < ClsDefCount; i++)
3874 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00003875
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003876 for (int i = 0; i < CatDefCount; i++)
3877 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003878}
Mike Stump1eb44332009-09-09 15:08:12 +00003879
Steve Narofface66252008-11-13 20:07:04 +00003880void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3881 int ClsDefCount = ClassImplementation.size();
3882 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00003883
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003884 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003885 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003886 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003887
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003888 // For each implemented category, write out all its meta data.
3889 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003890 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroff621edce2009-04-29 16:37:50 +00003891
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003892 // Write objc_symtab metadata
3893 /*
3894 struct _objc_symtab
3895 {
3896 long sel_ref_cnt;
3897 SEL *refs;
3898 short cls_def_cnt;
3899 short cat_def_cnt;
3900 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump1eb44332009-09-09 15:08:12 +00003901 };
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003902 */
Mike Stump1eb44332009-09-09 15:08:12 +00003903
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003904 Result += "\nstruct _objc_symtab {\n";
3905 Result += "\tlong sel_ref_cnt;\n";
3906 Result += "\tSEL *refs;\n";
3907 Result += "\tshort cls_def_cnt;\n";
3908 Result += "\tshort cat_def_cnt;\n";
3909 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3910 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003911
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003912 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003913 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003914 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003915 + ", " + utostr(CatDefCount) + "\n";
3916 for (int i = 0; i < ClsDefCount; i++) {
3917 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003918 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003919 Result += "\n";
3920 }
Mike Stump1eb44332009-09-09 15:08:12 +00003921
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003922 for (int i = 0; i < CatDefCount; i++) {
3923 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003924 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003925 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003926 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003927 Result += "\n";
3928 }
Mike Stump1eb44332009-09-09 15:08:12 +00003929
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003930 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003931
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003932 // Write objc_module metadata
Mike Stump1eb44332009-09-09 15:08:12 +00003933
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003934 /*
3935 struct _objc_module {
3936 long version;
3937 long size;
3938 const char *name;
3939 struct _objc_symtab *symtab;
3940 }
3941 */
Mike Stump1eb44332009-09-09 15:08:12 +00003942
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003943 Result += "\nstruct _objc_module {\n";
3944 Result += "\tlong version;\n";
3945 Result += "\tlong size;\n";
3946 Result += "\tconst char *name;\n";
3947 Result += "\tstruct _objc_symtab *symtab;\n";
3948 Result += "};\n\n";
3949 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003950 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003951 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003952 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003953 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003954
3955 if (LangOpts.Microsoft) {
Steve Naroff621edce2009-04-29 16:37:50 +00003956 if (ProtocolExprDecls.size()) {
3957 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
3958 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003959 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00003960 E = ProtocolExprDecls.end(); I != E; ++I) {
3961 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
3962 Result += (*I)->getNameAsString();
3963 Result += " = &_OBJC_PROTOCOL_";
3964 Result += (*I)->getNameAsString();
3965 Result += ";\n";
3966 }
3967 Result += "#pragma data_seg(pop)\n\n";
3968 }
Steve Naroff4f943c22008-03-10 20:43:59 +00003969 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003970 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003971 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3972 Result += "&_OBJC_MODULES;\n";
3973 Result += "#pragma data_seg(pop)\n\n";
3974 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003975}
Chris Lattner311ff022007-10-16 22:36:42 +00003976
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003977void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3978 const std::string &Name,
3979 ValueDecl *VD) {
3980 assert(BlockByRefDeclNo.count(VD) &&
3981 "RewriteByRefString: ByRef decl missing");
3982 ResultStr += "struct __Block_byref_" + Name +
3983 "_" + utostr(BlockByRefDeclNo[VD]) ;
3984}
3985
Steve Naroff54055232008-10-27 17:20:55 +00003986std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3987 const char *funcName,
3988 std::string Tag) {
3989 const FunctionType *AFT = CE->getFunctionType();
3990 QualType RT = AFT->getResultType();
3991 std::string StructRef = "struct " + Tag;
3992 std::string S = "static " + RT.getAsString() + " __" +
3993 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003994
Steve Naroff54055232008-10-27 17:20:55 +00003995 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00003996
Douglas Gregor72564e72009-02-26 23:50:07 +00003997 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003998 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00003999 // block (to reference imported block decl refs).
4000 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00004001 } else if (BD->param_empty()) {
4002 S += "(" + StructRef + " *__cself)";
4003 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004004 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00004005 assert(FT && "SynthesizeBlockFunc: No function proto");
4006 S += '(';
4007 // first add the implicit argument.
4008 S += StructRef + " *__cself, ";
4009 std::string ParamStr;
4010 for (BlockDecl::param_iterator AI = BD->param_begin(),
4011 E = BD->param_end(); AI != E; ++AI) {
4012 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004013 ParamStr = (*AI)->getNameAsString();
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00004014 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00004015 S += ParamStr;
4016 }
4017 if (FT->isVariadic()) {
4018 if (!BD->param_empty()) S += ", ";
4019 S += "...";
4020 }
4021 S += ')';
4022 }
4023 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004024
Steve Naroff54055232008-10-27 17:20:55 +00004025 // Create local declarations to avoid rewriting all closure decl ref exprs.
4026 // First, emit a declaration for all "by ref" decls.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004027 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004028 E = BlockByRefDecls.end(); I != E; ++I) {
4029 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004030 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004031 std::string TypeString;
4032 RewriteByRefString(TypeString, Name, (*I));
4033 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004034 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004035 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004036 }
Steve Naroff54055232008-10-27 17:20:55 +00004037 // Next, emit a declaration for all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004038 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004039 E = BlockByCopyDecls.end(); I != E; ++I) {
4040 S += " ";
Steve Naroff54055232008-10-27 17:20:55 +00004041 // Handle nested closure invocation. For example:
4042 //
4043 // void (^myImportedClosure)(void);
4044 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004045 //
Steve Naroff54055232008-10-27 17:20:55 +00004046 // void (^anotherClosure)(void);
4047 // anotherClosure = ^(void) {
4048 // myImportedClosure(); // import and invoke the closure
4049 // };
4050 //
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004051 if (isTopLevelBlockPointerType((*I)->getType())) {
4052 RewriteBlockPointerTypeVariable(S, (*I));
4053 S += " = (";
4054 RewriteBlockPointerType(S, (*I)->getType());
4055 S += ")";
4056 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4057 }
4058 else {
Fariborz Jahanian210c2482010-02-16 17:26:03 +00004059 std::string Name = (*I)->getNameAsString();
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00004060 (*I)->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004061 S += Name + " = __cself->" +
4062 (*I)->getNameAsString() + "; // bound by copy\n";
4063 }
Steve Naroff54055232008-10-27 17:20:55 +00004064 }
4065 std::string RewrittenStr = RewrittenBlockExprs[CE];
4066 const char *cstr = RewrittenStr.c_str();
4067 while (*cstr++ != '{') ;
4068 S += cstr;
4069 S += "\n";
4070 return S;
4071}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00004072
Steve Naroff54055232008-10-27 17:20:55 +00004073std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4074 const char *funcName,
4075 std::string Tag) {
4076 std::string StructRef = "struct " + Tag;
4077 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00004078
Steve Naroff54055232008-10-27 17:20:55 +00004079 S += funcName;
4080 S += "_block_copy_" + utostr(i);
4081 S += "(" + StructRef;
4082 S += "*dst, " + StructRef;
4083 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004084 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004085 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00004086 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004087 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00004088 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004089 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004090 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004091 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004092 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004093 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004094 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004095 S += "}\n";
4096
Steve Naroff54055232008-10-27 17:20:55 +00004097 S += "\nstatic void __";
4098 S += funcName;
4099 S += "_block_dispose_" + utostr(i);
4100 S += "(" + StructRef;
4101 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004102 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004103 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00004104 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004105 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004106 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004107 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004108 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004109 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004110 }
Mike Stump1eb44332009-09-09 15:08:12 +00004111 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00004112 return S;
4113}
4114
Steve Naroff01aec112009-12-06 21:14:13 +00004115std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4116 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00004117 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00004118 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00004119
Steve Naroff54055232008-10-27 17:20:55 +00004120 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004121 S += " struct " + Desc;
4122 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004123
Steve Naroff01aec112009-12-06 21:14:13 +00004124 Constructor += "(void *fp, "; // Invoke function pointer.
4125 Constructor += "struct " + Desc; // Descriptor pointer.
4126 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00004127
Steve Naroff54055232008-10-27 17:20:55 +00004128 if (BlockDeclRefs.size()) {
4129 // Output all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004130 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004131 E = BlockByCopyDecls.end(); I != E; ++I) {
4132 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004133 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004134 std::string ArgName = "_" + FieldName;
4135 // Handle nested closure invocation. For example:
4136 //
4137 // void (^myImportedBlock)(void);
4138 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004139 //
Steve Naroff54055232008-10-27 17:20:55 +00004140 // void (^anotherBlock)(void);
4141 // anotherBlock = ^(void) {
4142 // myImportedBlock(); // import and invoke the closure
4143 // };
4144 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004145 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004146 S += "struct __block_impl *";
4147 Constructor += ", void *" + ArgName;
4148 } else {
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00004149 (*I)->getType().getAsStringInternal(FieldName, Context->PrintingPolicy);
4150 (*I)->getType().getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00004151 Constructor += ", " + ArgName;
4152 }
4153 S += FieldName + ";\n";
4154 }
4155 // Output all "by ref" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004156 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004157 E = BlockByRefDecls.end(); I != E; ++I) {
4158 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004159 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004160 std::string ArgName = "_" + FieldName;
4161 // Handle nested closure invocation. For example:
4162 //
4163 // void (^myImportedBlock)(void);
4164 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004165 //
Steve Naroff54055232008-10-27 17:20:55 +00004166 // void (^anotherBlock)(void);
4167 // anotherBlock = ^(void) {
4168 // myImportedBlock(); // import and invoke the closure
4169 // };
4170 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004171 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004172 S += "struct __block_impl *";
4173 Constructor += ", void *" + ArgName;
4174 } else {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004175 std::string TypeString;
4176 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004177 TypeString += " *";
4178 FieldName = TypeString + FieldName;
4179 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00004180 Constructor += ", " + ArgName;
4181 }
4182 S += FieldName + "; // by ref\n";
4183 }
4184 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00004185 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004186 if (GlobalVarDecl)
4187 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4188 else
4189 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004190 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004191
Steve Naroff01aec112009-12-06 21:14:13 +00004192 Constructor += " Desc = desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004193
Steve Naroff54055232008-10-27 17:20:55 +00004194 // Initialize all "by copy" arguments.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004195 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004196 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004197 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004198 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004199 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00004200 Constructor += Name + " = (struct __block_impl *)_";
4201 else
4202 Constructor += Name + " = _";
4203 Constructor += Name + ";\n";
4204 }
4205 // Initialize all "by ref" arguments.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004206 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004207 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004208 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004209 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004210 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00004211 Constructor += Name + " = (struct __block_impl *)_";
4212 else
4213 Constructor += Name + " = _";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004214 Constructor += Name + "->__forwarding;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004215 }
4216 } else {
4217 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00004218 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004219 if (GlobalVarDecl)
4220 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4221 else
4222 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004223 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4224 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004225 }
4226 Constructor += " ";
4227 Constructor += "}\n";
4228 S += Constructor;
4229 S += "};\n";
4230 return S;
4231}
4232
Steve Naroff01aec112009-12-06 21:14:13 +00004233std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4234 std::string ImplTag, int i,
4235 const char *FunName,
4236 unsigned hasCopy) {
4237 std::string S = "\nstatic struct " + DescTag;
4238
4239 S += " {\n unsigned long reserved;\n";
4240 S += " unsigned long Block_size;\n";
4241 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004242 S += " void (*copy)(struct ";
4243 S += ImplTag; S += "*, struct ";
4244 S += ImplTag; S += "*);\n";
4245
4246 S += " void (*dispose)(struct ";
4247 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004248 }
4249 S += "} ";
4250
4251 S += DescTag + "_DATA = { 0, sizeof(struct ";
4252 S += ImplTag + ")";
4253 if (hasCopy) {
4254 S += ", __" + std::string(FunName) + "_block_copy_" + utostr(i);
4255 S += ", __" + std::string(FunName) + "_block_dispose_" + utostr(i);
4256 }
4257 S += "};\n";
4258 return S;
4259}
4260
Steve Naroff54055232008-10-27 17:20:55 +00004261void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004262 const char *FunName) {
4263 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00004264 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004265 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Steve Naroff54055232008-10-27 17:20:55 +00004266 // Insert closures that were part of the function.
4267 for (unsigned i = 0; i < Blocks.size(); i++) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004268 // Need to copy-in the inner copied-in variables not actually used in this
4269 // block.
4270 for (int j = 0; j < InnerDeclRefsCount[i]; j++)
4271 BlockDeclRefs.push_back(InnerDeclRefs[j]);
Steve Naroff54055232008-10-27 17:20:55 +00004272 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004273 llvm::SmallPtrSet<ValueDecl *, 8> InnerBlockValueDecls;
4274 llvm::SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
4275 GetInnerBlockDeclRefExprs(Blocks[i]->getBody(),
4276 InnerBlockDeclRefs, InnerBlockValueDecls);
Steve Naroff54055232008-10-27 17:20:55 +00004277
Steve Naroff01aec112009-12-06 21:14:13 +00004278 std::string ImplTag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
4279 std::string DescTag = "__" + std::string(FunName) + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00004280
Steve Naroff01aec112009-12-06 21:14:13 +00004281 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00004282
Benjamin Kramerd999b372010-02-14 14:14:16 +00004283 InsertText(FunLocStart, CI);
Steve Naroff54055232008-10-27 17:20:55 +00004284
Steve Naroff01aec112009-12-06 21:14:13 +00004285 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00004286
Benjamin Kramerd999b372010-02-14 14:14:16 +00004287 InsertText(FunLocStart, CF);
Steve Naroff54055232008-10-27 17:20:55 +00004288
4289 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00004290 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004291 InsertText(FunLocStart, HF);
Steve Naroff54055232008-10-27 17:20:55 +00004292 }
Steve Naroff01aec112009-12-06 21:14:13 +00004293 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4294 ImportedBlockDecls.size() > 0);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004295 InsertText(FunLocStart, BD);
Mike Stump1eb44332009-09-09 15:08:12 +00004296
Steve Naroff54055232008-10-27 17:20:55 +00004297 BlockDeclRefs.clear();
4298 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004299 BlockByRefDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004300 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004301 BlockByCopyDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004302 ImportedBlockDecls.clear();
4303 }
4304 Blocks.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004305 InnerDeclRefsCount.clear();
4306 InnerDeclRefs.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004307 RewrittenBlockExprs.clear();
4308}
4309
4310void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4311 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner8ec03f52008-11-24 03:54:41 +00004312 const char *FuncName = FD->getNameAsCString();
Mike Stump1eb44332009-09-09 15:08:12 +00004313
Steve Naroff54055232008-10-27 17:20:55 +00004314 SynthesizeBlockLiterals(FunLocStart, FuncName);
4315}
4316
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004317static void BuildUniqueMethodName(std::string &Name,
4318 ObjCMethodDecl *MD) {
4319 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4320 Name = IFace->getNameAsCString();
4321 Name += "__" + MD->getSelector().getAsString();
4322 // Convert colons to underscores.
4323 std::string::size_type loc = 0;
4324 while ((loc = Name.find(":", loc)) != std::string::npos)
4325 Name.replace(loc, 1, "_");
4326}
4327
Steve Naroff54055232008-10-27 17:20:55 +00004328void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00004329 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4330 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00004331 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004332 std::string FuncName;
4333 BuildUniqueMethodName(FuncName, MD);
Steve Naroff54055232008-10-27 17:20:55 +00004334 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
4335}
4336
4337void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4338 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4339 CI != E; ++CI)
4340 if (*CI) {
4341 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4342 GetBlockDeclRefExprs(CBE->getBody());
4343 else
4344 GetBlockDeclRefExprs(*CI);
4345 }
4346 // Handle specific things.
4347 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
4348 // FIXME: Handle enums.
4349 if (!isa<FunctionDecl>(CDRE->getDecl()))
4350 BlockDeclRefs.push_back(CDRE);
4351 return;
4352}
4353
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004354void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4355 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
4356 llvm::SmallPtrSet<ValueDecl *, 8> &InnerBlockValueDecls) {
4357 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4358 CI != E; ++CI)
4359 if (*CI) {
4360 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4361 GetInnerBlockDeclRefExprs(CBE->getBody(),
4362 InnerBlockDeclRefs,
4363 InnerBlockValueDecls);
4364 else
4365 GetInnerBlockDeclRefExprs(*CI,
4366 InnerBlockDeclRefs,
4367 InnerBlockValueDecls);
4368
4369 }
4370 // Handle specific things.
4371 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
4372 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahaniane7c5c932010-02-26 19:05:20 +00004373 !isa<ParmVarDecl>(CDRE->getDecl()) &&
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004374 !InnerBlockValueDecls.count(CDRE->getDecl())) {
4375 InnerBlockValueDecls.insert(CDRE->getDecl());
4376 InnerBlockDeclRefs.push_back(CDRE);
4377 }
4378 return;
4379}
4380
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004381Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00004382 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00004383 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004384
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004385 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004386 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004387 } else if (const BlockDeclRefExpr *CDRE =
4388 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004389 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004390 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004391 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004392 }
4393 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4394 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4395 }
4396 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4397 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4398 else if (const ConditionalOperator *CEXPR =
4399 dyn_cast<ConditionalOperator>(BlockExp)) {
4400 Expr *LHSExp = CEXPR->getLHS();
4401 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4402 Expr *RHSExp = CEXPR->getRHS();
4403 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4404 Expr *CONDExp = CEXPR->getCond();
4405 ConditionalOperator *CondExpr =
4406 new (Context) ConditionalOperator(CONDExp,
4407 SourceLocation(), cast<Expr>(LHSStmt),
4408 SourceLocation(), cast<Expr>(RHSStmt),
4409 Exp->getType());
4410 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00004411 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4412 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004413 } else {
4414 assert(1 && "RewriteBlockClass: Bad type");
4415 }
4416 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00004417 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00004418 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00004419 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00004420 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004421
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004422 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4423 SourceLocation(),
4424 &Context->Idents.get("__block_impl"));
4425 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00004426
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004427 // Generate a funky cast.
4428 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004429
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004430 // Push the block argument type.
4431 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00004432 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004433 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004434 E = FTP->arg_type_end(); I && (I != E); ++I) {
4435 QualType t = *I;
4436 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004437 if (isTopLevelBlockPointerType(t)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004438 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004439 t = Context->getPointerType(BPT->getPointeeType());
4440 }
4441 ArgTypes.push_back(t);
4442 }
Steve Naroff54055232008-10-27 17:20:55 +00004443 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004444 // Now do the pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00004445 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00004446 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0,
4447 false, false, 0, 0,
4448 false, CC_Default);
Mike Stump1eb44332009-09-09 15:08:12 +00004449
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004450 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00004451
John McCall9d125032010-01-15 18:39:57 +00004452 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4453 CastExpr::CK_Unknown,
4454 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004455 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004456 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4457 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004458 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00004459
Douglas Gregor44b43212008-12-11 16:49:14 +00004460 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00004461 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004462 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004463 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4464 FD->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00004465
John McCall9d125032010-01-15 18:39:57 +00004466 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4467 CastExpr::CK_Unknown, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004468 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00004469
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004470 llvm::SmallVector<Expr*, 8> BlkExprs;
4471 // Add the implicit argument.
4472 BlkExprs.push_back(BlkCast);
4473 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004474 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004475 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004476 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00004477 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004478 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4479 BlkExprs.size(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00004480 Exp->getType(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004481 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00004482}
4483
4484void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004485 Stmt *BlockCall = SynthesizeBlockCall(Exp, Exp->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004486 ReplaceStmt(Exp, BlockCall);
Steve Naroff54055232008-10-27 17:20:55 +00004487}
4488
Steve Naroff621edce2009-04-29 16:37:50 +00004489// We need to return the rewritten expression to handle cases where the
4490// BlockDeclRefExpr is embedded in another expression being rewritten.
4491// For example:
4492//
4493// int main() {
4494// __block Foo *f;
4495// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00004496//
Steve Naroff621edce2009-04-29 16:37:50 +00004497// void (^myblock)() = ^() {
4498// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4499// i = 77;
4500// };
4501//}
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004502Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00004503 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004504 // for each DeclRefExp where BYREFVAR is name of the variable.
4505 ValueDecl *VD;
4506 bool isArrow = true;
4507 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4508 VD = BDRE->getDecl();
4509 else {
4510 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4511 isArrow = false;
4512 }
4513
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004514 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4515 &Context->Idents.get("__forwarding"),
4516 Context->VoidPtrTy, 0,
4517 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004518 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4519 FD, SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004520 FD->getType());
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004521
4522 const char *Name = VD->getNameAsCString();
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004523 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4524 &Context->Idents.get(Name),
4525 Context->VoidPtrTy, 0,
4526 /*BitWidth=*/0, /*Mutable=*/true);
4527 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004528 DeclRefExp->getType());
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004529
4530
4531
Steve Naroffdf8570d2009-02-02 17:19:26 +00004532 // Need parens to enforce precedence.
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004533 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4534 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004535 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00004536 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00004537}
4538
Steve Naroffb2f9e512008-11-03 23:29:32 +00004539void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4540 SourceLocation LocStart = CE->getLParenLoc();
4541 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00004542
4543 // Need to avoid trying to rewrite synthesized casts.
4544 if (LocStart.isInvalid())
4545 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004546 // Need to avoid trying to rewrite casts contained in macros.
4547 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4548 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004549
Steve Naroff54055232008-10-27 17:20:55 +00004550 const char *startBuf = SM->getCharacterData(LocStart);
4551 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004552 QualType QT = CE->getType();
4553 const Type* TypePtr = QT->getAs<Type>();
4554 if (isa<TypeOfExprType>(TypePtr)) {
4555 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4556 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4557 std::string TypeAsString = "(";
Fariborz Jahanianafad76f2010-02-18 01:20:22 +00004558 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004559 TypeAsString += ")";
Benjamin Kramerd999b372010-02-14 14:14:16 +00004560 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004561 return;
4562 }
Steve Naroff54055232008-10-27 17:20:55 +00004563 // advance the location to startArgList.
4564 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004565
Steve Naroff54055232008-10-27 17:20:55 +00004566 while (*argPtr++ && (argPtr < endBuf)) {
4567 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004568 case '^':
4569 // Replace the '^' with '*'.
4570 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004571 ReplaceText(LocStart, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004572 break;
Steve Naroff54055232008-10-27 17:20:55 +00004573 }
4574 }
4575 return;
4576}
4577
4578void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4579 SourceLocation DeclLoc = FD->getLocation();
4580 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004581
Steve Naroff54055232008-10-27 17:20:55 +00004582 // We have 1 or more arguments that have closure pointers.
4583 const char *startBuf = SM->getCharacterData(DeclLoc);
4584 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004585
Steve Naroff54055232008-10-27 17:20:55 +00004586 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004587
Steve Naroff54055232008-10-27 17:20:55 +00004588 parenCount++;
4589 // advance the location to startArgList.
4590 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4591 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004592
Steve Naroff54055232008-10-27 17:20:55 +00004593 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004594
Steve Naroff54055232008-10-27 17:20:55 +00004595 while (*argPtr++ && parenCount) {
4596 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004597 case '^':
4598 // Replace the '^' with '*'.
4599 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004600 ReplaceText(DeclLoc, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004601 break;
4602 case '(':
4603 parenCount++;
4604 break;
4605 case ')':
4606 parenCount--;
4607 break;
Steve Naroff54055232008-10-27 17:20:55 +00004608 }
4609 }
4610 return;
4611}
4612
4613bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004614 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004615 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004616 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004617 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004618 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004619 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004620 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004621 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004622 }
4623 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004624 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004625 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004626 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004627 return true;
4628 }
4629 return false;
4630}
4631
Ted Kremenek8189cde2009-02-07 01:47:29 +00004632void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4633 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004634 const char *argPtr = strchr(Name, '(');
4635 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004636
Steve Naroff54055232008-10-27 17:20:55 +00004637 LParen = argPtr; // output the start.
4638 argPtr++; // skip past the left paren.
4639 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004640
Steve Naroff54055232008-10-27 17:20:55 +00004641 while (*argPtr && parenCount) {
4642 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004643 case '(': parenCount++; break;
4644 case ')': parenCount--; break;
4645 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00004646 }
4647 if (parenCount) argPtr++;
4648 }
4649 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4650 RParen = argPtr; // output the end
4651}
4652
4653void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4654 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4655 RewriteBlockPointerFunctionArgs(FD);
4656 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004657 }
Steve Naroff54055232008-10-27 17:20:55 +00004658 // Handle Variables and Typedefs.
4659 SourceLocation DeclLoc = ND->getLocation();
4660 QualType DeclT;
4661 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4662 DeclT = VD->getType();
4663 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4664 DeclT = TDD->getUnderlyingType();
4665 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4666 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004667 else
Steve Naroff54055232008-10-27 17:20:55 +00004668 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00004669
Steve Naroff54055232008-10-27 17:20:55 +00004670 const char *startBuf = SM->getCharacterData(DeclLoc);
4671 const char *endBuf = startBuf;
4672 // scan backward (from the decl location) for the end of the previous decl.
4673 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4674 startBuf--;
Mike Stump1eb44332009-09-09 15:08:12 +00004675
Steve Naroff54055232008-10-27 17:20:55 +00004676 // *startBuf != '^' if we are dealing with a pointer to function that
4677 // may take block argument types (which will be handled below).
4678 if (*startBuf == '^') {
4679 // Replace the '^' with '*', computing a negative offset.
4680 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004681 ReplaceText(DeclLoc, 1, "*");
Steve Naroff54055232008-10-27 17:20:55 +00004682 }
4683 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4684 // Replace the '^' with '*' for arguments.
4685 DeclLoc = ND->getLocation();
4686 startBuf = SM->getCharacterData(DeclLoc);
4687 const char *argListBegin, *argListEnd;
4688 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4689 while (argListBegin < argListEnd) {
4690 if (*argListBegin == '^') {
4691 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004692 ReplaceText(CaretLoc, 1, "*");
Steve Naroff54055232008-10-27 17:20:55 +00004693 }
4694 argListBegin++;
4695 }
4696 }
4697 return;
4698}
4699
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004700
4701/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4702/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4703/// struct Block_byref_id_object *src) {
4704/// _Block_object_assign (&_dest->object, _src->object,
4705/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4706/// [|BLOCK_FIELD_IS_WEAK]) // object
4707/// _Block_object_assign(&_dest->object, _src->object,
4708/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4709/// [|BLOCK_FIELD_IS_WEAK]) // block
4710/// }
4711/// And:
4712/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4713/// _Block_object_dispose(_src->object,
4714/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4715/// [|BLOCK_FIELD_IS_WEAK]) // object
4716/// _Block_object_dispose(_src->object,
4717/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4718/// [|BLOCK_FIELD_IS_WEAK]) // block
4719/// }
4720
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004721std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4722 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004723 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00004724 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004725 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004726 CopyDestroyCache.insert(flag);
4727 S = "static void __Block_byref_id_object_copy_";
4728 S += utostr(flag);
4729 S += "(void *dst, void *src) {\n";
4730
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004731 // offset into the object pointer is computed as:
4732 // void * + void* + int + int + void* + void *
4733 unsigned IntSize =
4734 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4735 unsigned VoidPtrSize =
4736 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4737
4738 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
4739 S += " _Block_object_assign((char*)dst + ";
4740 S += utostr(offset);
4741 S += ", *(void * *) ((char*)src + ";
4742 S += utostr(offset);
4743 S += "), ";
4744 S += utostr(flag);
4745 S += ");\n}\n";
4746
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004747 S += "static void __Block_byref_id_object_dispose_";
4748 S += utostr(flag);
4749 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004750 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4751 S += utostr(offset);
4752 S += "), ";
4753 S += utostr(flag);
4754 S += ");\n}\n";
4755 return S;
4756}
4757
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004758/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4759/// the declaration into:
4760/// struct __Block_byref_ND {
4761/// void *__isa; // NULL for everything except __weak pointers
4762/// struct __Block_byref_ND *__forwarding;
4763/// int32_t __flags;
4764/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004765/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4766/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004767/// typex ND;
4768/// };
4769///
4770/// It then replaces declaration of ND variable with:
4771/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4772/// __size=sizeof(struct __Block_byref_ND),
4773/// ND=initializer-if-any};
4774///
4775///
4776void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004777 // Insert declaration for the function in which block literal is
4778 // used.
4779 if (CurFunctionDeclToDeclareForBlock)
4780 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004781 int flag = 0;
4782 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004783 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4784 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00004785 SourceLocation X = ND->getLocEnd();
4786 X = SM->getInstantiationLoc(X);
4787 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004788 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004789 std::string ByrefType;
4790 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004791 ByrefType += " {\n";
4792 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004793 RewriteByRefString(ByrefType, Name, ND);
4794 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004795 ByrefType += " int __flags;\n";
4796 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004797 // Add void *__Block_byref_id_object_copy;
4798 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004799 QualType Ty = ND->getType();
4800 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4801 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004802 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4803 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004804 }
4805
4806 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004807 ByrefType += " " + Name + ";\n";
4808 ByrefType += "};\n";
4809 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004810 SourceLocation FunLocStart;
4811 if (CurFunctionDef)
4812 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4813 else {
4814 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4815 FunLocStart = CurMethodDef->getLocStart();
4816 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00004817 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004818 if (Ty.isObjCGCWeak()) {
4819 flag |= BLOCK_FIELD_IS_WEAK;
4820 isa = 1;
4821 }
4822
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004823 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004824 flag = BLOCK_BYREF_CALLER;
4825 QualType Ty = ND->getType();
4826 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4827 if (Ty->isBlockPointerType())
4828 flag |= BLOCK_FIELD_IS_BLOCK;
4829 else
4830 flag |= BLOCK_FIELD_IS_OBJECT;
4831 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004832 if (!HF.empty())
Benjamin Kramerd999b372010-02-14 14:14:16 +00004833 InsertText(FunLocStart, HF);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004834 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004835
4836 // struct __Block_byref_ND ND =
4837 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4838 // initializer-if-any};
4839 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00004840 unsigned flags = 0;
4841 if (HasCopyAndDispose)
4842 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004843 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004844 ByrefType.clear();
4845 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004846 std::string ForwardingCastType("(");
4847 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004848 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004849 ByrefType += " " + Name + " = {(void*)";
4850 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004851 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004852 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004853 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004854 ByrefType += "sizeof(";
4855 RewriteByRefString(ByrefType, Name, ND);
4856 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004857 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004858 ByrefType += ", __Block_byref_id_object_copy_";
4859 ByrefType += utostr(flag);
4860 ByrefType += ", __Block_byref_id_object_dispose_";
4861 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004862 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004863 ByrefType += "};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00004864 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(), ByrefType);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004865 }
4866 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004867 SourceLocation startLoc;
4868 Expr *E = ND->getInit();
4869 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4870 startLoc = ECE->getLParenLoc();
4871 else
4872 startLoc = E->getLocStart();
Fariborz Jahanian791b10d2010-01-05 23:06:29 +00004873 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004874 endBuf = SM->getCharacterData(startLoc);
4875
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004876 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004877 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004878 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004879 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004880 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004881 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004882 ByrefType += "sizeof(";
4883 RewriteByRefString(ByrefType, Name, ND);
4884 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004885 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004886 ByrefType += "__Block_byref_id_object_copy_";
4887 ByrefType += utostr(flag);
4888 ByrefType += ", __Block_byref_id_object_dispose_";
4889 ByrefType += utostr(flag);
4890 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004891 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00004892 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroffc5143c52009-12-23 17:24:33 +00004893
4894 // Complete the newly synthesized compound expression by inserting a right
4895 // curly brace before the end of the declaration.
4896 // FIXME: This approach avoids rewriting the initializer expression. It
4897 // also assumes there is only one declarator. For example, the following
4898 // isn't currently supported by this routine (in general):
4899 //
4900 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4901 //
4902 const char *startBuf = SM->getCharacterData(startLoc);
4903 const char *semiBuf = strchr(startBuf, ';');
4904 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4905 SourceLocation semiLoc =
4906 startLoc.getFileLocWithOffset(semiBuf-startBuf);
4907
Benjamin Kramerd999b372010-02-14 14:14:16 +00004908 InsertText(semiLoc, "}");
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004909 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00004910 return;
4911}
4912
Mike Stump1eb44332009-09-09 15:08:12 +00004913void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00004914 // Add initializers for any closure decl refs.
4915 GetBlockDeclRefExprs(Exp->getBody());
4916 if (BlockDeclRefs.size()) {
4917 // Unique all "by copy" declarations.
4918 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004919 if (!BlockDeclRefs[i]->isByRef()) {
4920 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4921 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4922 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4923 }
4924 }
Steve Naroff54055232008-10-27 17:20:55 +00004925 // Unique all "by ref" declarations.
4926 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4927 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004928 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4929 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4930 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4931 }
Steve Naroff54055232008-10-27 17:20:55 +00004932 }
4933 // Find any imported blocks...they will need special attention.
4934 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004935 if (BlockDeclRefs[i]->isByRef() ||
4936 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian5b011b02010-02-26 21:46:27 +00004937 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff54055232008-10-27 17:20:55 +00004938 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff54055232008-10-27 17:20:55 +00004939 }
4940}
4941
Steve Narofffa15fd92008-10-28 20:29:00 +00004942FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4943 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00004944 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump1eb44332009-09-09 15:08:12 +00004945 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004946 ID, FType, 0, FunctionDecl::Extern, false,
Douglas Gregor2224f842009-02-25 16:33:18 +00004947 false);
Steve Narofffa15fd92008-10-28 20:29:00 +00004948}
4949
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004950Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
4951 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004952 Blocks.push_back(Exp);
4953
4954 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004955
4956 // Add inner imported variables now used in current block.
4957 int countOfInnerDecls = 0;
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004958 if (!InnerBlockDeclRefs.empty()) {
4959 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
4960 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
4961 ValueDecl *VD = Exp->getDecl();
4962 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004963 // We need to save the copied-in variables in nested
4964 // blocks because it is needed at the end for some of the API generations.
4965 // See SynthesizeBlockLiterals routine.
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004966 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4967 BlockDeclRefs.push_back(Exp);
4968 BlockByCopyDeclsPtrSet.insert(VD);
4969 BlockByCopyDecls.push_back(VD);
4970 }
4971 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4972 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4973 BlockDeclRefs.push_back(Exp);
4974 BlockByRefDeclsPtrSet.insert(VD);
4975 BlockByRefDecls.push_back(VD);
4976 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004977 }
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004978 // Find any imported blocks...they will need special attention.
4979 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
4980 if (InnerBlockDeclRefs[i]->isByRef() ||
4981 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4982 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4983 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004984 }
4985 InnerDeclRefsCount.push_back(countOfInnerDecls);
4986
Steve Narofffa15fd92008-10-28 20:29:00 +00004987 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00004988
Steve Narofffa15fd92008-10-28 20:29:00 +00004989 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00004990 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004991 else if (CurMethodDef)
4992 BuildUniqueMethodName(FuncName, CurMethodDef);
4993 else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004994 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00004995
Steve Narofffa15fd92008-10-28 20:29:00 +00004996 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00004997
Steve Narofffa15fd92008-10-28 20:29:00 +00004998 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4999 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00005000
Steve Narofffa15fd92008-10-28 20:29:00 +00005001 // Get a pointer to the function type so we can cast appropriately.
5002 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
5003
5004 FunctionDecl *FD;
5005 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00005006
Steve Narofffa15fd92008-10-28 20:29:00 +00005007 // Simulate a contructor call...
5008 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005009 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00005010
Steve Narofffa15fd92008-10-28 20:29:00 +00005011 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00005012
Steve Narofffdc03722008-10-29 21:23:59 +00005013 // Initialize the block function.
Steve Narofffa15fd92008-10-28 20:29:00 +00005014 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005015 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
5016 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005017 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5018 CastExpr::CK_Unknown, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00005019 InitExprs.push_back(castExpr);
5020
Steve Naroff01aec112009-12-06 21:14:13 +00005021 // Initialize the block descriptor.
5022 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00005023
Steve Naroff01aec112009-12-06 21:14:13 +00005024 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
5025 &Context->Idents.get(DescData.c_str()),
5026 Context->VoidPtrTy, 0,
5027 VarDecl::Static);
5028 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
5029 new (Context) DeclRefExpr(NewVD,
5030 Context->VoidPtrTy, SourceLocation()),
5031 UnaryOperator::AddrOf,
5032 Context->getPointerType(Context->VoidPtrTy),
5033 SourceLocation());
5034 InitExprs.push_back(DescRefExpr);
5035
Steve Narofffa15fd92008-10-28 20:29:00 +00005036 // Add initializers for any closure decl refs.
5037 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00005038 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00005039 // Output all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005040 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005041 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005042 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00005043 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner8ec03f52008-11-24 03:54:41 +00005044 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005045 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005046 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00005047 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005048 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005049 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5050 CastExpr::CK_Unknown, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00005051 } else {
Chris Lattner8ec03f52008-11-24 03:54:41 +00005052 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005053 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00005054 }
Mike Stump1eb44332009-09-09 15:08:12 +00005055 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005056 }
5057 // Output all "by ref" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005058 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005059 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005060 ValueDecl *ND = (*I);
5061 std::string Name(ND->getNameAsString());
5062 std::string RecName;
5063 RewriteByRefString(RecName, Name, ND);
5064 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5065 + sizeof("struct"));
5066 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
5067 SourceLocation(), II);
5068 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5069 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5070
Chris Lattner8ec03f52008-11-24 03:54:41 +00005071 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005072 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
5073 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00005074 Context->getPointerType(Exp->getType()),
Steve Narofffdc03722008-10-29 21:23:59 +00005075 SourceLocation());
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005076 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CastExpr::CK_Unknown, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00005077 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005078 }
5079 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00005080 if (ImportedBlockDecls.size()) {
5081 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5082 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00005083 unsigned IntSize =
5084 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanianff127882009-12-23 21:52:32 +00005085 Expr *FlagExp = new (Context) IntegerLiteral(llvm::APInt(IntSize, flag),
5086 Context->IntTy, SourceLocation());
5087 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00005088 }
Ted Kremenek668bf912009-02-09 20:51:47 +00005089 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
5090 FType, SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005091 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00005092 Context->getPointerType(NewRep->getType()),
Steve Narofffa15fd92008-10-28 20:29:00 +00005093 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005094 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CastExpr::CK_Unknown,
5095 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00005096 BlockDeclRefs.clear();
5097 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005098 BlockByRefDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005099 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005100 BlockByCopyDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005101 ImportedBlockDecls.clear();
5102 return NewRep;
5103}
5104
5105//===----------------------------------------------------------------------===//
5106// Function Body / Expression rewriting
5107//===----------------------------------------------------------------------===//
5108
Steve Naroffc77a6362008-12-04 16:24:46 +00005109// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
5110// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
5111// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
5112// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
5113// Since the rewriter isn't capable of rewriting rewritten code, it's important
5114// we get this right.
5115void RewriteObjC::CollectPropertySetters(Stmt *S) {
5116 // Perform a bottom up traversal of all children.
5117 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5118 CI != E; ++CI)
5119 if (*CI)
5120 CollectPropertySetters(*CI);
5121
5122 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
5123 if (BinOp->isAssignmentOp()) {
5124 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
5125 PropSetters[PRE] = BinOp;
5126 }
5127 }
5128}
5129
Steve Narofffa15fd92008-10-28 20:29:00 +00005130Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00005131 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005132 isa<DoStmt>(S) || isa<ForStmt>(S))
5133 Stmts.push_back(S);
5134 else if (isa<ObjCForCollectionStmt>(S)) {
5135 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00005136 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00005137 }
Mike Stump1eb44332009-09-09 15:08:12 +00005138
Steve Narofffa15fd92008-10-28 20:29:00 +00005139 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005140
Steve Narofffa15fd92008-10-28 20:29:00 +00005141 // Perform a bottom up rewrite of all children.
5142 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5143 CI != E; ++CI)
5144 if (*CI) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005145 Stmt *newStmt;
5146 Stmt *S = (*CI);
5147 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5148 Expr *OldBase = IvarRefExpr->getBase();
5149 bool replaced = false;
5150 newStmt = RewriteObjCNestedIvarRefExpr(S, replaced);
5151 if (replaced) {
5152 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
5153 ReplaceStmt(OldBase, IRE->getBase());
5154 else
5155 ReplaceStmt(S, newStmt);
5156 }
5157 }
5158 else
5159 newStmt = RewriteFunctionBodyOrGlobalInitializer(S);
Mike Stump1eb44332009-09-09 15:08:12 +00005160 if (newStmt)
Steve Narofffa15fd92008-10-28 20:29:00 +00005161 *CI = newStmt;
5162 }
Mike Stump1eb44332009-09-09 15:08:12 +00005163
Steve Narofffa15fd92008-10-28 20:29:00 +00005164 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005165 llvm::SmallPtrSet<ValueDecl *, 8> InnerBlockValueDecls;
5166 llvm::SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
5167 GetInnerBlockDeclRefExprs(BE->getBody(),
5168 InnerBlockDeclRefs, InnerBlockValueDecls);
Steve Narofffa15fd92008-10-28 20:29:00 +00005169 // Rewrite the block body in place.
5170 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Mike Stump1eb44332009-09-09 15:08:12 +00005171
Steve Narofffa15fd92008-10-28 20:29:00 +00005172 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenek6a12a142010-01-07 18:00:35 +00005173 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005174 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00005175
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005176 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5177
Steve Narofffa15fd92008-10-28 20:29:00 +00005178 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005179 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00005180 return blockTranscribed;
5181 }
5182 // Handle specific things.
5183 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5184 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00005185
Steve Naroffc77a6362008-12-04 16:24:46 +00005186 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
5187 BinaryOperator *BinOp = PropSetters[PropRefExpr];
5188 if (BinOp) {
5189 // Because the rewriter doesn't allow us to rewrite rewritten code,
5190 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00005191 DisableReplaceStmt = true;
5192 // Save the source range. Even if we disable the replacement, the
5193 // rewritten node will have been inserted into the tree. If the synthesized
5194 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump1eb44332009-09-09 15:08:12 +00005195 // self.errorHandler = handler ? handler :
Steve Naroffb619d952008-12-09 12:56:34 +00005196 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5197 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00005198 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroffb619d952008-12-09 12:56:34 +00005199 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00005200 //
5201 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
5202 // we changed the RHS of BinOp, the rewriter would fail (since it needs
5203 // to see the original expression). Consider this example:
5204 //
5205 // Foo *obj1, *obj2;
5206 //
5207 // obj1.i = [obj2 rrrr];
5208 //
5209 // 'BinOp' for the previous expression looks like:
5210 //
5211 // (BinaryOperator 0x231ccf0 'int' '='
5212 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5213 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5214 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5215 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5216 //
5217 // 'newStmt' represents the rewritten message expression. For example:
5218 //
5219 // (CallExpr 0x231d300 'id':'struct objc_object *'
5220 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5221 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5222 // (CStyleCastExpr 0x231d220 'void *'
5223 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5224 //
5225 // Note that 'newStmt' is passed to RewritePropertySetter so that it
5226 // can be used as the setter argument. ReplaceStmt() will still 'see'
5227 // the original RHS (since we haven't altered BinOp).
5228 //
Mike Stump1eb44332009-09-09 15:08:12 +00005229 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff4c3580e2008-12-04 23:50:32 +00005230 // node. As a result, we now leak the original AST nodes.
5231 //
Steve Naroffb619d952008-12-09 12:56:34 +00005232 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00005233 } else {
5234 return RewritePropertyGetter(PropRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00005235 }
5236 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005237 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5238 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00005239
Steve Narofffa15fd92008-10-28 20:29:00 +00005240 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5241 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00005242
Steve Narofffa15fd92008-10-28 20:29:00 +00005243 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00005244#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00005245 // Before we rewrite it, put the original message expression in a comment.
5246 SourceLocation startLoc = MessExpr->getLocStart();
5247 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00005248
Steve Narofffa15fd92008-10-28 20:29:00 +00005249 const char *startBuf = SM->getCharacterData(startLoc);
5250 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00005251
Steve Narofffa15fd92008-10-28 20:29:00 +00005252 std::string messString;
5253 messString += "// ";
5254 messString.append(startBuf, endBuf-startBuf+1);
5255 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00005256
5257 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00005258 // InsertText(clang::SourceLocation, char const*, unsigned int).
5259 // InsertText(startLoc, messString.c_str(), messString.size());
5260 // Tried this, but it didn't work either...
5261 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00005262#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00005263 return RewriteMessageExpr(MessExpr);
5264 }
Mike Stump1eb44332009-09-09 15:08:12 +00005265
Steve Narofffa15fd92008-10-28 20:29:00 +00005266 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5267 return RewriteObjCTryStmt(StmtTry);
5268
5269 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5270 return RewriteObjCSynchronizedStmt(StmtTry);
5271
5272 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5273 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00005274
Steve Narofffa15fd92008-10-28 20:29:00 +00005275 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5276 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00005277
5278 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00005279 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00005280 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00005281 OrigStmtRange.getEnd());
5282 if (BreakStmt *StmtBreakStmt =
5283 dyn_cast<BreakStmt>(S))
5284 return RewriteBreakStmt(StmtBreakStmt);
5285 if (ContinueStmt *StmtContinueStmt =
5286 dyn_cast<ContinueStmt>(S))
5287 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00005288
5289 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00005290 // and cast exprs.
5291 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5292 // FIXME: What we're doing here is modifying the type-specifier that
5293 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00005294 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00005295 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5296 // the context of an ObjCForCollectionStmt. For example:
5297 // NSArray *someArray;
5298 // for (id <FooProtocol> index in someArray) ;
5299 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5300 // and it depends on the original text locations/positions.
Benjamin Kramerb2041de2009-12-05 22:16:51 +00005301 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroff3d7e7862009-12-05 15:55:59 +00005302 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00005303
Steve Narofffa15fd92008-10-28 20:29:00 +00005304 // Blocks rewrite rules.
5305 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5306 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00005307 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00005308 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005309 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005310 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00005311 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005312 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005313 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005314 if (VD->hasAttr<BlocksAttr>()) {
5315 static unsigned uniqueByrefDeclCount = 0;
5316 assert(!BlockByRefDeclNo.count(ND) &&
5317 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5318 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005319 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005320 }
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005321 else
5322 RewriteTypeOfDecl(VD);
5323 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005324 }
5325 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005326 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005327 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005328 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005329 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5330 }
5331 }
5332 }
Mike Stump1eb44332009-09-09 15:08:12 +00005333
Steve Narofffa15fd92008-10-28 20:29:00 +00005334 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5335 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00005336
5337 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005338 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5339 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00005340 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5341 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005342 && "Statement stack mismatch");
5343 Stmts.pop_back();
5344 }
5345 // Handle blocks rewriting.
5346 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5347 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00005348 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00005349 }
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005350 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5351 ValueDecl *VD = DRE->getDecl();
5352 if (VD->hasAttr<BlocksAttr>())
5353 return RewriteBlockDeclRefExpr(DRE);
5354 }
5355
Steve Narofffa15fd92008-10-28 20:29:00 +00005356 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005357 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00005358 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005359 ReplaceStmt(S, BlockCall);
5360 return BlockCall;
5361 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005362 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00005363 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005364 RewriteCastExpr(CE);
5365 }
5366#if 0
5367 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00005368 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00005369 // Get the new text.
5370 std::string SStr;
5371 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00005372 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00005373 const std::string &Str = Buf.str();
5374
5375 printf("CAST = %s\n", &Str[0]);
5376 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5377 delete S;
5378 return Replacement;
5379 }
5380#endif
5381 // Return this stmt unmodified.
5382 return S;
5383}
5384
Steve Naroff3d7e7862009-12-05 15:55:59 +00005385void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5386 for (RecordDecl::field_iterator i = RD->field_begin(),
5387 e = RD->field_end(); i != e; ++i) {
5388 FieldDecl *FD = *i;
5389 if (isTopLevelBlockPointerType(FD->getType()))
5390 RewriteBlockPointerDecl(FD);
5391 if (FD->getType()->isObjCQualifiedIdType() ||
5392 FD->getType()->isObjCQualifiedInterfaceType())
5393 RewriteObjCQualifiedInterfaceTypes(FD);
5394 }
5395}
5396
Steve Narofffa15fd92008-10-28 20:29:00 +00005397/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5398/// main file of the input.
5399void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5400 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00005401 if (FD->isOverloadedOperator())
5402 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005403
Steve Narofffa15fd92008-10-28 20:29:00 +00005404 // Since function prototypes don't have ParmDecl's, we check the function
5405 // prototype. This enables us to rewrite function declarations and
5406 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00005407 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005408
Sebastian Redld3a413d2009-04-26 20:35:05 +00005409 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005410 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005411 CurFunctionDef = FD;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005412 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005413 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005414 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005415 Body =
5416 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5417 FD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005418 CurrentBody = 0;
5419 if (PropParentMap) {
5420 delete PropParentMap;
5421 PropParentMap = 0;
5422 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005423 // This synthesizes and inserts the block "impl" struct, invoke function,
5424 // and any copy/dispose helper functions.
5425 InsertBlockLiteralsWithinFunction(FD);
5426 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005427 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005428 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005429 return;
5430 }
5431 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005432 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005433 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005434 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005435 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005436 Body =
5437 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5438 MD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005439 CurrentBody = 0;
5440 if (PropParentMap) {
5441 delete PropParentMap;
5442 PropParentMap = 0;
5443 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005444 InsertBlockLiteralsWithinMethod(MD);
5445 CurMethodDef = 0;
5446 }
5447 }
5448 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5449 ClassImplementation.push_back(CI);
5450 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5451 CategoryImplementation.push_back(CI);
5452 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5453 RewriteForwardClassDecl(CD);
5454 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5455 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005456 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005457 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005458 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005459 CheckFunctionPointerDecl(VD->getType(), VD);
5460 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00005461 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005462 RewriteCastExpr(CE);
5463 }
5464 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00005465 } else if (VD->getType()->isRecordType()) {
5466 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5467 if (RD->isDefinition())
5468 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005469 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005470 if (VD->getInit()) {
5471 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005472 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005473 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005474 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005475 CurrentBody = 0;
5476 if (PropParentMap) {
5477 delete PropParentMap;
5478 PropParentMap = 0;
5479 }
Mike Stump1eb44332009-09-09 15:08:12 +00005480 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00005481 VD->getNameAsCString());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005482 GlobalVarDecl = 0;
5483
5484 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00005485 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005486 RewriteCastExpr(CE);
5487 }
5488 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005489 return;
5490 }
5491 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005492 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005493 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005494 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005495 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5496 return;
5497 }
5498 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroff3d7e7862009-12-05 15:55:59 +00005499 if (RD->isDefinition())
5500 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005501 return;
5502 }
5503 // Nothing yet.
5504}
5505
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00005506void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005507 if (Diags.hasErrorOccurred())
5508 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005509
Steve Narofffa15fd92008-10-28 20:29:00 +00005510 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00005511
Steve Naroff621edce2009-04-29 16:37:50 +00005512 // Here's a great place to add any extra declarations that may be needed.
5513 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00005514 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00005515 E = ProtocolExprDecls.end(); I != E; ++I)
5516 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5517
Benjamin Kramerd999b372010-02-14 14:14:16 +00005518 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff0aab7962008-11-14 14:10:01 +00005519 if (ClassImplementation.size() || CategoryImplementation.size())
5520 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00005521
Steve Narofffa15fd92008-10-28 20:29:00 +00005522 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5523 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00005524 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00005525 Rewrite.getRewriteBufferFor(MainFileID)) {
5526 //printf("Changed:\n");
5527 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5528 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +00005529 llvm::errs() << "No changes\n";
Steve Narofffa15fd92008-10-28 20:29:00 +00005530 }
Steve Narofface66252008-11-13 20:07:04 +00005531
Steve Naroff621edce2009-04-29 16:37:50 +00005532 if (ClassImplementation.size() || CategoryImplementation.size() ||
5533 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00005534 // Rewrite Objective-c meta data*
5535 std::string ResultStr;
5536 SynthesizeMetaDataIntoBuffer(ResultStr);
5537 // Emit metadata.
5538 *OutFile << ResultStr;
5539 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005540 OutFile->flush();
5541}
5542