blob: 87b1cd40e4a1b9c520034fd09523b17b4486ba5b [file] [log] [blame]
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattnere99c8322007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-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 Lattnere99c8322007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Eli Friedman9f30fc32009-05-18 22:50:54 +000014#include "clang/Frontend/ASTConsumers.h"
Chris Lattner16a0de42007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattnere99c8322007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Steve Naroff1042ff32008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Chris Lattner16a0de42007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner4431a1b2007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattnerf3a59a12007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000023#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
Chris Lattner211f8b82007-10-25 17:07:24 +000025#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian99e96b02007-10-26 19:46:17 +000026#include "llvm/ADT/SmallPtrSet.h"
Ted Kremenek2d470fc2008-09-13 05:16:45 +000027#include "llvm/ADT/OwningPtr.h"
Fariborz Jahaniane3891582010-01-05 18:04:40 +000028#include "llvm/ADT/DenseSet.h"
Chris Lattnere99c8322007-10-11 00:43:27 +000029using namespace clang;
Chris Lattner211f8b82007-10-25 17:07:24 +000030using llvm::utostr;
Chris Lattnere99c8322007-10-11 00:43:27 +000031
Chris Lattnere99c8322007-10-11 00:43:27 +000032namespace {
Steve Naroff1dc53ef2008-04-14 22:03:09 +000033 class RewriteObjC : public ASTConsumer {
Fariborz Jahanian4bf727d2009-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 Lattner0bd1c972007-10-16 21:07:07 +000056 Rewriter Rewrite;
Chris Lattnere9c810c2007-11-30 22:25:36 +000057 Diagnostic &Diags;
Steve Naroff945a3b12008-03-10 20:43:59 +000058 const LangOptions &LangOpts;
Steve Naroff7b3579b2008-01-30 19:17:43 +000059 unsigned RewriteFailedDiag;
Steve Naroff6d6da252008-12-05 17:03:39 +000060 unsigned TryFinallyContainsReturnDiag;
Mike Stump11289f42009-09-09 15:08:12 +000061
Chris Lattnerc6d91c02007-10-17 22:35:30 +000062 ASTContext *Context;
Chris Lattnere99c8322007-10-11 00:43:27 +000063 SourceManager *SM;
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +000064 TranslationUnitDecl *TUDecl;
Chris Lattnerd32480d2009-01-17 06:22:33 +000065 FileID MainFileID;
Chris Lattnerf3a59a12007-12-02 01:13:47 +000066 const char *MainFileStart, *MainFileEnd;
Chris Lattner0bd1c972007-10-16 21:07:07 +000067 SourceLocation LastIncLoc;
Mike Stump11289f42009-09-09 15:08:12 +000068
Ted Kremenek1b0ea822008-01-07 19:49:32 +000069 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
70 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
71 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Naroff13e74872008-05-06 18:26:51 +000072 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremenek1b0ea822008-01-07 19:49:32 +000073 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
74 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +000075 llvm::SmallVector<Stmt *, 32> Stmts;
76 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffd9803712009-04-29 16:37:50 +000077 // Remember all the @protocol(<expr>) expressions.
78 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahaniane3891582010-01-05 18:04:40 +000079
80 llvm::DenseSet<uint64_t> CopyDestroyCache;
81
Steve Naroffce8e8862008-03-15 00:55:56 +000082 unsigned NumObjCStringLiterals;
Mike Stump11289f42009-09-09 15:08:12 +000083
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000084 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +000085 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +000086 FunctionDecl *MsgSendStretFunctionDecl;
87 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian4f76f222007-12-03 21:26:48 +000088 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000089 FunctionDecl *GetClassFunctionDecl;
Steve Naroffb2f8ff12007-12-07 03:50:46 +000090 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff574440f2007-10-24 22:48:43 +000091 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff265a6b92007-11-08 14:30:50 +000092 FunctionDecl *CFStringFunctionDecl;
Steve Naroff17978c42008-03-11 17:37:02 +000093 FunctionDecl *SuperContructorFunctionDecl;
Mike Stump11289f42009-09-09 15:08:12 +000094
Steve Naroffa397efd2007-11-03 11:27:19 +000095 // ObjC string constant support.
Steve Naroff08899ff2008-04-15 22:42:06 +000096 VarDecl *ConstantStringClassReference;
Steve Naroffa397efd2007-11-03 11:27:19 +000097 RecordDecl *NSStringRecord;
Mike Stump11289f42009-09-09 15:08:12 +000098
Fariborz Jahanian19d42bf2008-01-16 00:09:11 +000099 // ObjC foreach break/continue generation support.
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000100 int BcLabelCount;
Mike Stump11289f42009-09-09 15:08:12 +0000101
Steve Naroff7fa2f042007-11-15 10:28:18 +0000102 // Needed for super.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000103 ObjCMethodDecl *CurMethodDef;
Steve Naroff7fa2f042007-11-15 10:28:18 +0000104 RecordDecl *SuperStructDecl;
Steve Naroffce8e8862008-03-15 00:55:56 +0000105 RecordDecl *ConstantStringDecl;
Mike Stump11289f42009-09-09 15:08:12 +0000106
Steve Naroffd9803712009-04-29 16:37:50 +0000107 TypeDecl *ProtocolTypeDecl;
108 QualType getProtocolType();
Mike Stump11289f42009-09-09 15:08:12 +0000109
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000110 // Needed for header files being rewritten
111 bool IsHeader;
Mike Stump11289f42009-09-09 15:08:12 +0000112
Steve Narofff9e7c902008-03-28 22:26:09 +0000113 std::string InFileName;
Eli Friedman94cf21e2009-05-18 22:20:00 +0000114 llvm::raw_ostream* OutFile;
Eli Friedmanf22439a2009-05-18 22:39:16 +0000115
116 bool SilenceRewriteMacroWarning;
Fariborz Jahanianbc6811c2010-01-07 22:51:18 +0000117 bool objc_impl_method;
Eli Friedmanf22439a2009-05-18 22:39:16 +0000118
Steve Naroff00a31762008-03-27 22:29:16 +0000119 std::string Preamble;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000120
121 // Block expressions.
122 llvm::SmallVector<BlockExpr *, 32> Blocks;
123 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
124 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Mike Stump11289f42009-09-09 15:08:12 +0000125
Steve Naroff677ab3a2008-10-27 17:20:55 +0000126 // Block related declarations.
127 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
128 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
129 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
130
131 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
132
Steve Naroff4588d0f2008-12-04 16:24:46 +0000133 // This maps a property to it's assignment statement.
134 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Naroff1042ff32008-12-08 16:43:47 +0000135 // This maps a property to it's synthesied message expression.
136 // This allows us to rewrite chained getters (e.g. o.a.b.c).
137 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
Mike Stump11289f42009-09-09 15:08:12 +0000138
Steve Naroff22216db2008-12-04 23:50:32 +0000139 // This maps an original source AST to it's rewritten form. This allows
140 // us to avoid rewriting the same node twice (which is very uncommon).
141 // This is needed to support some of the exotic property rewriting.
142 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Narofff326f402008-12-03 00:56:33 +0000143
Steve Naroff677ab3a2008-10-27 17:20:55 +0000144 FunctionDecl *CurFunctionDef;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000145 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Steve Naroffd8907b72008-10-29 18:15:37 +0000146 VarDecl *GlobalVarDecl;
Mike Stump11289f42009-09-09 15:08:12 +0000147
Steve Naroff08628db2008-12-09 12:56:34 +0000148 bool DisableReplaceStmt;
Mike Stump11289f42009-09-09 15:08:12 +0000149
Fariborz Jahanian93191af2007-10-18 19:23:00 +0000150 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnere99c8322007-10-11 00:43:27 +0000151 public:
Ted Kremenek380df932008-05-31 20:11:04 +0000152 virtual void Initialize(ASTContext &context);
153
Chris Lattner3c799d72007-10-24 17:06:59 +0000154 // Top Level Driver code.
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000155 virtual void HandleTopLevelDecl(DeclGroupRef D) {
156 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
157 HandleTopLevelSingleDecl(*I);
158 }
159 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000160 void HandleDeclInMainFile(Decl *D);
Eli Friedman94cf21e2009-05-18 22:20:00 +0000161 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000162 Diagnostic &D, const LangOptions &LOpts,
163 bool silenceMacroWarn);
Ted Kremenek6231e7e2008-08-08 04:15:52 +0000164
165 ~RewriteObjC() {}
Mike Stump11289f42009-09-09 15:08:12 +0000166
Chris Lattnercf169832009-03-28 04:11:33 +0000167 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump11289f42009-09-09 15:08:12 +0000168
Chris Lattner2e0d2602008-01-31 19:37:57 +0000169 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff22216db2008-12-04 23:50:32 +0000170 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump11289f42009-09-09 15:08:12 +0000171
Steve Naroff22216db2008-12-04 23:50:32 +0000172 if (ReplacingStmt)
173 return; // We can't rewrite the same node twice.
Chris Lattner2e0d2602008-01-31 19:37:57 +0000174
Steve Naroff08628db2008-12-09 12:56:34 +0000175 if (DisableReplaceStmt)
176 return; // Used when rewriting the assignment of a property setter.
177
Steve Naroff22216db2008-12-04 23:50:32 +0000178 // If replacement succeeded or warning disabled return with no warning.
179 if (!Rewrite.ReplaceStmt(Old, New)) {
180 ReplacedNodes[Old] = New;
181 return;
182 }
183 if (SilenceRewriteMacroWarning)
184 return;
Chris Lattner8488c822008-11-18 07:04:44 +0000185 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
186 << Old->getSourceRange();
Chris Lattner2e0d2602008-01-31 19:37:57 +0000187 }
Steve Naroff08628db2008-12-09 12:56:34 +0000188
189 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
190 // Measaure the old text.
191 int Size = Rewrite.getRangeSize(SrcRange);
192 if (Size == -1) {
193 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
194 << Old->getSourceRange();
195 return;
196 }
197 // Get the new text.
198 std::string SStr;
199 llvm::raw_string_ostream S(SStr);
Chris Lattnerc61089a2009-06-30 01:26:17 +0000200 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroff08628db2008-12-09 12:56:34 +0000201 const std::string &Str = S.str();
202
203 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000204 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroff08628db2008-12-09 12:56:34 +0000205 ReplacedNodes[Old] = New;
206 return;
207 }
208 if (SilenceRewriteMacroWarning)
209 return;
210 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
211 << Old->getSourceRange();
212 }
213
Steve Naroff00a31762008-03-27 22:29:16 +0000214 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
215 bool InsertAfter = true) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000216 // If insertion succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000217 if (!Rewrite.InsertText(Loc, llvm::StringRef(StrData, StrLen),
218 InsertAfter) ||
Chris Lattner1780a852008-01-31 19:42:41 +0000219 SilenceRewriteMacroWarning)
220 return;
Mike Stump11289f42009-09-09 15:08:12 +0000221
Chris Lattner1780a852008-01-31 19:42:41 +0000222 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
223 }
Mike Stump11289f42009-09-09 15:08:12 +0000224
Chris Lattner9cc55f52008-01-31 19:51:04 +0000225 void RemoveText(SourceLocation Loc, unsigned StrLen) {
226 // If removal succeeded or warning disabled return with no warning.
227 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
228 return;
Mike Stump11289f42009-09-09 15:08:12 +0000229
Chris Lattner9cc55f52008-01-31 19:51:04 +0000230 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
231 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000232
Chris Lattner9cc55f52008-01-31 19:51:04 +0000233 void ReplaceText(SourceLocation Start, unsigned OrigLength,
234 const char *NewStr, unsigned NewLength) {
235 // If removal succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000236 if (!Rewrite.ReplaceText(Start, OrigLength,
237 llvm::StringRef(NewStr, NewLength)) ||
Chris Lattner9cc55f52008-01-31 19:51:04 +0000238 SilenceRewriteMacroWarning)
239 return;
Mike Stump11289f42009-09-09 15:08:12 +0000240
Chris Lattner9cc55f52008-01-31 19:51:04 +0000241 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
242 }
Mike Stump11289f42009-09-09 15:08:12 +0000243
Chris Lattner3c799d72007-10-24 17:06:59 +0000244 // Syntactic Rewriting.
Steve Narofff36987c2007-11-04 22:37:50 +0000245 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000246 void RewriteInclude();
Chris Lattner3c799d72007-10-24 17:06:59 +0000247 void RewriteTabs();
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000248 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffc038b3a2008-12-02 17:36:43 +0000249 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
250 ObjCImplementationDecl *IMD,
251 ObjCCategoryImplDecl *CID);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000252 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000253 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000254 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
255 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
256 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
257 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
258 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000259 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000260 void RewriteFunctionDecl(FunctionDecl *FD);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000261 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000262 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff873bd842008-07-29 18:15:38 +0000263 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroff50d42052007-11-01 13:24:47 +0000264 bool needToScanForQualifiers(QualType T);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000265 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff7fa2f042007-11-15 10:28:18 +0000266 QualType getSuperStructType();
Steve Naroffce8e8862008-03-15 00:55:56 +0000267 QualType getConstantStringStructType();
Steve Naroffcd92aeb2008-05-31 14:15:04 +0000268 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump11289f42009-09-09 15:08:12 +0000269
Chris Lattner3c799d72007-10-24 17:06:59 +0000270 // Expression Rewriting.
Steve Naroff20113382007-11-09 15:20:18 +0000271 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroff4588d0f2008-12-04 16:24:46 +0000272 void CollectPropertySetters(Stmt *S);
Mike Stump11289f42009-09-09 15:08:12 +0000273
Steve Naroff1042ff32008-12-08 16:43:47 +0000274 Stmt *CurrentBody;
275 ParentMap *PropParentMap; // created lazily.
Mike Stump11289f42009-09-09 15:08:12 +0000276
Chris Lattner69534692007-10-24 16:57:36 +0000277 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner37f5b7d2008-05-23 20:40:52 +0000278 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroff4588d0f2008-12-04 16:24:46 +0000279 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Mike Stump11289f42009-09-09 15:08:12 +0000280 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroff08628db2008-12-09 12:56:34 +0000281 SourceRange SrcRange);
Steve Naroffe4f9b232007-11-05 14:50:49 +0000282 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner69534692007-10-24 16:57:36 +0000283 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffa397efd2007-11-03 11:27:19 +0000284 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian33c0e812007-12-07 18:47:10 +0000285 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffec60b432009-12-05 21:43:12 +0000286 void WarnAboutReturnGotoStmts(Stmt *S);
287 void HasReturnStmts(Stmt *S, bool &hasReturns);
288 void RewriteTryReturnStmts(Stmt *S);
289 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000290 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian284011b2008-01-29 22:59:37 +0000291 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000292 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
293 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
294 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattnera779d692008-01-31 05:10:40 +0000295 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
296 SourceLocation OrigEnd);
Mike Stump11289f42009-09-09 15:08:12 +0000297 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Steve Naroff574440f2007-10-24 22:48:43 +0000298 Expr **args, unsigned nargs);
Fariborz Jahanian965a8962008-01-08 22:06:28 +0000299 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000300 Stmt *RewriteBreakStmt(BreakStmt *S);
301 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian965a8962008-01-08 22:06:28 +0000302 void SynthCountByEnumWithState(std::string &buf);
Mike Stump11289f42009-09-09 15:08:12 +0000303
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000304 void SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +0000305 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000306 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +0000307 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000308 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000309 void SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +0000310 void SynthGetMetaClassFunctionDecl();
Fariborz Jahanian31e18502007-12-04 21:47:40 +0000311 void SynthSelGetUidFunctionDecl();
Steve Naroff17978c42008-03-11 17:37:02 +0000312 void SynthSuperContructorFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000313
Chris Lattner3c799d72007-10-24 17:06:59 +0000314 // Metadata emission.
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000315 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000316 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000317
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000318 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000319 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000320
Douglas Gregor29bd76f2009-04-23 01:02:12 +0000321 template<typename MethodIterator>
322 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
323 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +0000324 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +0000325 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +0000326 const char *ClassName,
327 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000328
Steve Naroffd9803712009-04-29 16:37:50 +0000329 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
330 const char *prefix,
331 const char *ClassName,
332 std::string &Result);
333 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Mike Stump11289f42009-09-09 15:08:12 +0000334 const char *prefix,
Steve Naroffd9803712009-04-29 16:37:50 +0000335 const char *ClassName,
336 std::string &Result);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000337 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000338 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000339 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
340 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000341 std::string &Result);
Steve Narofff8cfd162008-11-13 20:07:04 +0000342 void RewriteImplementations();
343 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000344
Steve Naroff677ab3a2008-10-27 17:20:55 +0000345 // Block rewriting.
Mike Stump11289f42009-09-09 15:08:12 +0000346 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000347 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump11289f42009-09-09 15:08:12 +0000348
Steve Naroff677ab3a2008-10-27 17:20:55 +0000349 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
350 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump11289f42009-09-09 15:08:12 +0000351
352 // Block specific rewrite rules.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000353 void RewriteBlockCall(CallExpr *Exp);
354 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000355 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahaniane3891582010-01-05 18:04:40 +0000356 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +0000357 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000358 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump11289f42009-09-09 15:08:12 +0000359
360 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000361 const char *funcName, std::string Tag);
Mike Stump11289f42009-09-09 15:08:12 +0000362 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000363 const char *funcName, std::string Tag);
Steve Naroff30484702009-12-06 21:14:13 +0000364 std::string SynthesizeBlockImpl(BlockExpr *CE,
365 std::string Tag, std::string Desc);
366 std::string SynthesizeBlockDescriptor(std::string DescTag,
367 std::string ImplTag,
368 int i, const char *funcName,
369 unsigned hasCopy);
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +0000370 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000371 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000372 const char *FunName);
Steve Naroffe70a52a2009-12-05 15:55:59 +0000373 void RewriteRecordBody(RecordDecl *RD);
Mike Stump11289f42009-09-09 15:08:12 +0000374
Steve Naroff677ab3a2008-10-27 17:20:55 +0000375 void CollectBlockDeclRefInfo(BlockExpr *Exp);
376 void GetBlockCallExprs(Stmt *S);
377 void GetBlockDeclRefExprs(Stmt *S);
Mike Stump11289f42009-09-09 15:08:12 +0000378
Steve Naroff677ab3a2008-10-27 17:20:55 +0000379 // We avoid calling Type::isBlockPointerType(), since it operates on the
380 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek5a201952009-02-07 01:47:29 +0000381 bool isTopLevelBlockPointerType(QualType T) {
382 return isa<BlockPointerType>(T);
383 }
Mike Stump11289f42009-09-09 15:08:12 +0000384
Steve Naroff677ab3a2008-10-27 17:20:55 +0000385 // FIXME: This predicate seems like it would be useful to add to ASTContext.
386 bool isObjCType(QualType T) {
387 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
388 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000389
Steve Naroff677ab3a2008-10-27 17:20:55 +0000390 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000391
Steve Naroff677ab3a2008-10-27 17:20:55 +0000392 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
393 OCT == Context->getCanonicalType(Context->getObjCClassType()))
394 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000395
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000396 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +0000397 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Narofffb4330f2009-06-17 22:40:22 +0000398 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff677ab3a2008-10-27 17:20:55 +0000399 return true;
400 }
401 return false;
402 }
403 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek5a201952009-02-07 01:47:29 +0000404 void GetExtentOfArgList(const char *Name, const char *&LParen,
405 const char *&RParen);
Steve Naroffc989a7b2008-11-03 23:29:32 +0000406 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump11289f42009-09-09 15:08:12 +0000407
Steve Narofff4b992a2008-10-28 20:29:00 +0000408 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroffd8907b72008-10-29 18:15:37 +0000409 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Mike Stump11289f42009-09-09 15:08:12 +0000410
Steve Naroffd9803712009-04-29 16:37:50 +0000411 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump11289f42009-09-09 15:08:12 +0000412 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroffd9803712009-04-29 16:37:50 +0000413 if (From[i] == '"')
414 To += "\\\"";
415 else
416 To += From[i];
417 }
418 }
Chris Lattnere99c8322007-10-11 00:43:27 +0000419 };
420}
421
Mike Stump11289f42009-09-09 15:08:12 +0000422void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
423 NamedDecl *D) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000424 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000425 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +0000426 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +0000427 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +0000428 // All the args are checked/rewritten. Don't call twice!
429 RewriteBlockPointerDecl(D);
430 break;
431 }
432 }
433}
434
435void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000436 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +0000437 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000438 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000439}
440
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000441static bool IsHeaderFile(const std::string &Filename) {
442 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump11289f42009-09-09 15:08:12 +0000443
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000444 if (DotPos == std::string::npos) {
445 // no file extension
Mike Stump11289f42009-09-09 15:08:12 +0000446 return false;
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000447 }
Mike Stump11289f42009-09-09 15:08:12 +0000448
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000449 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
450 // C header: .h
451 // C++ header: .hh or .H;
452 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump11289f42009-09-09 15:08:12 +0000453}
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000454
Eli Friedman94cf21e2009-05-18 22:20:00 +0000455RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000456 Diagnostic &D, const LangOptions &LOpts,
457 bool silenceMacroWarn)
458 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
459 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Narofff9e7c902008-03-28 22:26:09 +0000460 IsHeader = IsHeaderFile(inFile);
Mike Stump11289f42009-09-09 15:08:12 +0000461 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Narofff9e7c902008-03-28 22:26:09 +0000462 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump11289f42009-09-09 15:08:12 +0000463 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek5a201952009-02-07 01:47:29 +0000464 "rewriter doesn't support user-specified control flow semantics "
465 "for @try/@finally (code may not execute properly)");
Steve Narofff9e7c902008-03-28 22:26:09 +0000466}
467
Eli Friedmana63ab2d2009-05-18 22:29:17 +0000468ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
469 llvm::raw_ostream* OS,
Mike Stump11289f42009-09-09 15:08:12 +0000470 Diagnostic &Diags,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000471 const LangOptions &LOpts,
472 bool SilenceRewriteMacroWarning) {
473 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere9c810c2007-11-30 22:25:36 +0000474}
Chris Lattnere99c8322007-10-11 00:43:27 +0000475
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000476void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner187f6262008-01-31 19:38:44 +0000477 Context = &context;
478 SM = &Context->getSourceManager();
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +0000479 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner187f6262008-01-31 19:38:44 +0000480 MsgSendFunctionDecl = 0;
481 MsgSendSuperFunctionDecl = 0;
482 MsgSendStretFunctionDecl = 0;
483 MsgSendSuperStretFunctionDecl = 0;
484 MsgSendFpretFunctionDecl = 0;
485 GetClassFunctionDecl = 0;
486 GetMetaClassFunctionDecl = 0;
487 SelGetUidFunctionDecl = 0;
488 CFStringFunctionDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000489 ConstantStringClassReference = 0;
490 NSStringRecord = 0;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000491 CurMethodDef = 0;
492 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000493 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000494 GlobalVarDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000495 SuperStructDecl = 0;
Steve Naroffd9803712009-04-29 16:37:50 +0000496 ProtocolTypeDecl = 0;
Steve Naroff60a9ef62008-03-27 22:59:54 +0000497 ConstantStringDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000498 BcLabelCount = 0;
Steve Naroff17978c42008-03-11 17:37:02 +0000499 SuperContructorFunctionDecl = 0;
Steve Naroffce8e8862008-03-15 00:55:56 +0000500 NumObjCStringLiterals = 0;
Steve Narofff1ab6002008-12-08 20:01:41 +0000501 PropParentMap = 0;
502 CurrentBody = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000503 DisableReplaceStmt = false;
Fariborz Jahanianbc6811c2010-01-07 22:51:18 +0000504 objc_impl_method = false;
Mike Stump11289f42009-09-09 15:08:12 +0000505
Chris Lattner187f6262008-01-31 19:38:44 +0000506 // Get the ID and start/end of the main file.
507 MainFileID = SM->getMainFileID();
508 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
509 MainFileStart = MainBuf->getBufferStart();
510 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000511
Chris Lattner184e65d2009-04-14 23:22:57 +0000512 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump11289f42009-09-09 15:08:12 +0000513
Chris Lattner187f6262008-01-31 19:38:44 +0000514 // declaring objc_selector outside the parameter list removes a silly
515 // scope related warning...
Steve Naroff00a31762008-03-27 22:29:16 +0000516 if (IsHeader)
Steve Narofffcc6fd52009-02-03 20:39:18 +0000517 Preamble = "#pragma once\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000518 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff6ab6dc72008-12-23 20:11:22 +0000519 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroff00a31762008-03-27 22:29:16 +0000520 Preamble += "struct objc_object *superClass; ";
Steve Naroff17978c42008-03-11 17:37:02 +0000521 if (LangOpts.Microsoft) {
522 // Add a constructor for creating temporary objects.
Ted Kremenek5a201952009-02-07 01:47:29 +0000523 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
524 ": ";
Steve Naroff00a31762008-03-27 22:29:16 +0000525 Preamble += "object(o), superClass(s) {} ";
Steve Naroff17978c42008-03-11 17:37:02 +0000526 }
Steve Naroff00a31762008-03-27 22:29:16 +0000527 Preamble += "};\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000528 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
529 Preamble += "typedef struct objc_object Protocol;\n";
530 Preamble += "#define _REWRITER_typedef_Protocol\n";
531 Preamble += "#endif\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000532 if (LangOpts.Microsoft) {
533 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
534 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
535 } else
536 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
537 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroff00a31762008-03-27 22:29:16 +0000538 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000539 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroff00a31762008-03-27 22:29:16 +0000540 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000541 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000542 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000543 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000544 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000545 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroff00a31762008-03-27 22:29:16 +0000546 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000547 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000548 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000549 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000550 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000551 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
552 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
553 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
554 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
555 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroffd30f8c52008-05-09 21:17:56 +0000556 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff8dd15252008-07-16 18:58:11 +0000557 // @synchronized hooks.
Steve Narofff122ff02008-12-08 17:30:33 +0000558 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
559 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
560 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000561 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
562 Preamble += "struct __objcFastEnumerationState {\n\t";
563 Preamble += "unsigned long state;\n\t";
Steve Naroff4dbab8a2008-04-04 22:58:22 +0000564 Preamble += "void **itemsPtr;\n\t";
Steve Naroff00a31762008-03-27 22:29:16 +0000565 Preamble += "unsigned long *mutationsPtr;\n\t";
566 Preamble += "unsigned long extra[5];\n};\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000567 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000568 Preamble += "#define __FASTENUMERATIONSTATE\n";
569 Preamble += "#endif\n";
570 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
571 Preamble += "struct __NSConstantStringImpl {\n";
572 Preamble += " int *isa;\n";
573 Preamble += " int flags;\n";
574 Preamble += " char *str;\n";
575 Preamble += " long length;\n";
576 Preamble += "};\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000577 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
578 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
579 Preamble += "#else\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000580 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000581 Preamble += "#endif\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000582 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
583 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000584 // Blocks preamble.
585 Preamble += "#ifndef BLOCK_IMPL\n";
586 Preamble += "#define BLOCK_IMPL\n";
587 Preamble += "struct __block_impl {\n";
588 Preamble += " void *isa;\n";
589 Preamble += " int Flags;\n";
Steve Naroff30484702009-12-06 21:14:13 +0000590 Preamble += " int Reserved;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000591 Preamble += " void *FuncPtr;\n";
592 Preamble += "};\n";
Steve Naroff61d879e2008-12-16 15:50:30 +0000593 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroff287a2bf2009-12-06 01:52:22 +0000594 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000595 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_assign(void *, const void *, const int);\n";
596 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
597 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
598 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
599 Preamble += "#else\n";
Steve Naroff7bf01ea2010-01-05 18:09:31 +0000600 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
601 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000602 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
603 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
604 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000605 Preamble += "#endif\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000606 if (LangOpts.Microsoft) {
Steve Narofff122ff02008-12-08 17:30:33 +0000607 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
608 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000609 Preamble += "#define __attribute__(X)\n";
610 }
Fariborz Jahanian7fac6552010-01-05 19:21:35 +0000611 else {
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000612 Preamble += "#define __block\n";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +0000613 Preamble += "#define __weak\n";
614 }
Chris Lattner187f6262008-01-31 19:38:44 +0000615}
616
617
Chris Lattner3c799d72007-10-24 17:06:59 +0000618//===----------------------------------------------------------------------===//
619// Top Level Driver Code
620//===----------------------------------------------------------------------===//
621
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000622void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Chris Lattner0bd1c972007-10-16 21:07:07 +0000623 // Two cases: either the decl could be in the main file, or it could be in a
624 // #included file. If the former, rewrite it now. If the later, check to see
625 // if we rewrote the #include/#import.
626 SourceLocation Loc = D->getLocation();
Chris Lattner8a425862009-01-16 07:36:28 +0000627 Loc = SM->getInstantiationLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000628
Chris Lattner0bd1c972007-10-16 21:07:07 +0000629 // If this is for a builtin, ignore it.
630 if (Loc.isInvalid()) return;
631
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000632 // Look for built-in declarations that we need to refer during the rewrite.
633 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000634 RewriteFunctionDecl(FD);
Steve Naroff08899ff2008-04-15 22:42:06 +0000635 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000636 // declared in <Foundation/NSString.h>
Chris Lattner86d7d912008-11-24 03:54:41 +0000637 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000638 ConstantStringClassReference = FVD;
639 return;
640 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000641 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff161a92b2007-10-26 20:53:56 +0000642 RewriteInterfaceDecl(MD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000643 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000644 RewriteCategoryDecl(CD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000645 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff921385f2007-10-30 16:42:30 +0000646 RewriteProtocolDecl(PD);
Mike Stump11289f42009-09-09 15:08:12 +0000647 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000648 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000649 RewriteForwardProtocolDecl(FP);
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000650 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
651 // Recurse into linkage specifications
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000652 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
653 DIEnd = LSD->decls_end();
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000654 DI != DIEnd; ++DI)
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000655 HandleTopLevelSingleDecl(*DI);
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000656 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000657 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekd61ed3b2008-04-14 21:24:13 +0000658 if (SM->isFromMainFile(Loc))
Chris Lattner0bd1c972007-10-16 21:07:07 +0000659 return HandleDeclInMainFile(D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000660}
661
Chris Lattner3c799d72007-10-24 17:06:59 +0000662//===----------------------------------------------------------------------===//
663// Syntactic (non-AST) Rewriting Code
664//===----------------------------------------------------------------------===//
665
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000666void RewriteObjC::RewriteInclude() {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000667 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000668 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
669 const char *MainBufStart = MainBuf.first;
670 const char *MainBufEnd = MainBuf.second;
671 size_t ImportLen = strlen("import");
672 size_t IncludeLen = strlen("include");
Mike Stump11289f42009-09-09 15:08:12 +0000673
Fariborz Jahanian137d6932008-01-19 01:03:17 +0000674 // Loop over the whole file, looking for includes.
Fariborz Jahanian80258362008-01-19 00:30:35 +0000675 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
676 if (*BufPtr == '#') {
677 if (++BufPtr == MainBufEnd)
678 return;
679 while (*BufPtr == ' ' || *BufPtr == '\t')
680 if (++BufPtr == MainBufEnd)
681 return;
682 if (!strncmp(BufPtr, "import", ImportLen)) {
683 // replace import with include
Mike Stump11289f42009-09-09 15:08:12 +0000684 SourceLocation ImportLoc =
Fariborz Jahanian80258362008-01-19 00:30:35 +0000685 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000686 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000687 BufPtr += ImportLen;
688 }
689 }
690 }
Chris Lattner0bd1c972007-10-16 21:07:07 +0000691}
692
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000693void RewriteObjC::RewriteTabs() {
Chris Lattner3c799d72007-10-24 17:06:59 +0000694 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
695 const char *MainBufStart = MainBuf.first;
696 const char *MainBufEnd = MainBuf.second;
Mike Stump11289f42009-09-09 15:08:12 +0000697
Chris Lattner3c799d72007-10-24 17:06:59 +0000698 // Loop over the whole file, looking for tabs.
699 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
700 if (*BufPtr != '\t')
701 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000702
Chris Lattner3c799d72007-10-24 17:06:59 +0000703 // Okay, we found a tab. This tab will turn into at least one character,
704 // but it depends on which 'virtual column' it is in. Compute that now.
705 unsigned VCol = 0;
706 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
707 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
708 ++VCol;
Mike Stump11289f42009-09-09 15:08:12 +0000709
Chris Lattner3c799d72007-10-24 17:06:59 +0000710 // Okay, now that we know the virtual column, we know how many spaces to
711 // insert. We assume 8-character tab-stops.
712 unsigned Spaces = 8-(VCol & 7);
Mike Stump11289f42009-09-09 15:08:12 +0000713
Chris Lattner3c799d72007-10-24 17:06:59 +0000714 // Get the location of the tab.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000715 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
716 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Mike Stump11289f42009-09-09 15:08:12 +0000717
Chris Lattner3c799d72007-10-24 17:06:59 +0000718 // Rewrite the single tab character into a sequence of spaces.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000719 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattner3c799d72007-10-24 17:06:59 +0000720 }
Chris Lattner16a0de42007-10-11 18:38:32 +0000721}
722
Steve Naroff9af94912008-12-02 15:48:25 +0000723static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
724 ObjCIvarDecl *OID) {
725 std::string S;
726 S = "((struct ";
727 S += ClassDecl->getIdentifier()->getName();
728 S += "_IMPL *)self)->";
Daniel Dunbar70e7ead2009-10-18 20:26:27 +0000729 S += OID->getName();
Steve Naroff9af94912008-12-02 15:48:25 +0000730 return S;
731}
732
Steve Naroffc038b3a2008-12-02 17:36:43 +0000733void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
734 ObjCImplementationDecl *IMD,
735 ObjCCategoryImplDecl *CID) {
Steve Naroffe1908e32008-12-01 20:33:01 +0000736 SourceLocation startLoc = PID->getLocStart();
737 InsertText(startLoc, "// ", 3);
Steve Naroff9af94912008-12-02 15:48:25 +0000738 const char *startBuf = SM->getCharacterData(startLoc);
739 assert((*startBuf == '@') && "bogus @synthesize location");
740 const char *semiBuf = strchr(startBuf, ';');
741 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek5a201952009-02-07 01:47:29 +0000742 SourceLocation onePastSemiLoc =
743 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroff9af94912008-12-02 15:48:25 +0000744
745 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
746 return; // FIXME: is this correct?
Mike Stump11289f42009-09-09 15:08:12 +0000747
Steve Naroff9af94912008-12-02 15:48:25 +0000748 // Generate the 'getter' function.
Steve Naroff9af94912008-12-02 15:48:25 +0000749 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroff9af94912008-12-02 15:48:25 +0000750 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroff9af94912008-12-02 15:48:25 +0000751 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000752
Steve Naroff003d00e2008-12-02 16:05:55 +0000753 if (!OID)
754 return;
Mike Stump11289f42009-09-09 15:08:12 +0000755
Steve Naroff003d00e2008-12-02 16:05:55 +0000756 std::string Getr;
757 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
758 Getr += "{ ";
759 // Synthesize an explicit cast to gain access to the ivar.
Mike Stump11289f42009-09-09 15:08:12 +0000760 // FIXME: deal with code generation implications for various property
761 // attributes (copy, retain, nonatomic).
Steve Naroff06297042008-12-02 17:54:50 +0000762 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroff003d00e2008-12-02 16:05:55 +0000763 Getr += "return " + getIvarAccessString(ClassDecl, OID);
764 Getr += "; }";
Steve Naroff9af94912008-12-02 15:48:25 +0000765 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroff9af94912008-12-02 15:48:25 +0000766 if (PD->isReadOnly())
767 return;
Mike Stump11289f42009-09-09 15:08:12 +0000768
Steve Naroff9af94912008-12-02 15:48:25 +0000769 // Generate the 'setter' function.
770 std::string Setr;
771 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroff9af94912008-12-02 15:48:25 +0000772 Setr += "{ ";
Steve Naroff003d00e2008-12-02 16:05:55 +0000773 // Synthesize an explicit cast to initialize the ivar.
Mike Stump11289f42009-09-09 15:08:12 +0000774 // FIXME: deal with code generation implications for various property
775 // attributes (copy, retain, nonatomic).
Steve Narofff326f402008-12-03 00:56:33 +0000776 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroff003d00e2008-12-02 16:05:55 +0000777 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000778 Setr += PD->getNameAsCString();
Steve Naroff003d00e2008-12-02 16:05:55 +0000779 Setr += "; }";
Steve Naroff9af94912008-12-02 15:48:25 +0000780 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffe1908e32008-12-01 20:33:01 +0000781}
Chris Lattner16a0de42007-10-11 18:38:32 +0000782
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000783void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattner3c799d72007-10-24 17:06:59 +0000784 // Get the start location and compute the semi location.
785 SourceLocation startLoc = ClassDecl->getLocation();
786 const char *startBuf = SM->getCharacterData(startLoc);
787 const char *semiPtr = strchr(startBuf, ';');
Mike Stump11289f42009-09-09 15:08:12 +0000788
Chris Lattner3c799d72007-10-24 17:06:59 +0000789 // Translate to typedef's that forward reference structs with the same name
790 // as the class. As a convenience, we include the original declaration
791 // as a comment.
792 std::string typedefString;
Fariborz Jahanian1c2cb6d2010-01-11 22:48:40 +0000793 typedefString += "// @class ";
794 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
795 I != E; ++I) {
796 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
797 typedefString += ForwardDecl->getNameAsString();
798 if (I+1 != E)
799 typedefString += ", ";
800 else
801 typedefString += ";\n";
802 }
803
Chris Lattner9ee23b72009-02-20 18:04:31 +0000804 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
805 I != E; ++I) {
Ted Kremenek9b124e12009-11-18 00:28:11 +0000806 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff1b232132007-11-09 12:50:28 +0000807 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000808 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000809 typedefString += "\n";
810 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000811 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000812 typedefString += "\n";
Steve Naroff98eb8d12007-11-05 14:36:37 +0000813 typedefString += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000814 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000815 typedefString += ";\n#endif\n";
Steve Naroff574440f2007-10-24 22:48:43 +0000816 }
Mike Stump11289f42009-09-09 15:08:12 +0000817
Steve Naroff574440f2007-10-24 22:48:43 +0000818 // Replace the @class with typedefs corresponding to the classes.
Mike Stump11289f42009-09-09 15:08:12 +0000819 ReplaceText(startLoc, semiPtr-startBuf+1,
Chris Lattner9cc55f52008-01-31 19:51:04 +0000820 typedefString.c_str(), typedefString.size());
Chris Lattner3c799d72007-10-24 17:06:59 +0000821}
822
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000823void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff3ce37a62007-12-14 23:37:57 +0000824 SourceLocation LocStart = Method->getLocStart();
825 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000826
Chris Lattner88ea93e2009-02-04 01:06:56 +0000827 if (SM->getInstantiationLineNumber(LocEnd) >
828 SM->getInstantiationLineNumber(LocStart)) {
Steve Naroffe020fa12008-10-21 13:37:27 +0000829 InsertText(LocStart, "#if 0\n", 6);
830 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff3ce37a62007-12-14 23:37:57 +0000831 } else {
Chris Lattner1780a852008-01-31 19:42:41 +0000832 InsertText(LocStart, "// ", 3);
Steve Naroff5448cf62007-10-30 13:30:57 +0000833 }
834}
835
Mike Stump11289f42009-09-09 15:08:12 +0000836void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000837 SourceLocation Loc = prop->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000838
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000839 ReplaceText(Loc, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000840
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000841 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahaniane8a30162007-11-07 00:09:37 +0000842}
843
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000844void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000845 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000846
Steve Naroff5448cf62007-10-30 13:30:57 +0000847 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000848 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000849
850 for (ObjCCategoryDecl::instmeth_iterator
851 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000852 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000853 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +0000854 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000855 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000856 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000857 RewriteMethodDeclaration(*I);
858
Steve Naroff5448cf62007-10-30 13:30:57 +0000859 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +0000860 ReplaceText(CatDecl->getAtEndRange().getBegin(), 0, "// ", 3);
Steve Naroff5448cf62007-10-30 13:30:57 +0000861}
862
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000863void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000864 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Mike Stump11289f42009-09-09 15:08:12 +0000865
Steve Narofff921385f2007-10-30 16:42:30 +0000866 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000867
Steve Narofff921385f2007-10-30 16:42:30 +0000868 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000869 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000870
871 for (ObjCProtocolDecl::instmeth_iterator
872 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000873 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000874 RewriteMethodDeclaration(*I);
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000875 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000876 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000877 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000878 RewriteMethodDeclaration(*I);
879
Steve Narofff921385f2007-10-30 16:42:30 +0000880 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +0000881 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Chris Lattner9cc55f52008-01-31 19:51:04 +0000882 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroffa509f042007-11-14 15:03:57 +0000883
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000884 // Must comment out @optional/@required
885 const char *startBuf = SM->getCharacterData(LocStart);
886 const char *endBuf = SM->getCharacterData(LocEnd);
887 for (const char *p = startBuf; p < endBuf; p++) {
888 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
889 std::string CommentedOptional = "/* @optional */";
Steve Naroffa509f042007-11-14 15:03:57 +0000890 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000891 ReplaceText(OptionalLoc, strlen("@optional"),
892 CommentedOptional.c_str(), CommentedOptional.size());
Mike Stump11289f42009-09-09 15:08:12 +0000893
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000894 }
895 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
896 std::string CommentedRequired = "/* @required */";
Steve Naroffa509f042007-11-14 15:03:57 +0000897 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000898 ReplaceText(OptionalLoc, strlen("@required"),
899 CommentedRequired.c_str(), CommentedRequired.size());
Mike Stump11289f42009-09-09 15:08:12 +0000900
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000901 }
902 }
Steve Narofff921385f2007-10-30 16:42:30 +0000903}
904
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000905void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000906 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffc17b0562007-11-14 03:37:28 +0000907 if (LocStart.isInvalid())
908 assert(false && "Invalid SourceLocation");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000909 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000910 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000911}
912
Mike Stump11289f42009-09-09 15:08:12 +0000913void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000914 std::string &ResultStr) {
Steve Naroff295570a2008-10-30 12:09:33 +0000915 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroffb067bbd2008-07-16 14:40:40 +0000916 const FunctionType *FPRetType = 0;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000917 ResultStr += "\nstatic ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000918 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +0000919 ResultStr += "id";
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000920 else if (OMD->getResultType()->isFunctionPointerType() ||
921 OMD->getResultType()->isBlockPointerType()) {
Steve Naroffb067bbd2008-07-16 14:40:40 +0000922 // needs special handling, since pointer-to-functions have special
923 // syntax (where a decaration models use).
924 QualType retType = OMD->getResultType();
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000925 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000926 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000927 PointeeTy = PT->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000928 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000929 PointeeTy = BPT->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +0000930 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000931 ResultStr += FPRetType->getResultType().getAsString();
932 ResultStr += "(*";
Steve Naroffb067bbd2008-07-16 14:40:40 +0000933 }
934 } else
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +0000935 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7262fca2008-01-10 01:39:52 +0000936 ResultStr += " ";
Mike Stump11289f42009-09-09 15:08:12 +0000937
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000938 // Unique method name
Fariborz Jahanian56338352007-11-13 21:02:00 +0000939 std::string NameStr;
Mike Stump11289f42009-09-09 15:08:12 +0000940
Douglas Gregorffca3a22009-01-09 17:18:27 +0000941 if (OMD->isInstanceMethod())
Fariborz Jahanian56338352007-11-13 21:02:00 +0000942 NameStr += "_I_";
943 else
944 NameStr += "_C_";
Mike Stump11289f42009-09-09 15:08:12 +0000945
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000946 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +0000947 NameStr += "_";
Mike Stump11289f42009-09-09 15:08:12 +0000948
949 if (ObjCCategoryImplDecl *CID =
Steve Naroff11b387f2009-01-08 19:41:02 +0000950 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000951 NameStr += CID->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +0000952 NameStr += "_";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000953 }
Mike Stump11289f42009-09-09 15:08:12 +0000954 // Append selector names, replacing ':' with '_'
Chris Lattnere4b95692008-11-24 03:33:13 +0000955 {
956 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000957 int len = selString.size();
958 for (int i = 0; i < len; i++)
959 if (selString[i] == ':')
960 selString[i] = '_';
Fariborz Jahanian56338352007-11-13 21:02:00 +0000961 NameStr += selString;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000962 }
Fariborz Jahanian56338352007-11-13 21:02:00 +0000963 // Remember this name for metadata emission
964 MethodInternalNames[OMD] = NameStr;
965 ResultStr += NameStr;
Mike Stump11289f42009-09-09 15:08:12 +0000966
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000967 // Rewrite arguments
968 ResultStr += "(";
Mike Stump11289f42009-09-09 15:08:12 +0000969
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000970 // invisible arguments
Douglas Gregorffca3a22009-01-09 17:18:27 +0000971 if (OMD->isInstanceMethod()) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000972 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000973 selfTy = Context->getPointerType(selfTy);
Steve Naroffdc5b6b22008-03-12 00:25:36 +0000974 if (!LangOpts.Microsoft) {
975 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
976 ResultStr += "struct ";
977 }
978 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000979 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +0000980 ResultStr += " *";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000981 }
982 else
Steve Naroffd9803712009-04-29 16:37:50 +0000983 ResultStr += Context->getObjCClassType().getAsString();
Mike Stump11289f42009-09-09 15:08:12 +0000984
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000985 ResultStr += " self, ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000986 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000987 ResultStr += " _cmd";
Mike Stump11289f42009-09-09 15:08:12 +0000988
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000989 // Method arguments.
Chris Lattnera4997152009-02-20 18:43:26 +0000990 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
991 E = OMD->param_end(); PI != E; ++PI) {
992 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000993 ResultStr += ", ";
Steve Naroffdcdcdcd2008-04-18 21:13:19 +0000994 if (PDecl->getType()->isObjCQualifiedIdType()) {
995 ResultStr += "id ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000996 ResultStr += PDecl->getNameAsString();
Steve Naroffdcdcdcd2008-04-18 21:13:19 +0000997 } else {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000998 std::string Name = PDecl->getNameAsString();
Steve Naroffa5c0db82008-12-11 21:05:33 +0000999 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroff44df6a22008-10-30 14:45:29 +00001000 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001001 const BlockPointerType *BPT = PDecl->getType()->getAs<BlockPointerType>();
Douglas Gregor7de59662009-05-29 20:38:28 +00001002 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name,
1003 Context->PrintingPolicy);
Steve Naroff44df6a22008-10-30 14:45:29 +00001004 } else
Douglas Gregor7de59662009-05-29 20:38:28 +00001005 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001006 ResultStr += Name;
1007 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001008 }
Fariborz Jahanianeab81cd2008-01-21 20:14:23 +00001009 if (OMD->isVariadic())
1010 ResultStr += ", ...";
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001011 ResultStr += ") ";
Mike Stump11289f42009-09-09 15:08:12 +00001012
Steve Naroffb067bbd2008-07-16 14:40:40 +00001013 if (FPRetType) {
1014 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump11289f42009-09-09 15:08:12 +00001015
Steve Naroffb067bbd2008-07-16 14:40:40 +00001016 // Now, emit the argument types (if any).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001017 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001018 ResultStr += "(";
1019 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1020 if (i) ResultStr += ", ";
1021 std::string ParamStr = FT->getArgType(i).getAsString();
1022 ResultStr += ParamStr;
1023 }
1024 if (FT->isVariadic()) {
1025 if (FT->getNumArgs()) ResultStr += ", ";
1026 ResultStr += "...";
1027 }
1028 ResultStr += ")";
1029 } else {
1030 ResultStr += "()";
1031 }
1032 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001033}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001034void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001035 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1036 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump11289f42009-09-09 15:08:12 +00001037
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001038 if (IMD)
Chris Lattner1780a852008-01-31 19:42:41 +00001039 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001040 else
Chris Lattner1780a852008-01-31 19:42:41 +00001041 InsertText(CID->getLocStart(), "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +00001042
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001043 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001044 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1045 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001046 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001047 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001048 ObjCMethodDecl *OMD = *I;
1049 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001050 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001051 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redla7b98a72009-04-26 20:35:05 +00001052
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001053 const char *startBuf = SM->getCharacterData(LocStart);
1054 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattner9cc55f52008-01-31 19:51:04 +00001055 ReplaceText(LocStart, endBuf-startBuf,
1056 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001057 }
Mike Stump11289f42009-09-09 15:08:12 +00001058
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001059 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001060 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1061 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001062 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001063 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001064 ObjCMethodDecl *OMD = *I;
1065 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001066 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001067 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +00001068
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001069 const char *startBuf = SM->getCharacterData(LocStart);
1070 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattner9cc55f52008-01-31 19:51:04 +00001071 ReplaceText(LocStart, endBuf-startBuf,
Mike Stump11289f42009-09-09 15:08:12 +00001072 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001073 }
Steve Naroffe1908e32008-12-01 20:33:01 +00001074 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001075 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001076 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001077 I != E; ++I) {
Steve Naroffc038b3a2008-12-02 17:36:43 +00001078 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffe1908e32008-12-01 20:33:01 +00001079 }
1080
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001081 if (IMD)
Chris Lattner1780a852008-01-31 19:42:41 +00001082 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001083 else
Mike Stump11289f42009-09-09 15:08:12 +00001084 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001085}
1086
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001087void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffc5484042007-10-30 02:23:23 +00001088 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001089 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff2f55b982007-11-01 03:35:41 +00001090 // we haven't seen a forward decl - generate a typedef.
Steve Naroff03f27672007-11-14 23:02:56 +00001091 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001092 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001093 ResultStr += "\n";
1094 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001095 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001096 ResultStr += "\n";
Steve Naroffa1e115e2008-03-10 23:16:54 +00001097 ResultStr += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001098 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001099 ResultStr += ";\n#endif\n";
Steve Naroff2f55b982007-11-01 03:35:41 +00001100 // Mark this typedef as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001101 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff2f55b982007-11-01 03:35:41 +00001102 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001103 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump11289f42009-09-09 15:08:12 +00001104
1105 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001106 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff0c0f5ba2009-01-11 01:06:09 +00001107 RewriteProperty(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001108 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001109 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001110 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001111 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001112 for (ObjCInterfaceDecl::classmeth_iterator
1113 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001114 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001115 RewriteMethodDeclaration(*I);
1116
Steve Naroff4cd61ac2007-10-30 03:43:13 +00001117 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +00001118 ReplaceText(ClassDecl->getAtEndRange().getBegin(), 0, "// ", 3);
Steve Naroff161a92b2007-10-26 20:53:56 +00001119}
1120
Steve Naroff08628db2008-12-09 12:56:34 +00001121Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1122 SourceRange SrcRange) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00001123 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1124 // This allows us to reuse all the fun and games in SynthMessageExpr().
1125 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1126 ObjCMessageExpr *MsgExpr;
1127 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1128 llvm::SmallVector<Expr *, 1> ExprVec;
1129 ExprVec.push_back(newStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001130
Steve Naroff1042ff32008-12-08 16:43:47 +00001131 Stmt *Receiver = PropRefExpr->getBase();
1132 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1133 if (PRE && PropGetters[PRE]) {
1134 // This allows us to handle chain/nested property getters.
1135 Receiver = PropGetters[PRE];
1136 }
Mike Stump11289f42009-09-09 15:08:12 +00001137 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1138 PDecl->getSetterName(), PDecl->getType(),
1139 PDecl->getSetterMethodDecl(),
1140 SourceLocation(), SourceLocation(),
Steve Naroff4588d0f2008-12-04 16:24:46 +00001141 &ExprVec[0], 1);
1142 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001143
Steve Naroff4588d0f2008-12-04 16:24:46 +00001144 // Now do the actual rewrite.
Steve Naroff08628db2008-12-09 12:56:34 +00001145 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffdf705772008-12-10 14:53:27 +00001146 //delete BinOp;
Ted Kremenek5a201952009-02-07 01:47:29 +00001147 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1148 // to things that stay around.
1149 Context->Deallocate(MsgExpr);
Steve Naroff4588d0f2008-12-04 16:24:46 +00001150 return ReplacingStmt;
Steve Narofff326f402008-12-03 00:56:33 +00001151}
1152
Steve Naroff4588d0f2008-12-04 16:24:46 +00001153Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Narofff326f402008-12-03 00:56:33 +00001154 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1155 // This allows us to reuse all the fun and games in SynthMessageExpr().
1156 ObjCMessageExpr *MsgExpr;
1157 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
Mike Stump11289f42009-09-09 15:08:12 +00001158
Steve Naroff1042ff32008-12-08 16:43:47 +00001159 Stmt *Receiver = PropRefExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00001160
Steve Naroff1042ff32008-12-08 16:43:47 +00001161 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1162 if (PRE && PropGetters[PRE]) {
1163 // This allows us to handle chain/nested property getters.
1164 Receiver = PropGetters[PRE];
1165 }
Mike Stump11289f42009-09-09 15:08:12 +00001166 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1167 PDecl->getGetterName(), PDecl->getType(),
1168 PDecl->getGetterMethodDecl(),
1169 SourceLocation(), SourceLocation(),
Steve Narofff326f402008-12-03 00:56:33 +00001170 0, 0);
1171
Steve Naroff22216db2008-12-04 23:50:32 +00001172 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001173
1174 if (!PropParentMap)
1175 PropParentMap = new ParentMap(CurrentBody);
1176
1177 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1178 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1179 // We stash away the ReplacingStmt since actually doing the
1180 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1181 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek5a201952009-02-07 01:47:29 +00001182 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1183 // to things that stay around.
1184 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001185 return PropRefExpr; // return the original...
1186 } else {
1187 ReplaceStmt(PropRefExpr, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001188 // delete PropRefExpr; elsewhere...
Ted Kremenek5a201952009-02-07 01:47:29 +00001189 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1190 // to things that stay around.
1191 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001192 return ReplacingStmt;
1193 }
Steve Narofff326f402008-12-03 00:56:33 +00001194}
1195
Mike Stump11289f42009-09-09 15:08:12 +00001196Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001197 SourceLocation OrigStart) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001198 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001199 const Expr *BaseExpr = IV->getBase();
Steve Naroff677ab3a2008-10-27 17:20:55 +00001200 if (CurMethodDef) {
Fariborz Jahanian12e2e862010-01-12 17:31:23 +00001201 if (BaseExpr->getType()->isObjCObjectPointerType() &&
1202 isa<DeclRefExpr>(BaseExpr)) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001203 ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001204 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroffb1c02372008-05-08 17:52:16 +00001205 // lookup which class implements the instance variable.
1206 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001207 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001208 clsDeclared);
Steve Naroffb1c02372008-05-08 17:52:16 +00001209 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001210
Steve Naroffb1c02372008-05-08 17:52:16 +00001211 // Synthesize an explicit cast to gain access to the ivar.
1212 std::string RecName = clsDeclared->getIdentifier()->getName();
1213 RecName += "_IMPL";
1214 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001215 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001216 SourceLocation(), II);
Steve Naroffb1c02372008-05-08 17:52:16 +00001217 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1218 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Mike Stump11289f42009-09-09 15:08:12 +00001219 CastExpr *castExpr = new (Context) CStyleCastExpr(castT,
Anders Carlssona2615922009-07-31 00:48:10 +00001220 CastExpr::CK_Unknown,
1221 IV->getBase(),
1222 castT,SourceLocation(),
1223 SourceLocation());
Steve Naroffb1c02372008-05-08 17:52:16 +00001224 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001225 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1226 IV->getBase()->getLocEnd(),
1227 castExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001228 if (IV->isFreeIvar() &&
Steve Naroff677ab3a2008-10-27 17:20:55 +00001229 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001230 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1231 IV->getLocation(),
1232 D->getType());
Steve Naroffb1c02372008-05-08 17:52:16 +00001233 ReplaceStmt(IV, ME);
Steve Naroff22216db2008-12-04 23:50:32 +00001234 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb1c02372008-05-08 17:52:16 +00001235 return ME;
Steve Naroff05caa482007-11-15 11:33:00 +00001236 }
Mike Stump11289f42009-09-09 15:08:12 +00001237
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001238 ReplaceStmt(IV->getBase(), PE);
1239 // Cannot delete IV->getBase(), since PE points to it.
1240 // Replace the old base with the cast. This is important when doing
1241 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001242 IV->setBase(PE);
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001243 return IV;
Steve Naroff05caa482007-11-15 11:33:00 +00001244 }
Steve Naroff24840f62008-04-18 21:55:08 +00001245 } else { // we are outside a method.
Steve Naroff29ce4e52008-05-06 23:20:07 +00001246 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump11289f42009-09-09 15:08:12 +00001247
Steve Naroff29ce4e52008-05-06 23:20:07 +00001248 // Explicit ivar refs need to have a cast inserted.
1249 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian12e2e862010-01-12 17:31:23 +00001250 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Fariborz Jahanian9146e442010-01-11 17:50:35 +00001251 ObjCInterfaceType *iFaceDecl =
1252 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001253 // lookup which class implements the instance variable.
1254 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001255 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001256 clsDeclared);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001257 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001258
Steve Naroff29ce4e52008-05-06 23:20:07 +00001259 // Synthesize an explicit cast to gain access to the ivar.
1260 std::string RecName = clsDeclared->getIdentifier()->getName();
1261 RecName += "_IMPL";
1262 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001263 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001264 SourceLocation(), II);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001265 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1266 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Mike Stump11289f42009-09-09 15:08:12 +00001267 CastExpr *castExpr = new (Context) CStyleCastExpr(castT,
Anders Carlssona2615922009-07-31 00:48:10 +00001268 CastExpr::CK_Unknown,
1269 IV->getBase(),
Ted Kremenek5a201952009-02-07 01:47:29 +00001270 castT, SourceLocation(),
1271 SourceLocation());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001272 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001273 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner34873d22008-05-28 16:38:23 +00001274 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001275 ReplaceStmt(IV->getBase(), PE);
1276 // Cannot delete IV->getBase(), since PE points to it.
1277 // Replace the old base with the cast. This is important when doing
1278 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001279 IV->setBase(PE);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001280 return IV;
1281 }
Steve Naroff05caa482007-11-15 11:33:00 +00001282 }
Steve Naroff24840f62008-04-18 21:55:08 +00001283 return IV;
Steve Narofff60782b2007-11-15 02:58:25 +00001284}
1285
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001286/// SynthCountByEnumWithState - To print:
1287/// ((unsigned int (*)
1288/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001289/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001290/// sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001291/// "countByEnumeratingWithState:objects:count:"),
1292/// &enumState,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001293/// (id *)items, (unsigned int)16)
1294///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001295void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001296 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1297 "id *, unsigned int))(void *)objc_msgSend)";
1298 buf += "\n\t\t";
1299 buf += "((id)l_collection,\n\t\t";
1300 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1301 buf += "\n\t\t";
1302 buf += "&enumState, "
1303 "(id *)items, (unsigned int)16)";
1304}
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001305
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001306/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1307/// statement to exit to its outer synthesized loop.
1308///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001309Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001310 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1311 return S;
1312 // replace break with goto __break_label
1313 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001314
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001315 SourceLocation startLoc = S->getLocStart();
1316 buf = "goto __break_label_";
1317 buf += utostr(ObjCBcLabelNo.back());
Chris Lattner9cc55f52008-01-31 19:51:04 +00001318 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001319
1320 return 0;
1321}
1322
1323/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1324/// statement to continue with its inner synthesized loop.
1325///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001326Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001327 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1328 return S;
1329 // replace continue with goto __continue_label
1330 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001331
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001332 SourceLocation startLoc = S->getLocStart();
1333 buf = "goto __continue_label_";
1334 buf += utostr(ObjCBcLabelNo.back());
Chris Lattner9cc55f52008-01-31 19:51:04 +00001335 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001336
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001337 return 0;
1338}
1339
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001340/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001341/// It rewrites:
1342/// for ( type elem in collection) { stmts; }
Mike Stump11289f42009-09-09 15:08:12 +00001343
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001344/// Into:
1345/// {
Mike Stump11289f42009-09-09 15:08:12 +00001346/// type elem;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001347/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001348/// id items[16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001349/// id l_collection = (id)collection;
Mike Stump11289f42009-09-09 15:08:12 +00001350/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001351/// objects:items count:16];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001352/// if (limit) {
1353/// unsigned long startMutations = *enumState.mutationsPtr;
1354/// do {
1355/// unsigned long counter = 0;
1356/// do {
Mike Stump11289f42009-09-09 15:08:12 +00001357/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001358/// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001359/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001360/// stmts;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001361/// __continue_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001362/// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001363/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001364/// objects:items count:16]);
1365/// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001366/// __break_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001367/// }
1368/// else
1369/// elem = nil;
1370/// }
1371///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001372Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattnera779d692008-01-31 05:10:40 +00001373 SourceLocation OrigEnd) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001374 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001375 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001376 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump11289f42009-09-09 15:08:12 +00001377 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001378 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001379
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001380 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001381 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001382 const char *elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001383 std::string elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001384 std::string buf;
1385 buf = "\n{\n\t";
1386 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1387 // type elem;
Chris Lattner529efc72009-03-28 06:33:19 +00001388 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek292b3842008-10-06 22:16:13 +00001389 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001390 if (ElementType->isObjCQualifiedIdType() ||
1391 ElementType->isObjCQualifiedInterfaceType())
1392 // Simply use 'id' for all qualified types.
1393 elementTypeAsString = "id";
1394 else
1395 elementTypeAsString = ElementType.getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001396 buf += elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001397 buf += " ";
Chris Lattner86d7d912008-11-24 03:54:41 +00001398 elementName = D->getNameAsCString();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001399 buf += elementName;
1400 buf += ";\n\t";
1401 }
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001402 else {
1403 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner86d7d912008-11-24 03:54:41 +00001404 elementName = DR->getDecl()->getNameAsCString();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001405 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1406 if (VD->getType()->isObjCQualifiedIdType() ||
1407 VD->getType()->isObjCQualifiedInterfaceType())
1408 // Simply use 'id' for all qualified types.
1409 elementTypeAsString = "id";
1410 else
1411 elementTypeAsString = VD->getType().getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001412 }
Mike Stump11289f42009-09-09 15:08:12 +00001413
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001414 // struct __objcFastEnumerationState enumState = { 0 };
1415 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1416 // id items[16];
1417 buf += "id items[16];\n\t";
1418 // id l_collection = (id)
1419 buf += "id l_collection = (id)";
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001420 // Find start location of 'collection' the hard way!
1421 const char *startCollectionBuf = startBuf;
1422 startCollectionBuf += 3; // skip 'for'
1423 startCollectionBuf = strchr(startCollectionBuf, '(');
1424 startCollectionBuf++; // skip '('
1425 // find 'in' and skip it.
1426 while (*startCollectionBuf != ' ' ||
1427 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1428 (*(startCollectionBuf+3) != ' ' &&
1429 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1430 startCollectionBuf++;
1431 startCollectionBuf += 3;
Mike Stump11289f42009-09-09 15:08:12 +00001432
1433 // Replace: "for (type element in" with string constructed thus far.
Chris Lattner9cc55f52008-01-31 19:51:04 +00001434 ReplaceText(startLoc, startCollectionBuf - startBuf,
1435 buf.c_str(), buf.size());
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001436 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001437 SourceLocation rightParenLoc = S->getRParenLoc();
1438 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1439 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001440 buf = ";\n\t";
Mike Stump11289f42009-09-09 15:08:12 +00001441
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001442 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1443 // objects:items count:16];
1444 // which is synthesized into:
Mike Stump11289f42009-09-09 15:08:12 +00001445 // unsigned int limit =
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001446 // ((unsigned int (*)
1447 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001448 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001449 // sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001450 // "countByEnumeratingWithState:objects:count:"),
1451 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001452 // (id *)items, (unsigned int)16);
1453 buf += "unsigned long limit =\n\t\t";
1454 SynthCountByEnumWithState(buf);
1455 buf += ";\n\t";
1456 /// if (limit) {
1457 /// unsigned long startMutations = *enumState.mutationsPtr;
1458 /// do {
1459 /// unsigned long counter = 0;
1460 /// do {
Mike Stump11289f42009-09-09 15:08:12 +00001461 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001462 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001463 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001464 buf += "if (limit) {\n\t";
1465 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1466 buf += "do {\n\t\t";
1467 buf += "unsigned long counter = 0;\n\t\t";
1468 buf += "do {\n\t\t\t";
1469 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1470 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1471 buf += elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001472 buf += " = (";
1473 buf += elementTypeAsString;
1474 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001475 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattner9cc55f52008-01-31 19:51:04 +00001476 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001477
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001478 /// __continue_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001479 /// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001480 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001481 /// objects:items count:16]);
1482 /// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001483 /// __break_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001484 /// }
1485 /// else
1486 /// elem = nil;
1487 /// }
Mike Stump11289f42009-09-09 15:08:12 +00001488 ///
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001489 buf = ";\n\t";
1490 buf += "__continue_label_";
1491 buf += utostr(ObjCBcLabelNo.back());
1492 buf += ": ;";
1493 buf += "\n\t\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001494 buf += "} while (counter < limit);\n\t";
1495 buf += "} while (limit = ";
1496 SynthCountByEnumWithState(buf);
1497 buf += ");\n\t";
1498 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001499 buf += " = ((";
1500 buf += elementTypeAsString;
1501 buf += ")0);\n\t";
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001502 buf += "__break_label_";
1503 buf += utostr(ObjCBcLabelNo.back());
1504 buf += ": ;\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001505 buf += "}\n\t";
1506 buf += "else\n\t\t";
1507 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001508 buf += " = ((";
1509 buf += elementTypeAsString;
1510 buf += ")0);\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001511 buf += "}\n";
Mike Stump11289f42009-09-09 15:08:12 +00001512
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001513 // Insert all these *after* the statement body.
Sebastian Redla7b98a72009-04-26 20:35:05 +00001514 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Narofff0ff8792008-07-21 18:26:02 +00001515 if (isa<CompoundStmt>(S->getBody())) {
1516 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1517 InsertText(endBodyLoc, buf.c_str(), buf.size());
1518 } else {
1519 /* Need to treat single statements specially. For example:
1520 *
1521 * for (A *a in b) if (stuff()) break;
1522 * for (A *a in b) xxxyy;
1523 *
1524 * The following code simply scans ahead to the semi to find the actual end.
1525 */
1526 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1527 const char *semiBuf = strchr(stmtBuf, ';');
1528 assert(semiBuf && "Can't find ';'");
1529 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1530 InsertText(endBodyLoc, buf.c_str(), buf.size());
1531 }
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001532 Stmts.pop_back();
1533 ObjCBcLabelNo.pop_back();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001534 return 0;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001535}
1536
Mike Stump11289f42009-09-09 15:08:12 +00001537/// RewriteObjCSynchronizedStmt -
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001538/// This routine rewrites @synchronized(expr) stmt;
1539/// into:
1540/// objc_sync_enter(expr);
1541/// @try stmt @finally { objc_sync_exit(expr); }
1542///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001543Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001544 // Get the start location and compute the semi location.
1545 SourceLocation startLoc = S->getLocStart();
1546 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001547
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001548 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump11289f42009-09-09 15:08:12 +00001549
1550 std::string buf;
Steve Naroffb2fc0522008-08-21 13:03:03 +00001551 buf = "objc_sync_enter((id)";
1552 const char *lparenBuf = startBuf;
1553 while (*lparenBuf != '(') lparenBuf++;
1554 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001555 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1556 // the sync expression is typically a message expression that's already
Steve Naroffad7013b2008-08-19 13:04:19 +00001557 // been rewritten! (which implies the SourceLocation's are invalid).
1558 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001559 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffad7013b2008-08-19 13:04:19 +00001560 while (*endBuf != ')') endBuf--;
1561 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001562 buf = ");\n";
1563 // declare a new scope with two variables, _stack and _rethrow.
1564 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1565 buf += "int buf[18/*32-bit i386*/];\n";
1566 buf += "char *pointers[4];} _stack;\n";
1567 buf += "id volatile _rethrow = 0;\n";
1568 buf += "objc_exception_try_enter(&_stack);\n";
1569 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001570 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001571 startLoc = S->getSynchBody()->getLocEnd();
1572 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001573
Steve Naroffad7013b2008-08-19 13:04:19 +00001574 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001575 SourceLocation lastCurlyLoc = startLoc;
1576 buf = "}\nelse {\n";
1577 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroffd9803712009-04-29 16:37:50 +00001578 buf += "}\n";
1579 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001580 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffec60b432009-12-05 21:43:12 +00001581
1582 std::string syncBuf;
1583 syncBuf += " objc_sync_exit(";
Mike Stump11289f42009-09-09 15:08:12 +00001584 Expr *syncExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00001585 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00001586 S->getSynchExpr(),
Ted Kremenek5a201952009-02-07 01:47:29 +00001587 Context->getObjCIdType(),
1588 SourceLocation(),
1589 SourceLocation());
Ted Kremenek2d470fc2008-09-13 05:16:45 +00001590 std::string syncExprBufS;
1591 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00001592 syncExpr->printPretty(syncExprBuf, *Context, 0,
1593 PrintingPolicy(LangOpts));
Steve Naroffec60b432009-12-05 21:43:12 +00001594 syncBuf += syncExprBuf.str();
1595 syncBuf += ");";
1596
1597 buf += syncBuf;
1598 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001599 buf += "}\n";
1600 buf += "}";
Mike Stump11289f42009-09-09 15:08:12 +00001601
Chris Lattner9cc55f52008-01-31 19:51:04 +00001602 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffec60b432009-12-05 21:43:12 +00001603
1604 bool hasReturns = false;
1605 HasReturnStmts(S->getSynchBody(), hasReturns);
1606 if (hasReturns)
1607 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1608
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001609 return 0;
1610}
1611
Steve Naroffec60b432009-12-05 21:43:12 +00001612void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1613{
Steve Naroff6d6da252008-12-05 17:03:39 +00001614 // Perform a bottom up traversal of all children.
1615 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1616 CI != E; ++CI)
1617 if (*CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001618 WarnAboutReturnGotoStmts(*CI);
Steve Naroff6d6da252008-12-05 17:03:39 +00001619
Steve Naroffec60b432009-12-05 21:43:12 +00001620 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump11289f42009-09-09 15:08:12 +00001621 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff6d6da252008-12-05 17:03:39 +00001622 TryFinallyContainsReturnDiag);
1623 }
1624 return;
1625}
1626
Steve Naroffec60b432009-12-05 21:43:12 +00001627void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1628{
1629 // Perform a bottom up traversal of all children.
1630 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1631 CI != E; ++CI)
1632 if (*CI)
1633 HasReturnStmts(*CI, hasReturns);
1634
1635 if (isa<ReturnStmt>(S))
1636 hasReturns = true;
1637 return;
1638}
1639
1640void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1641 // Perform a bottom up traversal of all children.
1642 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1643 CI != E; ++CI)
1644 if (*CI) {
1645 RewriteTryReturnStmts(*CI);
1646 }
1647 if (isa<ReturnStmt>(S)) {
1648 SourceLocation startLoc = S->getLocStart();
1649 const char *startBuf = SM->getCharacterData(startLoc);
1650
1651 const char *semiBuf = strchr(startBuf, ';');
1652 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1653 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1654
1655 std::string buf;
1656 buf = "{ objc_exception_try_exit(&_stack); return";
1657
1658 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1659 InsertText(onePastSemiLoc, "}", 1);
1660 }
1661 return;
1662}
1663
1664void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1665 // Perform a bottom up traversal of all children.
1666 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1667 CI != E; ++CI)
1668 if (*CI) {
1669 RewriteSyncReturnStmts(*CI, syncExitBuf);
1670 }
1671 if (isa<ReturnStmt>(S)) {
1672 SourceLocation startLoc = S->getLocStart();
1673 const char *startBuf = SM->getCharacterData(startLoc);
1674
1675 const char *semiBuf = strchr(startBuf, ';');
1676 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1677 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1678
1679 std::string buf;
1680 buf = "{ objc_exception_try_exit(&_stack);";
1681 buf += syncExitBuf;
1682 buf += " return";
1683
1684 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1685 InsertText(onePastSemiLoc, "}", 1);
1686 }
1687 return;
1688}
1689
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001690Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001691 // Get the start location and compute the semi location.
1692 SourceLocation startLoc = S->getLocStart();
1693 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001694
Steve Naroffbf478ec2007-11-07 04:08:17 +00001695 assert((*startBuf == '@') && "bogus @try location");
1696
1697 std::string buf;
1698 // declare a new scope with two variables, _stack and _rethrow.
1699 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1700 buf += "int buf[18/*32-bit i386*/];\n";
1701 buf += "char *pointers[4];} _stack;\n";
1702 buf += "id volatile _rethrow = 0;\n";
1703 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff16018582007-11-07 18:43:40 +00001704 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffbf478ec2007-11-07 04:08:17 +00001705
Chris Lattner9cc55f52008-01-31 19:51:04 +00001706 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001707
Steve Naroffbf478ec2007-11-07 04:08:17 +00001708 startLoc = S->getTryBody()->getLocEnd();
1709 startBuf = SM->getCharacterData(startLoc);
1710
1711 assert((*startBuf == '}') && "bogus @try block");
Mike Stump11289f42009-09-09 15:08:12 +00001712
Steve Naroffbf478ec2007-11-07 04:08:17 +00001713 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffce2dca12008-07-16 15:31:30 +00001714 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1715 if (catchList) {
1716 startLoc = startLoc.getFileLocWithOffset(1);
1717 buf = " /* @catch begin */ else {\n";
1718 buf += " id _caught = objc_exception_extract(&_stack);\n";
1719 buf += " objc_exception_try_enter (&_stack);\n";
1720 buf += " if (_setjmp(_stack.buf))\n";
1721 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1722 buf += " else { /* @catch continue */";
Mike Stump11289f42009-09-09 15:08:12 +00001723
Steve Naroffce2dca12008-07-16 15:31:30 +00001724 InsertText(startLoc, buf.c_str(), buf.size());
Steve Narofffac18fe2008-09-09 19:59:12 +00001725 } else { /* no catch list */
1726 buf = "}\nelse {\n";
1727 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1728 buf += "}";
1729 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffce2dca12008-07-16 15:31:30 +00001730 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001731 bool sawIdTypedCatch = false;
1732 Stmt *lastCatchBody = 0;
Steve Naroffbf478ec2007-11-07 04:08:17 +00001733 while (catchList) {
Steve Naroff371b8fb2009-03-03 19:52:17 +00001734 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001735
Mike Stump11289f42009-09-09 15:08:12 +00001736 if (catchList == S->getCatchStmts())
Steve Naroffbf478ec2007-11-07 04:08:17 +00001737 buf = "if ("; // we are generating code for the first catch clause
1738 else
1739 buf = "else if (";
1740 startLoc = catchList->getLocStart();
1741 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001742
Steve Naroffbf478ec2007-11-07 04:08:17 +00001743 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump11289f42009-09-09 15:08:12 +00001744
Steve Naroffbf478ec2007-11-07 04:08:17 +00001745 const char *lParenLoc = strchr(startBuf, '(');
1746
Steve Naroffe6b7ffd2008-02-01 22:08:12 +00001747 if (catchList->hasEllipsis()) {
Steve Naroffedb5bc62008-02-01 20:02:07 +00001748 // Now rewrite the body...
1749 lastCatchBody = catchList->getCatchBody();
Steve Naroffedb5bc62008-02-01 20:02:07 +00001750 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1751 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001752 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1753 "bogus @catch paren location");
Steve Naroffedb5bc62008-02-01 20:02:07 +00001754 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001755
Steve Naroffedb5bc62008-02-01 20:02:07 +00001756 buf += "1) { id _tmp = _caught;";
Daniel Dunbardec484a2009-08-19 19:10:30 +00001757 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff371b8fb2009-03-03 19:52:17 +00001758 } else if (catchDecl) {
1759 QualType t = catchDecl->getType();
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001760 if (t == Context->getObjCIdType()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001761 buf += "1) { ";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001762 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001763 sawIdTypedCatch = true;
Fariborz Jahanian59516092010-01-12 01:22:23 +00001764 } else if (t->isObjCObjectPointerType()) {
1765 QualType InterfaceTy = t->getPointeeType();
1766 const ObjCInterfaceType *cls = // Should be a pointer to a class.
1767 InterfaceTy->getAs<ObjCInterfaceType>();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001768 if (cls) {
Steve Naroff16018582007-11-07 18:43:40 +00001769 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001770 buf += cls->getDecl()->getNameAsString();
Steve Naroff16018582007-11-07 18:43:40 +00001771 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001772 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001773 }
1774 }
1775 // Now rewrite the body...
1776 lastCatchBody = catchList->getCatchBody();
1777 SourceLocation rParenLoc = catchList->getRParenLoc();
1778 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1779 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1780 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1781 assert((*rParenBuf == ')') && "bogus @catch paren location");
1782 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001783
Steve Naroffbf478ec2007-11-07 04:08:17 +00001784 buf = " = _caught;";
Mike Stump11289f42009-09-09 15:08:12 +00001785 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroffbf478ec2007-11-07 04:08:17 +00001786 // declares the @catch parameter).
Chris Lattner9cc55f52008-01-31 19:51:04 +00001787 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff371b8fb2009-03-03 19:52:17 +00001788 } else {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001789 assert(false && "@catch rewrite bug");
Steve Naroffa733c7f2007-11-07 15:32:26 +00001790 }
Steve Naroffedb5bc62008-02-01 20:02:07 +00001791 // make sure all the catch bodies get rewritten!
Steve Naroffbf478ec2007-11-07 04:08:17 +00001792 catchList = catchList->getNextCatchStmt();
1793 }
1794 // Complete the catch list...
1795 if (lastCatchBody) {
1796 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001797 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1798 "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001799
Steve Naroff4adbe312008-09-11 15:29:03 +00001800 // Insert the last (implicit) else clause *before* the right curly brace.
1801 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1802 buf = "} /* last catch end */\n";
1803 buf += "else {\n";
1804 buf += " _rethrow = _caught;\n";
1805 buf += " objc_exception_try_exit(&_stack);\n";
1806 buf += "} } /* @catch end */\n";
1807 if (!S->getFinallyStmt())
1808 buf += "}\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001809 InsertText(bodyLoc, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001810
Steve Naroffbf478ec2007-11-07 04:08:17 +00001811 // Set lastCurlyLoc
1812 lastCurlyLoc = lastCatchBody->getLocEnd();
1813 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001814 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001815 startLoc = finalStmt->getLocStart();
1816 startBuf = SM->getCharacterData(startLoc);
1817 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump11289f42009-09-09 15:08:12 +00001818
Steve Naroffbf478ec2007-11-07 04:08:17 +00001819 buf = "/* @finally */";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001820 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001821
Steve Naroffbf478ec2007-11-07 04:08:17 +00001822 Stmt *body = finalStmt->getFinallyBody();
1823 SourceLocation startLoc = body->getLocStart();
1824 SourceLocation endLoc = body->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001825 assert(*SM->getCharacterData(startLoc) == '{' &&
1826 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001827 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001828 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001829
Steve Naroffbf478ec2007-11-07 04:08:17 +00001830 startLoc = startLoc.getFileLocWithOffset(1);
1831 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001832 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001833 endLoc = endLoc.getFileLocWithOffset(-1);
1834 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001835 InsertText(endLoc, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001836
Steve Naroffbf478ec2007-11-07 04:08:17 +00001837 // Set lastCurlyLoc
1838 lastCurlyLoc = body->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00001839
Steve Naroff6d6da252008-12-05 17:03:39 +00001840 // Now check for any return/continue/go statements within the @try.
Steve Naroffec60b432009-12-05 21:43:12 +00001841 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff4adbe312008-09-11 15:29:03 +00001842 } else { /* no finally clause - make sure we synthesize an implicit one */
1843 buf = "{ /* implicit finally clause */\n";
1844 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1845 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1846 buf += "}";
1847 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffec60b432009-12-05 21:43:12 +00001848
1849 // Now check for any return/continue/go statements within the @try.
1850 // The implicit finally clause won't called if the @try contains any
1851 // jump statements.
1852 bool hasReturns = false;
1853 HasReturnStmts(S->getTryBody(), hasReturns);
1854 if (hasReturns)
1855 RewriteTryReturnStmts(S->getTryBody());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001856 }
1857 // Now emit the final closing curly brace...
1858 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1859 buf = " } /* @try scope end */\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001860 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001861 return 0;
1862}
1863
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001864Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001865 return 0;
1866}
1867
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001868Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001869 return 0;
1870}
1871
Mike Stump11289f42009-09-09 15:08:12 +00001872// This can't be done with ReplaceStmt(S, ThrowExpr), since
1873// the throw expression is typically a message expression that's already
Steve Naroffa733c7f2007-11-07 15:32:26 +00001874// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001875Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroffa733c7f2007-11-07 15:32:26 +00001876 // Get the start location and compute the semi location.
1877 SourceLocation startLoc = S->getLocStart();
1878 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001879
Steve Naroffa733c7f2007-11-07 15:32:26 +00001880 assert((*startBuf == '@') && "bogus @throw location");
1881
1882 std::string buf;
1883 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffc7d2df22008-01-19 00:42:38 +00001884 if (S->getThrowExpr())
1885 buf = "objc_exception_throw(";
1886 else // add an implicit argument
1887 buf = "objc_exception_throw(_caught";
Mike Stump11289f42009-09-09 15:08:12 +00001888
Steve Naroff29788342008-07-25 15:41:30 +00001889 // handle "@ throw" correctly.
1890 const char *wBuf = strchr(startBuf, 'w');
1891 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1892 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001893
Steve Naroffa733c7f2007-11-07 15:32:26 +00001894 const char *semiBuf = strchr(startBuf, ';');
1895 assert((*semiBuf == ';') && "@throw: can't find ';'");
1896 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1897 buf = ");";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001898 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroffa733c7f2007-11-07 15:32:26 +00001899 return 0;
1900}
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001901
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001902Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerc6d91c02007-10-17 22:35:30 +00001903 // Create a new string expression.
1904 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlssond8499822007-10-29 05:01:08 +00001905 std::string StrEncoding;
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00001906 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00001907 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1908 StrEncoding.length(), false,StrType,
1909 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00001910 ReplaceStmt(Exp, Replacement);
Mike Stump11289f42009-09-09 15:08:12 +00001911
Chris Lattner4431a1b2007-11-30 22:53:43 +00001912 // Replace this subexpr in the parent.
Steve Naroff22216db2008-12-04 23:50:32 +00001913 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattner69534692007-10-24 16:57:36 +00001914 return Replacement;
Chris Lattnera7c19fe2007-10-16 22:36:42 +00001915}
1916
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001917Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff2654e182008-12-22 22:16:07 +00001918 if (!SelGetUidFunctionDecl)
1919 SynthSelGetUidFunctionDecl();
Steve Naroffe4f9b232007-11-05 14:50:49 +00001920 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1921 // Create a call to sel_registerName("selName").
1922 llvm::SmallVector<Expr*, 8> SelExprs;
1923 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00001924 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00001925 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00001926 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00001927 false, argType, SourceLocation()));
Steve Naroffe4f9b232007-11-05 14:50:49 +00001928 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1929 &SelExprs[0], SelExprs.size());
Chris Lattner2e0d2602008-01-31 19:37:57 +00001930 ReplaceStmt(Exp, SelExp);
Steve Naroff22216db2008-12-04 23:50:32 +00001931 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffe4f9b232007-11-05 14:50:49 +00001932 return SelExp;
1933}
1934
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001935CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff574440f2007-10-24 22:48:43 +00001936 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001937 // Get the type, we will need to reference it in a couple spots.
Steve Naroff574440f2007-10-24 22:48:43 +00001938 QualType msgSendType = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001939
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001940 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek5a201952009-02-07 01:47:29 +00001941 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001942
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001943 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattner3c799d72007-10-24 17:06:59 +00001944 QualType pToFunc = Context->getPointerType(msgSendType);
Mike Stump11289f42009-09-09 15:08:12 +00001945 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc,
Anders Carlssona2615922009-07-31 00:48:10 +00001946 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00001947 DRE,
Douglas Gregora11693b2008-11-12 17:17:38 +00001948 /*isLvalue=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001949
John McCall9dd450b2009-09-21 23:43:11 +00001950 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00001951
Ted Kremenekd7b4f402009-02-09 20:51:47 +00001952 return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1953 SourceLocation());
Steve Naroff574440f2007-10-24 22:48:43 +00001954}
1955
Steve Naroff50d42052007-11-01 13:24:47 +00001956static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1957 const char *&startRef, const char *&endRef) {
1958 while (startBuf < endBuf) {
1959 if (*startBuf == '<')
1960 startRef = startBuf; // mark the start.
1961 if (*startBuf == '>') {
Steve Naroff1b232132007-11-09 12:50:28 +00001962 if (startRef && *startRef == '<') {
1963 endRef = startBuf; // mark the end.
1964 return true;
1965 }
1966 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00001967 }
1968 startBuf++;
1969 }
1970 return false;
1971}
1972
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001973static void scanToNextArgument(const char *&argRef) {
1974 int angle = 0;
1975 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1976 if (*argRef == '<')
1977 angle++;
1978 else if (*argRef == '>')
1979 angle--;
1980 argRef++;
1981 }
1982 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1983}
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00001984
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001985bool RewriteObjC::needToScanForQualifiers(QualType T) {
Steve Naroffc277ad12009-07-18 15:33:26 +00001986 return T->isObjCQualifiedIdType() || T->isObjCQualifiedInterfaceType();
Steve Naroff50d42052007-11-01 13:24:47 +00001987}
1988
Steve Naroff873bd842008-07-29 18:15:38 +00001989void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1990 QualType Type = E->getType();
1991 if (needToScanForQualifiers(Type)) {
Steve Naroffdbfc6932008-11-19 21:15:47 +00001992 SourceLocation Loc, EndLoc;
Mike Stump11289f42009-09-09 15:08:12 +00001993
Steve Naroffdbfc6932008-11-19 21:15:47 +00001994 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1995 Loc = ECE->getLParenLoc();
1996 EndLoc = ECE->getRParenLoc();
1997 } else {
1998 Loc = E->getLocStart();
1999 EndLoc = E->getLocEnd();
2000 }
2001 // This will defend against trying to rewrite synthesized expressions.
2002 if (Loc.isInvalid() || EndLoc.isInvalid())
2003 return;
2004
Steve Naroff873bd842008-07-29 18:15:38 +00002005 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffdbfc6932008-11-19 21:15:47 +00002006 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff873bd842008-07-29 18:15:38 +00002007 const char *startRef = 0, *endRef = 0;
2008 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2009 // Get the locations of the startRef, endRef.
2010 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2011 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2012 // Comment out the protocol references.
2013 InsertText(LessLoc, "/*", 2);
2014 InsertText(GreaterLoc, "*/", 2);
2015 }
2016 }
2017}
2018
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002019void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002020 SourceLocation Loc;
2021 QualType Type;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002022 const FunctionProtoType *proto = 0;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002023 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2024 Loc = VD->getLocation();
2025 Type = VD->getType();
2026 }
2027 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2028 Loc = FD->getLocation();
2029 // Check for ObjC 'id' and class types that have been adorned with protocol
2030 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall9dd450b2009-09-21 23:43:11 +00002031 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002032 assert(funcType && "missing function type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002033 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002034 if (!proto)
2035 return;
2036 Type = proto->getResultType();
2037 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00002038 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2039 Loc = FD->getLocation();
2040 Type = FD->getType();
2041 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002042 else
2043 return;
Mike Stump11289f42009-09-09 15:08:12 +00002044
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002045 if (needToScanForQualifiers(Type)) {
Steve Naroff50d42052007-11-01 13:24:47 +00002046 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002047
Steve Naroff50d42052007-11-01 13:24:47 +00002048 const char *endBuf = SM->getCharacterData(Loc);
2049 const char *startBuf = endBuf;
Steve Naroff930e0992008-05-31 05:02:17 +00002050 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroff50d42052007-11-01 13:24:47 +00002051 startBuf--; // scan backward (from the decl location) for return type.
2052 const char *startRef = 0, *endRef = 0;
2053 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2054 // Get the locations of the startRef, endRef.
2055 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2056 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2057 // Comment out the protocol references.
Chris Lattner1780a852008-01-31 19:42:41 +00002058 InsertText(LessLoc, "/*", 2);
2059 InsertText(GreaterLoc, "*/", 2);
Steve Naroff37e011c2007-10-31 04:38:33 +00002060 }
2061 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002062 if (!proto)
2063 return; // most likely, was a variable
Steve Naroff50d42052007-11-01 13:24:47 +00002064 // Now check arguments.
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002065 const char *startBuf = SM->getCharacterData(Loc);
2066 const char *startFuncBuf = startBuf;
Steve Naroff50d42052007-11-01 13:24:47 +00002067 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2068 if (needToScanForQualifiers(proto->getArgType(i))) {
2069 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002070
Steve Naroff50d42052007-11-01 13:24:47 +00002071 const char *endBuf = startBuf;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002072 // scan forward (from the decl location) for argument types.
2073 scanToNextArgument(endBuf);
Steve Naroff50d42052007-11-01 13:24:47 +00002074 const char *startRef = 0, *endRef = 0;
2075 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2076 // Get the locations of the startRef, endRef.
Mike Stump11289f42009-09-09 15:08:12 +00002077 SourceLocation LessLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002078 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump11289f42009-09-09 15:08:12 +00002079 SourceLocation GreaterLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002080 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002081 // Comment out the protocol references.
Chris Lattner1780a852008-01-31 19:42:41 +00002082 InsertText(LessLoc, "/*", 2);
2083 InsertText(GreaterLoc, "*/", 2);
Steve Naroff50d42052007-11-01 13:24:47 +00002084 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002085 startBuf = ++endBuf;
2086 }
2087 else {
Steve Naroffc884aa82008-08-06 15:58:23 +00002088 // If the function name is derived from a macro expansion, then the
2089 // argument buffer will not follow the name. Need to speak with Chris.
2090 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002091 startBuf++; // scan forward (from the decl location) for argument types.
2092 startBuf++;
2093 }
Steve Naroff50d42052007-11-01 13:24:47 +00002094 }
Steve Naroff37e011c2007-10-31 04:38:33 +00002095}
2096
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002097// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002098void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002099 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2100 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002101 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002102 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002103 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002104 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002105 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002106 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002107 SelGetUidIdent, getFuncType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002108 FunctionDecl::Extern, false);
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002109}
2110
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002111void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002112 // declared in <objc/objc.h>
Douglas Gregor1e21c192009-01-09 01:47:02 +00002113 if (FD->getIdentifier() &&
2114 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002115 SelGetUidFunctionDecl = FD;
Steve Naroff37e011c2007-10-31 04:38:33 +00002116 return;
2117 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002118 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002119}
2120
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002121void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2122 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2123 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2124 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2125 if (!proto)
2126 return;
2127 QualType Type = proto->getResultType();
2128 std::string FdStr = Type.getAsString();
2129 FdStr += " ";
2130 FdStr += FD->getNameAsCString();
2131 FdStr += "(";
2132 unsigned numArgs = proto->getNumArgs();
2133 for (unsigned i = 0; i < numArgs; i++) {
2134 QualType ArgType = proto->getArgType(i);
2135 FdStr += ArgType.getAsString();
2136
2137 if (i+1 < numArgs)
2138 FdStr += ", ";
2139 }
2140 FdStr += ");\n";
2141 InsertText(FunLocStart, FdStr.c_str(), FdStr.size());
2142 CurFunctionDeclToDeclareForBlock = 0;
2143}
2144
Steve Naroff17978c42008-03-11 17:37:02 +00002145// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002146void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroff17978c42008-03-11 17:37:02 +00002147 if (SuperContructorFunctionDecl)
2148 return;
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002149 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroff17978c42008-03-11 17:37:02 +00002150 llvm::SmallVector<QualType, 16> ArgTys;
2151 QualType argT = Context->getObjCIdType();
2152 assert(!argT.isNull() && "Can't find 'id' type");
2153 ArgTys.push_back(argT);
2154 ArgTys.push_back(argT);
2155 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2156 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002157 false, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002158 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002159 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002160 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002161 FunctionDecl::Extern, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002162}
2163
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002164// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002165void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002166 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2167 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002168 QualType argT = Context->getObjCIdType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002169 assert(!argT.isNull() && "Can't find 'id' type");
2170 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002171 argT = Context->getObjCSelType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002172 assert(!argT.isNull() && "Can't find 'SEL' type");
2173 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002174 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002175 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002176 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002177 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002178 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002179 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002180 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002181}
2182
Steve Naroff7fa2f042007-11-15 10:28:18 +00002183// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002184void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002185 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2186 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002187 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002188 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002189 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002190 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2191 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2192 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002193 argT = Context->getObjCSelType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002194 assert(!argT.isNull() && "Can't find 'SEL' type");
2195 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002196 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff7fa2f042007-11-15 10:28:18 +00002197 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002198 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002199 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002200 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002201 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002202 FunctionDecl::Extern, false);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002203}
2204
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002205// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002206void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002207 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2208 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002209 QualType argT = Context->getObjCIdType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002210 assert(!argT.isNull() && "Can't find 'id' type");
2211 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002212 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002213 assert(!argT.isNull() && "Can't find 'SEL' type");
2214 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002215 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002216 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002217 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002218 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002219 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002220 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002221 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002222}
2223
Mike Stump11289f42009-09-09 15:08:12 +00002224// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002225// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002226void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump11289f42009-09-09 15:08:12 +00002227 IdentifierInfo *msgSendIdent =
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002228 &Context->Idents.get("objc_msgSendSuper_stret");
2229 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002230 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002231 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002232 &Context->Idents.get("objc_super"));
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002233 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2234 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2235 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002236 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002237 assert(!argT.isNull() && "Can't find 'SEL' type");
2238 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002239 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002240 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002241 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002242 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002243 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002244 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002245 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002246}
2247
Steve Naroff2e4e3852008-05-08 22:02:18 +00002248// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002249void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002250 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2251 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002252 QualType argT = Context->getObjCIdType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002253 assert(!argT.isNull() && "Can't find 'id' type");
2254 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002255 argT = Context->getObjCSelType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002256 assert(!argT.isNull() && "Can't find 'SEL' type");
2257 ArgTys.push_back(argT);
Steve Naroff2e4e3852008-05-08 22:02:18 +00002258 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002259 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002260 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002261 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002262 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002263 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002264 FunctionDecl::Extern, false);
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002265}
2266
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002267// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002268void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002269 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2270 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002271 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002272 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002273 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002274 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002275 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002276 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002277 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002278 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002279}
2280
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002281// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002282void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002283 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2284 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002285 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002286 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002287 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002288 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002289 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002290 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002291 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002292 FunctionDecl::Extern, false);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002293}
2294
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002295Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffce8e8862008-03-15 00:55:56 +00002296 QualType strType = getConstantStringStructType();
2297
2298 std::string S = "__NSConstantStringImpl_";
Steve Naroffa6141f02008-05-31 03:35:42 +00002299
2300 std::string tmpName = InFileName;
2301 unsigned i;
2302 for (i=0; i < tmpName.length(); i++) {
2303 char c = tmpName.at(i);
2304 // replace any non alphanumeric characters with '_'.
2305 if (!isalpha(c) && (c < '0' || c > '9'))
2306 tmpName[i] = '_';
2307 }
2308 S += tmpName;
2309 S += "_";
Steve Naroffce8e8862008-03-15 00:55:56 +00002310 S += utostr(NumObjCStringLiterals++);
2311
Steve Naroff00a31762008-03-27 22:29:16 +00002312 Preamble += "static __NSConstantStringImpl " + S;
2313 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2314 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffce8e8862008-03-15 00:55:56 +00002315 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek2d470fc2008-09-13 05:16:45 +00002316 std::string prettyBufS;
2317 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00002318 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2319 PrintingPolicy(LangOpts));
Steve Naroff00a31762008-03-27 22:29:16 +00002320 Preamble += prettyBuf.str();
2321 Preamble += ",";
Steve Naroff94ed6dc2009-12-06 01:48:44 +00002322 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002323
2324 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2325 &Context->Idents.get(S.c_str()), strType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002326 VarDecl::Static);
Ted Kremenek5a201952009-02-07 01:47:29 +00002327 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2328 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002329 Context->getPointerType(DRE->getType()),
Steve Naroffce8e8862008-03-15 00:55:56 +00002330 SourceLocation());
Steve Naroff265a6b92007-11-08 14:30:50 +00002331 // cast to NSConstantString *
Mike Stump11289f42009-09-09 15:08:12 +00002332 CastExpr *cast = new (Context) CStyleCastExpr(Exp->getType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002333 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002334 Unop, Exp->getType(),
2335 SourceLocation(),
Anders Carlssona2615922009-07-31 00:48:10 +00002336 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002337 ReplaceStmt(Exp, cast);
Steve Naroff22216db2008-12-04 23:50:32 +00002338 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff265a6b92007-11-08 14:30:50 +00002339 return cast;
Steve Naroffa397efd2007-11-03 11:27:19 +00002340}
2341
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002342ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002343 // check if we are sending a message to 'super'
Douglas Gregorffca3a22009-01-09 17:18:27 +00002344 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002345
Douglas Gregor8ea1f532008-11-04 14:56:14 +00002346 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
Mike Stump11289f42009-09-09 15:08:12 +00002347 const ObjCObjectPointerType *OPT =
John McCall9dd450b2009-09-21 23:43:11 +00002348 Super->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00002349 assert(OPT);
2350 const ObjCInterfaceType *IT = OPT->getInterfaceType();
Chris Lattnera9b3cae2008-06-21 18:04:54 +00002351 return IT->getDecl();
2352 }
2353 return 0;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002354}
2355
2356// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002357QualType RewriteObjC::getSuperStructType() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002358 if (!SuperStructDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002359 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002360 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002361 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002362 QualType FieldTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002363
Steve Naroff7fa2f042007-11-15 10:28:18 +00002364 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002365 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002366 // struct objc_class *super;
Mike Stump11289f42009-09-09 15:08:12 +00002367 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor91f84212008-12-11 16:49:14 +00002368
Steve Naroff7fa2f042007-11-15 10:28:18 +00002369 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002370 for (unsigned i = 0; i < 2; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002371 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2372 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002373 FieldTypes[i], 0,
2374 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002375 /*Mutable=*/false));
Douglas Gregor91f84212008-12-11 16:49:14 +00002376 }
Mike Stump11289f42009-09-09 15:08:12 +00002377
Douglas Gregor91f84212008-12-11 16:49:14 +00002378 SuperStructDecl->completeDefinition(*Context);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002379 }
2380 return Context->getTagDeclType(SuperStructDecl);
2381}
2382
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002383QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffce8e8862008-03-15 00:55:56 +00002384 if (!ConstantStringDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002385 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002386 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002387 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffce8e8862008-03-15 00:55:56 +00002388 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002389
Steve Naroffce8e8862008-03-15 00:55:56 +00002390 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002391 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffce8e8862008-03-15 00:55:56 +00002392 // int flags;
Mike Stump11289f42009-09-09 15:08:12 +00002393 FieldTypes[1] = Context->IntTy;
Steve Naroffce8e8862008-03-15 00:55:56 +00002394 // char *str;
Mike Stump11289f42009-09-09 15:08:12 +00002395 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffce8e8862008-03-15 00:55:56 +00002396 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002397 FieldTypes[3] = Context->LongTy;
Douglas Gregor91f84212008-12-11 16:49:14 +00002398
Steve Naroffce8e8862008-03-15 00:55:56 +00002399 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002400 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002401 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2402 ConstantStringDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002403 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002404 FieldTypes[i], 0,
Douglas Gregor91f84212008-12-11 16:49:14 +00002405 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002406 /*Mutable=*/true));
Douglas Gregor91f84212008-12-11 16:49:14 +00002407 }
2408
2409 ConstantStringDecl->completeDefinition(*Context);
Steve Naroffce8e8862008-03-15 00:55:56 +00002410 }
2411 return Context->getTagDeclType(ConstantStringDecl);
2412}
2413
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002414Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002415 if (!SelGetUidFunctionDecl)
2416 SynthSelGetUidFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002417 if (!MsgSendFunctionDecl)
2418 SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002419 if (!MsgSendSuperFunctionDecl)
2420 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002421 if (!MsgSendStretFunctionDecl)
2422 SynthMsgSendStretFunctionDecl();
2423 if (!MsgSendSuperStretFunctionDecl)
2424 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002425 if (!MsgSendFpretFunctionDecl)
2426 SynthMsgSendFpretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002427 if (!GetClassFunctionDecl)
2428 SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002429 if (!GetMetaClassFunctionDecl)
2430 SynthGetMetaClassFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002431
Steve Naroff7fa2f042007-11-15 10:28:18 +00002432 // default to objc_msgSend().
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002433 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2434 // May need to use objc_msgSend_stret() as well.
2435 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroffd9803712009-04-29 16:37:50 +00002436 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2437 QualType resultType = mDecl->getResultType();
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002438 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002439 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002440 else if (resultType->isRealFloatingType())
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002441 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002442 }
Mike Stump11289f42009-09-09 15:08:12 +00002443
Steve Naroff574440f2007-10-24 22:48:43 +00002444 // Synthesize a call to objc_msgSend().
2445 llvm::SmallVector<Expr*, 8> MsgExprs;
2446 IdentifierInfo *clsName = Exp->getClassName();
Mike Stump11289f42009-09-09 15:08:12 +00002447
Steve Naroff574440f2007-10-24 22:48:43 +00002448 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2449 if (clsName) { // class message.
Steve Naroff6c79f972008-07-24 19:44:33 +00002450 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2451 // the 'super' idiom within a class method.
Daniel Dunbar07d07852009-10-18 21:17:35 +00002452 if (clsName->getName() == "super") {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002453 MsgSendFlavor = MsgSendSuperFunctionDecl;
2454 if (MsgSendStretFlavor)
2455 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2456 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002457
2458 ObjCInterfaceDecl *SuperDecl =
Steve Naroff677ab3a2008-10-27 17:20:55 +00002459 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002460
2461 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002462
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002463 // set the receiver to self, the first argument to all methods.
Steve Naroffd9803712009-04-29 16:37:50 +00002464 InitExprs.push_back(
Mike Stump11289f42009-09-09 15:08:12 +00002465 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002466 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002467 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroffd9803712009-04-29 16:37:50 +00002468 Context->getObjCIdType(),
2469 SourceLocation()),
2470 Context->getObjCIdType(),
2471 SourceLocation(), SourceLocation())); // set the 'receiver'.
2472
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002473 llvm::SmallVector<Expr*, 8> ClsExprs;
2474 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002475 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002476 SuperDecl->getIdentifier()->getNameStart(),
2477 SuperDecl->getIdentifier()->getLength(),
2478 false, argType, SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002479 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002480 &ClsExprs[0],
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002481 ClsExprs.size());
2482 // To turn off a warning, type-cast to 'id'
Douglas Gregore200adc2008-10-27 19:41:14 +00002483 InitExprs.push_back( // set 'super class', using objc_getClass().
Mike Stump11289f42009-09-09 15:08:12 +00002484 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002485 CastExpr::CK_Unknown,
Douglas Gregore200adc2008-10-27 19:41:14 +00002486 Cls, Context->getObjCIdType(),
Mike Stump11289f42009-09-09 15:08:12 +00002487 SourceLocation(), SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002488 // struct objc_super
2489 QualType superType = getSuperStructType();
Steve Naroff0b844f02008-03-11 18:14:26 +00002490 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002491
Steve Naroff0b844f02008-03-11 18:14:26 +00002492 if (LangOpts.Microsoft) {
2493 SynthSuperContructorFunctionDecl();
2494 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002495 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff0b844f02008-03-11 18:14:26 +00002496 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002497 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002498 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002499 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002500 // The code for super is a little tricky to prevent collision with
2501 // the structure definition in the header. The rewriter has it's own
2502 // internal definition (__rw_objc_super) that is uses. This is why
2503 // we need the cast below. For example:
2504 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2505 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002506 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002507 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002508 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002509 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
2510 CastExpr::CK_Unknown, SuperRep,
Anders Carlssona2615922009-07-31 00:48:10 +00002511 Context->getPointerType(superType),
Mike Stump11289f42009-09-09 15:08:12 +00002512 SourceLocation(), SourceLocation());
2513 } else {
Steve Naroff0b844f02008-03-11 18:14:26 +00002514 // (struct objc_super) { <exprs from above> }
Mike Stump11289f42009-09-09 15:08:12 +00002515 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2516 &InitExprs[0], InitExprs.size(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002517 SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00002518 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE,
Chris Lattner07d754a2008-10-26 23:43:26 +00002519 false);
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002520 // struct objc_super *
Ted Kremenek5a201952009-02-07 01:47:29 +00002521 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002522 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002523 SourceLocation());
Steve Naroff0b844f02008-03-11 18:14:26 +00002524 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002525 MsgExprs.push_back(SuperRep);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002526 } else {
2527 llvm::SmallVector<Expr*, 8> ClsExprs;
2528 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002529 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002530 clsName->getNameStart(),
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002531 clsName->getLength(),
2532 false, argType,
2533 SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002534 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002535 &ClsExprs[0],
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002536 ClsExprs.size());
2537 MsgExprs.push_back(Cls);
2538 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002539 } else { // instance message.
2540 Expr *recExpr = Exp->getReceiver();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002541
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002542 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002543 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002544 if (MsgSendStretFlavor)
2545 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002546 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002547
Steve Naroff7fa2f042007-11-15 10:28:18 +00002548 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002549
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002550 InitExprs.push_back(
Mike Stump11289f42009-09-09 15:08:12 +00002551 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002552 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002553 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff97adf602008-07-16 22:35:27 +00002554 Context->getObjCIdType(),
Douglas Gregore200adc2008-10-27 19:41:14 +00002555 SourceLocation()),
2556 Context->getObjCIdType(),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002557 SourceLocation(), SourceLocation())); // set the 'receiver'.
Mike Stump11289f42009-09-09 15:08:12 +00002558
Steve Naroff7fa2f042007-11-15 10:28:18 +00002559 llvm::SmallVector<Expr*, 8> ClsExprs;
2560 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002561 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002562 SuperDecl->getIdentifier()->getNameStart(),
2563 SuperDecl->getIdentifier()->getLength(),
2564 false, argType, SourceLocation()));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002565 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002566 &ClsExprs[0],
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002567 ClsExprs.size());
Fariborz Jahaniand5db92b2007-12-05 17:29:46 +00002568 // To turn off a warning, type-cast to 'id'
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002569 InitExprs.push_back(
Douglas Gregore200adc2008-10-27 19:41:14 +00002570 // set 'super class', using objc_getClass().
Mike Stump11289f42009-09-09 15:08:12 +00002571 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002572 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002573 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002574 // struct objc_super
2575 QualType superType = getSuperStructType();
Steve Naroff17978c42008-03-11 17:37:02 +00002576 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002577
Steve Naroff17978c42008-03-11 17:37:02 +00002578 if (LangOpts.Microsoft) {
2579 SynthSuperContructorFunctionDecl();
2580 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002581 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff17978c42008-03-11 17:37:02 +00002582 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002583 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002584 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002585 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002586 // The code for super is a little tricky to prevent collision with
2587 // the structure definition in the header. The rewriter has it's own
2588 // internal definition (__rw_objc_super) that is uses. This is why
2589 // we need the cast below. For example:
2590 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2591 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002592 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002593 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002594 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002595 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Anders Carlssona2615922009-07-31 00:48:10 +00002596 CastExpr::CK_Unknown,
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002597 SuperRep, Context->getPointerType(superType),
Mike Stump11289f42009-09-09 15:08:12 +00002598 SourceLocation(), SourceLocation());
Steve Naroff17978c42008-03-11 17:37:02 +00002599 } else {
2600 // (struct objc_super) { <exprs from above> }
Mike Stump11289f42009-09-09 15:08:12 +00002601 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2602 &InitExprs[0], InitExprs.size(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002603 SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00002604 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002605 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002606 MsgExprs.push_back(SuperRep);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002607 } else {
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002608 // Remove all type-casts because it may contain objc-style types; e.g.
2609 // Foo<Proto> *.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002610 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002611 recExpr = CE->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002612 recExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002613 CastExpr::CK_Unknown, recExpr,
Mike Stump11289f42009-09-09 15:08:12 +00002614 Context->getObjCIdType(),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002615 SourceLocation(), SourceLocation());
Steve Naroff7fa2f042007-11-15 10:28:18 +00002616 MsgExprs.push_back(recExpr);
2617 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002618 }
Steve Naroffa397efd2007-11-03 11:27:19 +00002619 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff574440f2007-10-24 22:48:43 +00002620 llvm::SmallVector<Expr*, 8> SelExprs;
2621 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002622 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002623 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002624 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002625 false, argType, SourceLocation()));
Steve Naroff574440f2007-10-24 22:48:43 +00002626 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2627 &SelExprs[0], SelExprs.size());
2628 MsgExprs.push_back(SelExp);
Mike Stump11289f42009-09-09 15:08:12 +00002629
Steve Naroff574440f2007-10-24 22:48:43 +00002630 // Now push any user supplied arguments.
2631 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroffe7f18192007-11-14 23:54:14 +00002632 Expr *userExpr = Exp->getArg(i);
Steve Narofff60782b2007-11-15 02:58:25 +00002633 // Make all implicit casts explicit...ICE comes in handy:-)
2634 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2635 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregore200adc2008-10-27 19:41:14 +00002636 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002637 ? Context->getObjCIdType()
Douglas Gregore200adc2008-10-27 19:41:14 +00002638 : ICE->getType();
Anders Carlssona2615922009-07-31 00:48:10 +00002639 userExpr = new (Context) CStyleCastExpr(type, CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002640 userExpr, type, SourceLocation(),
Anders Carlssona2615922009-07-31 00:48:10 +00002641 SourceLocation());
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002642 }
2643 // Make id<P...> cast into an 'id' cast.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002644 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002645 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregorf19b2312008-10-28 15:36:24 +00002646 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002647 userExpr = CE->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002648 userExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002649 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002650 userExpr, Context->getObjCIdType(),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002651 SourceLocation(), SourceLocation());
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002652 }
Mike Stump11289f42009-09-09 15:08:12 +00002653 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002654 MsgExprs.push_back(userExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002655 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2656 // out the argument in the original expression (since we aren't deleting
2657 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2658 //Exp->setArg(i, 0);
Steve Naroff574440f2007-10-24 22:48:43 +00002659 }
Steve Narofff36987c2007-11-04 22:37:50 +00002660 // Generate the funky cast.
2661 CastExpr *cast;
2662 llvm::SmallVector<QualType, 8> ArgTypes;
2663 QualType returnType;
Mike Stump11289f42009-09-09 15:08:12 +00002664
Steve Narofff36987c2007-11-04 22:37:50 +00002665 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff44864e42007-11-15 10:43:57 +00002666 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2667 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2668 else
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002669 ArgTypes.push_back(Context->getObjCIdType());
2670 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattnera4997152009-02-20 18:43:26 +00002671 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Narofff36987c2007-11-04 22:37:50 +00002672 // Push any user argument types.
Chris Lattnera4997152009-02-20 18:43:26 +00002673 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2674 E = OMD->param_end(); PI != E; ++PI) {
2675 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump11289f42009-09-09 15:08:12 +00002676 ? Context->getObjCIdType()
Chris Lattnera4997152009-02-20 18:43:26 +00002677 : (*PI)->getType();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002678 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00002679 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002680 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002681 t = Context->getPointerType(BPT->getPointeeType());
2682 }
Steve Naroff98eb8d12007-11-05 14:36:37 +00002683 ArgTypes.push_back(t);
2684 }
Chris Lattnera4997152009-02-20 18:43:26 +00002685 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2686 ? Context->getObjCIdType() : OMD->getResultType();
Steve Narofff36987c2007-11-04 22:37:50 +00002687 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002688 returnType = Context->getObjCIdType();
Steve Narofff36987c2007-11-04 22:37:50 +00002689 }
2690 // Get the type, we will need to reference it in a couple spots.
Steve Naroff7fa2f042007-11-15 10:28:18 +00002691 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002692
Steve Narofff36987c2007-11-04 22:37:50 +00002693 // Create a reference to the objc_msgSend() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002694 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002695 SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002696
Mike Stump11289f42009-09-09 15:08:12 +00002697 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Narofff36987c2007-11-04 22:37:50 +00002698 // If we don't do this cast, we get the following bizarre warning/note:
2699 // xx.m:13: warning: function called through a non-compatible type
2700 // xx.m:13: note: if this code is reached, the program will abort
Mike Stump11289f42009-09-09 15:08:12 +00002701 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy),
2702 CastExpr::CK_Unknown, DRE,
Douglas Gregore200adc2008-10-27 19:41:14 +00002703 Context->getPointerType(Context->VoidTy),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002704 SourceLocation(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002705
Steve Narofff36987c2007-11-04 22:37:50 +00002706 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002707 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002708 &ArgTypes[0], ArgTypes.size(),
Steve Naroff327f0f42008-03-18 02:02:04 +00002709 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002710 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Narofff36987c2007-11-04 22:37:50 +00002711 castType = Context->getPointerType(castType);
Mike Stump11289f42009-09-09 15:08:12 +00002712 cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown, cast,
2713 castType, SourceLocation(),
Anders Carlssona2615922009-07-31 00:48:10 +00002714 SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002715
2716 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002717 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002718
John McCall9dd450b2009-09-21 23:43:11 +00002719 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002720 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002721 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002722 FT->getResultType(), SourceLocation());
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002723 Stmt *ReplacingStmt = CE;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002724 if (MsgSendStretFlavor) {
2725 // We have the method which returns a struct/union. Must also generate
2726 // call to objc_msgSend_stret and hang both varieties on a conditional
2727 // expression which dictate which one to envoke depending on size of
2728 // method's return type.
Mike Stump11289f42009-09-09 15:08:12 +00002729
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002730 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002731 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002732 SourceLocation());
2733 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Mike Stump11289f42009-09-09 15:08:12 +00002734 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy),
2735 CastExpr::CK_Unknown, STDRE,
Douglas Gregore200adc2008-10-27 19:41:14 +00002736 Context->getPointerType(Context->VoidTy),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002737 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002738 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002739 castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002740 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002741 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002742 castType = Context->getPointerType(castType);
Anders Carlssona2615922009-07-31 00:48:10 +00002743 cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown,
2744 cast, castType, SourceLocation(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002745
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002746 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002747 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002748
John McCall9dd450b2009-09-21 23:43:11 +00002749 FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002750 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002751 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002752 FT->getResultType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002753
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002754 // Build sizeof(returnType)
Mike Stump11289f42009-09-09 15:08:12 +00002755 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCallbcd03502009-12-07 02:54:59 +00002756 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl6f282892008-11-11 17:56:53 +00002757 Context->getSizeType(),
2758 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002759 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2760 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2761 // For X86 it is more complicated and some kind of target specific routine
2762 // is needed to decide what to do.
Mike Stump11289f42009-09-09 15:08:12 +00002763 unsigned IntSize =
Chris Lattner37e05872008-03-05 18:54:05 +00002764 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Mike Stump11289f42009-09-09 15:08:12 +00002765 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002766 Context->IntTy,
2767 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002768 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
2769 BinaryOperator::LE,
2770 Context->IntTy,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002771 SourceLocation());
2772 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump11289f42009-09-09 15:08:12 +00002773 ConditionalOperator *CondExpr =
Douglas Gregor7e112b02009-08-26 14:37:04 +00002774 new (Context) ConditionalOperator(lessThanExpr,
2775 SourceLocation(), CE,
2776 SourceLocation(), STCE, returnType);
Ted Kremenek5a201952009-02-07 01:47:29 +00002777 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002778 }
Mike Stump11289f42009-09-09 15:08:12 +00002779 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002780 return ReplacingStmt;
2781}
2782
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002783Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002784 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Mike Stump11289f42009-09-09 15:08:12 +00002785
Steve Naroff574440f2007-10-24 22:48:43 +00002786 // Now do the actual rewrite.
Chris Lattner2e0d2602008-01-31 19:37:57 +00002787 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00002788
2789 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002790 return ReplacingStmt;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002791}
2792
Steve Naroffd9803712009-04-29 16:37:50 +00002793// typedef struct objc_object Protocol;
2794QualType RewriteObjC::getProtocolType() {
2795 if (!ProtocolTypeDecl) {
John McCallbcd03502009-12-07 02:54:59 +00002796 TypeSourceInfo *TInfo
2797 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroffd9803712009-04-29 16:37:50 +00002798 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002799 SourceLocation(),
Steve Naroffd9803712009-04-29 16:37:50 +00002800 &Context->Idents.get("Protocol"),
John McCallbcd03502009-12-07 02:54:59 +00002801 TInfo);
Steve Naroffd9803712009-04-29 16:37:50 +00002802 }
2803 return Context->getTypeDeclType(ProtocolTypeDecl);
2804}
2805
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00002806/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroffd9803712009-04-29 16:37:50 +00002807/// a synthesized/forward data reference (to the protocol's metadata).
2808/// The forward references (and metadata) are generated in
2809/// RewriteObjC::HandleTranslationUnit().
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002810Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroffd9803712009-04-29 16:37:50 +00002811 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
2812 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump11289f42009-09-09 15:08:12 +00002813 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregored6c7442009-11-23 11:41:28 +00002814 ID, getProtocolType(), 0, VarDecl::Extern);
Steve Naroffd9803712009-04-29 16:37:50 +00002815 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
2816 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
2817 Context->getPointerType(DRE->getType()),
2818 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002819 CastExpr *castExpr = new (Context) CStyleCastExpr(DerefExpr->getType(),
2820 CastExpr::CK_Unknown,
2821 DerefExpr, DerefExpr->getType(),
Steve Naroffd9803712009-04-29 16:37:50 +00002822 SourceLocation(), SourceLocation());
2823 ReplaceStmt(Exp, castExpr);
2824 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump11289f42009-09-09 15:08:12 +00002825 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00002826 return castExpr;
Mike Stump11289f42009-09-09 15:08:12 +00002827
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00002828}
2829
Mike Stump11289f42009-09-09 15:08:12 +00002830bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002831 const char *endBuf) {
2832 while (startBuf < endBuf) {
2833 if (*startBuf == '#') {
2834 // Skip whitespace.
2835 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2836 ;
2837 if (!strncmp(startBuf, "if", strlen("if")) ||
2838 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2839 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2840 !strncmp(startBuf, "define", strlen("define")) ||
2841 !strncmp(startBuf, "undef", strlen("undef")) ||
2842 !strncmp(startBuf, "else", strlen("else")) ||
2843 !strncmp(startBuf, "elif", strlen("elif")) ||
2844 !strncmp(startBuf, "endif", strlen("endif")) ||
2845 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2846 !strncmp(startBuf, "include", strlen("include")) ||
2847 !strncmp(startBuf, "import", strlen("import")) ||
2848 !strncmp(startBuf, "include_next", strlen("include_next")))
2849 return true;
2850 }
2851 startBuf++;
2852 }
2853 return false;
2854}
2855
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002856/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002857/// an objective-c class with ivars.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002858void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002859 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002860 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Mike Stump11289f42009-09-09 15:08:12 +00002861 assert(CDecl->getNameAsCString() &&
Douglas Gregor77324f32008-11-17 14:58:09 +00002862 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00002863 // Do not synthesize more than once.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002864 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00002865 return;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002866 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattner8d1c04f2008-03-16 21:08:55 +00002867 int NumIvars = CDecl->ivar_size();
Steve Naroffdde78982007-11-14 19:25:57 +00002868 SourceLocation LocStart = CDecl->getLocStart();
2869 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00002870
Steve Naroffdde78982007-11-14 19:25:57 +00002871 const char *startBuf = SM->getCharacterData(LocStart);
2872 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00002873
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002874 // If no ivars and no root or if its root, directly or indirectly,
2875 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattner8d1c04f2008-03-16 21:08:55 +00002876 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2877 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner184e65d2009-04-14 23:22:57 +00002878 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Chris Lattner9cc55f52008-01-31 19:51:04 +00002879 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002880 return;
2881 }
Mike Stump11289f42009-09-09 15:08:12 +00002882
2883 // FIXME: This has potential of causing problem. If
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002884 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002885 Result += "\nstruct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002886 Result += CDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00002887 if (LangOpts.Microsoft)
2888 Result += "_IMPL";
Steve Naroffdc5b6b22008-03-12 00:25:36 +00002889
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002890 if (NumIvars > 0) {
Steve Naroffdde78982007-11-14 19:25:57 +00002891 const char *cursor = strchr(startBuf, '{');
Mike Stump11289f42009-09-09 15:08:12 +00002892 assert((cursor && endBuf)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002893 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002894 // If the buffer contains preprocessor directives, we do more fine-grained
2895 // rewrites. This is intended to fix code that looks like (which occurs in
2896 // NSURL.h, for example):
2897 //
2898 // #ifdef XYZ
2899 // @interface Foo : NSObject
2900 // #else
2901 // @interface FooBar : NSObject
2902 // #endif
2903 // {
2904 // int i;
2905 // }
2906 // @end
2907 //
2908 // This clause is segregated to avoid breaking the common case.
2909 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump11289f42009-09-09 15:08:12 +00002910 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002911 CDecl->getClassLoc();
2912 const char *endHeader = SM->getCharacterData(L);
Chris Lattner184e65d2009-04-14 23:22:57 +00002913 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002914
Chris Lattnerf5b77512009-02-20 18:18:36 +00002915 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002916 // advance to the end of the referenced protocols.
2917 while (endHeader < cursor && *endHeader != '>') endHeader++;
2918 endHeader++;
2919 }
2920 // rewrite the original header
2921 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2922 } else {
2923 // rewrite the original header *without* disturbing the '{'
Steve Naroffb0e33902009-12-04 21:36:32 +00002924 ReplaceText(LocStart, cursor-startBuf, Result.c_str(), Result.size());
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002925 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002926 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroffdde78982007-11-14 19:25:57 +00002927 Result = "\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002928 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00002929 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002930 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00002931 Result += "_IVARS;\n";
Mike Stump11289f42009-09-09 15:08:12 +00002932
Steve Naroffdde78982007-11-14 19:25:57 +00002933 // insert the super class structure definition.
Chris Lattner1780a852008-01-31 19:42:41 +00002934 SourceLocation OnePastCurly =
2935 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2936 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Naroffdde78982007-11-14 19:25:57 +00002937 }
2938 cursor++; // past '{'
Mike Stump11289f42009-09-09 15:08:12 +00002939
Steve Naroffdde78982007-11-14 19:25:57 +00002940 // Now comment out any visibility specifiers.
2941 while (cursor < endBuf) {
2942 if (*cursor == '@') {
2943 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner174a8252007-11-14 22:57:51 +00002944 // Skip whitespace.
2945 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2946 /*scan*/;
2947
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002948 // FIXME: presence of @public, etc. inside comment results in
2949 // this transformation as well, which is still correct c-code.
Steve Naroffdde78982007-11-14 19:25:57 +00002950 if (!strncmp(cursor, "public", strlen("public")) ||
2951 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffaf91b9a2008-04-04 22:34:24 +00002952 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002953 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattner1780a852008-01-31 19:42:41 +00002954 InsertText(atLoc, "// ", 3);
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002955 }
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002956 // FIXME: If there are cases where '<' is used in ivar declaration part
2957 // of user code, then scan the ivar list and use needToScanForQualifiers
2958 // for type checking.
2959 else if (*cursor == '<') {
2960 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner1780a852008-01-31 19:42:41 +00002961 InsertText(atLoc, "/* ", 3);
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002962 cursor = strchr(cursor, '>');
2963 cursor++;
2964 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner1780a852008-01-31 19:42:41 +00002965 InsertText(atLoc, " */", 3);
Steve Naroff295570a2008-10-30 12:09:33 +00002966 } else if (*cursor == '^') { // rewrite block specifier.
2967 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2968 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002969 }
Steve Naroffdde78982007-11-14 19:25:57 +00002970 cursor++;
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002971 }
Steve Naroffdde78982007-11-14 19:25:57 +00002972 // Don't forget to add a ';'!!
Chris Lattner1780a852008-01-31 19:42:41 +00002973 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Naroffdde78982007-11-14 19:25:57 +00002974 } else { // we don't have any instance variables - insert super struct.
Chris Lattner184e65d2009-04-14 23:22:57 +00002975 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroffdde78982007-11-14 19:25:57 +00002976 Result += " {\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002977 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00002978 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002979 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00002980 Result += "_IVARS;\n};\n";
Chris Lattner9cc55f52008-01-31 19:51:04 +00002981 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002982 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002983 // Mark this struct as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002984 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff13e74872008-05-06 18:26:51 +00002985 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002986}
2987
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002988// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002989/// class methods.
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002990template<typename MethodIterator>
2991void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
2992 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +00002993 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002994 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +00002995 const char *ClassName,
2996 std::string &Result) {
Chris Lattner31bc07e2007-12-12 07:46:12 +00002997 if (MethodBegin == MethodEnd) return;
Mike Stump11289f42009-09-09 15:08:12 +00002998
Chris Lattner31bc07e2007-12-12 07:46:12 +00002999 if (!objc_impl_method) {
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003000 /* struct _objc_method {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003001 SEL _cmd;
3002 char *method_types;
3003 void *_imp;
3004 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003005 */
Chris Lattner211f8b82007-10-25 17:07:24 +00003006 Result += "\nstruct _objc_method {\n";
3007 Result += "\tSEL _cmd;\n";
3008 Result += "\tchar *method_types;\n";
3009 Result += "\tvoid *_imp;\n";
3010 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003011
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003012 objc_impl_method = true;
Fariborz Jahanian74a1cfa2007-10-19 00:36:46 +00003013 }
Mike Stump11289f42009-09-09 15:08:12 +00003014
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003015 // Build _objc_method_list for class's methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003016
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003017 /* struct {
3018 struct _objc_method_list *next_method;
3019 int method_count;
3020 struct _objc_method method_list[];
3021 }
3022 */
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003023 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003024 Result += "\nstatic struct {\n";
3025 Result += "\tstruct _objc_method_list *next_method;\n";
3026 Result += "\tint method_count;\n";
3027 Result += "\tstruct _objc_method method_list[";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003028 Result += utostr(NumMethods);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003029 Result += "];\n} _OBJC_";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003030 Result += prefix;
3031 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3032 Result += "_METHODS_";
3033 Result += ClassName;
Steve Naroffb327e492008-03-12 17:18:30 +00003034 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003035 Result += IsInstanceMethod ? "inst" : "cls";
3036 Result += "_meth\")))= ";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003037 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003038
Chris Lattner31bc07e2007-12-12 07:46:12 +00003039 Result += "\t,{{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003040 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattner31bc07e2007-12-12 07:46:12 +00003041 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003042 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattner31bc07e2007-12-12 07:46:12 +00003043 Result += "\", \"";
3044 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003045 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003046 Result += MethodInternalNames[*MethodBegin];
3047 Result += "}\n";
3048 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3049 Result += "\t ,{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003050 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003051 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003052 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003053 Result += "\", \"";
3054 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003055 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003056 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanian56338352007-11-13 21:02:00 +00003057 Result += "}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003058 }
Chris Lattner31bc07e2007-12-12 07:46:12 +00003059 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003060}
3061
Steve Naroffd9803712009-04-29 16:37:50 +00003062/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner390d39a2008-07-21 21:32:27 +00003063void RewriteObjC::
Steve Naroffd9803712009-04-29 16:37:50 +00003064RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
3065 const char *ClassName, std::string &Result) {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003066 static bool objc_protocol_methods = false;
Steve Naroffd9803712009-04-29 16:37:50 +00003067
3068 // Output struct protocol_methods holder of method selector and type.
3069 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3070 /* struct protocol_methods {
3071 SEL _cmd;
3072 char *method_types;
3073 }
3074 */
3075 Result += "\nstruct _protocol_methods {\n";
3076 Result += "\tstruct objc_selector *_cmd;\n";
3077 Result += "\tchar *method_types;\n";
3078 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003079
Steve Naroffd9803712009-04-29 16:37:50 +00003080 objc_protocol_methods = true;
3081 }
3082 // Do not synthesize the protocol more than once.
3083 if (ObjCSynthesizedProtocols.count(PDecl))
3084 return;
Mike Stump11289f42009-09-09 15:08:12 +00003085
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003086 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3087 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3088 PDecl->instmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003089 /* struct _objc_protocol_method_list {
3090 int protocol_method_count;
3091 struct protocol_methods protocols[];
3092 }
Steve Naroff251084d2008-03-12 01:06:30 +00003093 */
Steve Naroffd9803712009-04-29 16:37:50 +00003094 Result += "\nstatic struct {\n";
3095 Result += "\tint protocol_method_count;\n";
3096 Result += "\tstruct _protocol_methods protocol_methods[";
3097 Result += utostr(NumMethods);
3098 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3099 Result += PDecl->getNameAsString();
3100 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3101 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003102
Steve Naroffd9803712009-04-29 16:37:50 +00003103 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003104 for (ObjCProtocolDecl::instmeth_iterator
3105 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003106 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003107 if (I == PDecl->instmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003108 Result += "\t ,{{(struct objc_selector *)\"";
3109 else
3110 Result += "\t ,{(struct objc_selector *)\"";
3111 Result += (*I)->getSelector().getAsString().c_str();
3112 std::string MethodTypeString;
3113 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3114 Result += "\", \"";
3115 Result += MethodTypeString;
3116 Result += "\"}\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003117 }
Steve Naroffd9803712009-04-29 16:37:50 +00003118 Result += "\t }\n};\n";
3119 }
Mike Stump11289f42009-09-09 15:08:12 +00003120
Steve Naroffd9803712009-04-29 16:37:50 +00003121 // Output class methods declared in this protocol.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003122 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3123 PDecl->classmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003124 if (NumMethods > 0) {
3125 /* struct _objc_protocol_method_list {
3126 int protocol_method_count;
3127 struct protocol_methods protocols[];
3128 }
3129 */
3130 Result += "\nstatic struct {\n";
3131 Result += "\tint protocol_method_count;\n";
3132 Result += "\tstruct _protocol_methods protocol_methods[";
3133 Result += utostr(NumMethods);
3134 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3135 Result += PDecl->getNameAsString();
3136 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3137 "{\n\t";
3138 Result += utostr(NumMethods);
3139 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003140
Steve Naroffd9803712009-04-29 16:37:50 +00003141 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003142 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003143 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003144 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003145 if (I == PDecl->classmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003146 Result += "\t ,{{(struct objc_selector *)\"";
3147 else
3148 Result += "\t ,{(struct objc_selector *)\"";
3149 Result += (*I)->getSelector().getAsString().c_str();
3150 std::string MethodTypeString;
3151 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3152 Result += "\", \"";
3153 Result += MethodTypeString;
3154 Result += "\"}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003155 }
Steve Naroffd9803712009-04-29 16:37:50 +00003156 Result += "\t }\n};\n";
3157 }
3158
3159 // Output:
3160 /* struct _objc_protocol {
3161 // Objective-C 1.0 extensions
3162 struct _objc_protocol_extension *isa;
3163 char *protocol_name;
3164 struct _objc_protocol **protocol_list;
3165 struct _objc_protocol_method_list *instance_methods;
3166 struct _objc_protocol_method_list *class_methods;
Mike Stump11289f42009-09-09 15:08:12 +00003167 };
Steve Naroffd9803712009-04-29 16:37:50 +00003168 */
3169 static bool objc_protocol = false;
3170 if (!objc_protocol) {
3171 Result += "\nstruct _objc_protocol {\n";
3172 Result += "\tstruct _objc_protocol_extension *isa;\n";
3173 Result += "\tchar *protocol_name;\n";
3174 Result += "\tstruct _objc_protocol **protocol_list;\n";
3175 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3176 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003177 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003178
Steve Naroffd9803712009-04-29 16:37:50 +00003179 objc_protocol = true;
Chris Lattner388f6e92008-07-21 21:33:21 +00003180 }
Mike Stump11289f42009-09-09 15:08:12 +00003181
Steve Naroffd9803712009-04-29 16:37:50 +00003182 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3183 Result += PDecl->getNameAsString();
3184 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3185 "{\n\t0, \"";
3186 Result += PDecl->getNameAsString();
3187 Result += "\", 0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003188 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003189 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3190 Result += PDecl->getNameAsString();
3191 Result += ", ";
3192 }
3193 else
3194 Result += "0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003195 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003196 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3197 Result += PDecl->getNameAsString();
3198 Result += "\n";
3199 }
3200 else
3201 Result += "0\n";
3202 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003203
Steve Naroffd9803712009-04-29 16:37:50 +00003204 // Mark this protocol as having been generated.
3205 if (!ObjCSynthesizedProtocols.insert(PDecl))
3206 assert(false && "protocol already synthesized");
3207
3208}
3209
3210void RewriteObjC::
3211RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3212 const char *prefix, const char *ClassName,
3213 std::string &Result) {
3214 if (Protocols.empty()) return;
Mike Stump11289f42009-09-09 15:08:12 +00003215
Steve Naroffd9803712009-04-29 16:37:50 +00003216 for (unsigned i = 0; i != Protocols.size(); i++)
3217 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3218
Chris Lattner388f6e92008-07-21 21:33:21 +00003219 // Output the top lovel protocol meta-data for the class.
3220 /* struct _objc_protocol_list {
3221 struct _objc_protocol_list *next;
3222 int protocol_count;
3223 struct _objc_protocol *class_protocols[];
3224 }
3225 */
3226 Result += "\nstatic struct {\n";
3227 Result += "\tstruct _objc_protocol_list *next;\n";
3228 Result += "\tint protocol_count;\n";
3229 Result += "\tstruct _objc_protocol *class_protocols[";
3230 Result += utostr(Protocols.size());
3231 Result += "];\n} _OBJC_";
3232 Result += prefix;
3233 Result += "_PROTOCOLS_";
3234 Result += ClassName;
3235 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3236 "{\n\t0, ";
3237 Result += utostr(Protocols.size());
3238 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003239
Chris Lattner388f6e92008-07-21 21:33:21 +00003240 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003241 Result += Protocols[0]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003242 Result += " \n";
Mike Stump11289f42009-09-09 15:08:12 +00003243
Chris Lattner388f6e92008-07-21 21:33:21 +00003244 for (unsigned i = 1; i != Protocols.size(); i++) {
3245 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003246 Result += Protocols[i]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003247 Result += "\n";
3248 }
3249 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003250}
3251
Steve Naroffd9803712009-04-29 16:37:50 +00003252
Mike Stump11289f42009-09-09 15:08:12 +00003253/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003254/// implementation.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003255void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003256 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003257 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003258 // Find category declaration for this implementation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003259 ObjCCategoryDecl *CDecl;
Mike Stump11289f42009-09-09 15:08:12 +00003260 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003261 CDecl = CDecl->getNextClassCategory())
3262 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3263 break;
Mike Stump11289f42009-09-09 15:08:12 +00003264
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003265 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003266 FullCategoryName += '_';
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003267 FullCategoryName += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003268
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003269 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003270 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003271 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003272
3273 // If any of our property implementations have associated getters or
3274 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003275 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3276 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003277 Prop != PropEnd; ++Prop) {
3278 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3279 continue;
3280 if (!(*Prop)->getPropertyIvarDecl())
3281 continue;
3282 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3283 if (!PD)
3284 continue;
3285 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3286 InstanceMethods.push_back(Getter);
3287 if (PD->isReadOnly())
3288 continue;
3289 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3290 InstanceMethods.push_back(Setter);
3291 }
3292 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003293 true, "CATEGORY_", FullCategoryName.c_str(),
3294 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003295
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003296 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003297 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003298 false, "CATEGORY_", FullCategoryName.c_str(),
3299 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003300
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003301 // Protocols referenced in class declaration?
Fariborz Jahanian989e0392007-11-13 22:09:49 +00003302 // Null CDecl is case of a category implementation with no category interface
3303 if (CDecl)
Steve Naroffd9803712009-04-29 16:37:50 +00003304 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3305 FullCategoryName.c_str(), Result);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003306 /* struct _objc_category {
3307 char *category_name;
3308 char *class_name;
3309 struct _objc_method_list *instance_methods;
3310 struct _objc_method_list *class_methods;
3311 struct _objc_protocol_list *protocols;
3312 // Objective-C 1.0 extensions
3313 uint32_t size; // sizeof (struct _objc_category)
Mike Stump11289f42009-09-09 15:08:12 +00003314 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003315 // @property decl.
Mike Stump11289f42009-09-09 15:08:12 +00003316 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003317 */
Mike Stump11289f42009-09-09 15:08:12 +00003318
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003319 static bool objc_category = false;
3320 if (!objc_category) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003321 Result += "\nstruct _objc_category {\n";
3322 Result += "\tchar *category_name;\n";
3323 Result += "\tchar *class_name;\n";
3324 Result += "\tstruct _objc_method_list *instance_methods;\n";
3325 Result += "\tstruct _objc_method_list *class_methods;\n";
3326 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003327 Result += "\tunsigned int size;\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003328 Result += "\tstruct _objc_property_list *instance_properties;\n";
3329 Result += "};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003330 objc_category = true;
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003331 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003332 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3333 Result += FullCategoryName;
Steve Naroffb327e492008-03-12 17:18:30 +00003334 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003335 Result += IDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003336 Result += "\"\n\t, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003337 Result += ClassDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003338 Result += "\"\n";
Mike Stump11289f42009-09-09 15:08:12 +00003339
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003340 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003341 Result += "\t, (struct _objc_method_list *)"
3342 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3343 Result += FullCategoryName;
3344 Result += "\n";
3345 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003346 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003347 Result += "\t, 0\n";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003348 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003349 Result += "\t, (struct _objc_method_list *)"
3350 "&_OBJC_CATEGORY_CLASS_METHODS_";
3351 Result += FullCategoryName;
3352 Result += "\n";
3353 }
3354 else
3355 Result += "\t, 0\n";
Mike Stump11289f42009-09-09 15:08:12 +00003356
Chris Lattnerf5b77512009-02-20 18:18:36 +00003357 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump11289f42009-09-09 15:08:12 +00003358 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003359 Result += FullCategoryName;
3360 Result += "\n";
3361 }
3362 else
3363 Result += "\t, 0\n";
3364 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003365}
3366
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003367/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3368/// ivar offset.
Mike Stump11289f42009-09-09 15:08:12 +00003369void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
3370 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003371 std::string &Result) {
Steve Naroffde7d0f62008-07-16 18:22:22 +00003372 if (ivar->isBitField()) {
3373 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3374 // place all bitfields at offset 0.
3375 Result += "0";
3376 } else {
3377 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003378 Result += IDecl->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003379 if (LangOpts.Microsoft)
3380 Result += "_IMPL";
3381 Result += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003382 Result += ivar->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003383 Result += ")";
3384 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003385}
3386
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003387//===----------------------------------------------------------------------===//
3388// Meta Data Emission
3389//===----------------------------------------------------------------------===//
3390
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003391void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003392 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003393 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00003394
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003395 // Explictly declared @interface's are already synthesized.
Steve Naroffaac654a2009-04-20 20:09:33 +00003396 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump11289f42009-09-09 15:08:12 +00003397 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003398 // produce correct synthesis as yet.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003399 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003400 }
Mike Stump11289f42009-09-09 15:08:12 +00003401
Chris Lattner30d23e82007-12-12 07:56:42 +00003402 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003403 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump11289f42009-09-09 15:08:12 +00003404 ? IDecl->ivar_size()
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003405 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003406 if (NumIvars > 0) {
3407 static bool objc_ivar = false;
3408 if (!objc_ivar) {
3409 /* struct _objc_ivar {
3410 char *ivar_name;
3411 char *ivar_type;
3412 int ivar_offset;
Mike Stump11289f42009-09-09 15:08:12 +00003413 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003414 */
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003415 Result += "\nstruct _objc_ivar {\n";
3416 Result += "\tchar *ivar_name;\n";
3417 Result += "\tchar *ivar_type;\n";
3418 Result += "\tint ivar_offset;\n";
3419 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003420
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003421 objc_ivar = true;
3422 }
3423
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003424 /* struct {
3425 int ivar_count;
3426 struct _objc_ivar ivar_list[nIvars];
Mike Stump11289f42009-09-09 15:08:12 +00003427 };
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003428 */
Mike Stump11289f42009-09-09 15:08:12 +00003429 Result += "\nstatic struct {\n";
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003430 Result += "\tint ivar_count;\n";
3431 Result += "\tstruct _objc_ivar ivar_list[";
3432 Result += utostr(NumIvars);
3433 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003434 Result += IDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003435 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003436 "{\n\t";
3437 Result += utostr(NumIvars);
3438 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003439
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003440 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor5f662052009-04-23 03:23:08 +00003441 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003442 if (!IDecl->ivar_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00003443 for (ObjCImplementationDecl::ivar_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003444 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor5f662052009-04-23 03:23:08 +00003445 IV != IVEnd; ++IV)
3446 IVars.push_back(*IV);
3447 IVI = IVars.begin();
3448 IVE = IVars.end();
Chris Lattner30d23e82007-12-12 07:56:42 +00003449 } else {
3450 IVI = CDecl->ivar_begin();
3451 IVE = CDecl->ivar_end();
3452 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003453 Result += "\t,{{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003454 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003455 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003456 std::string TmpString, StrEncoding;
3457 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3458 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003459 Result += StrEncoding;
3460 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003461 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003462 Result += "}\n";
Chris Lattner30d23e82007-12-12 07:56:42 +00003463 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003464 Result += "\t ,{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003465 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003466 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003467 std::string TmpString, StrEncoding;
3468 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3469 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003470 Result += StrEncoding;
3471 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003472 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003473 Result += "}\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003474 }
Mike Stump11289f42009-09-09 15:08:12 +00003475
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003476 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003477 }
Mike Stump11289f42009-09-09 15:08:12 +00003478
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003479 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003480 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003481 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003482
3483 // If any of our property implementations have associated getters or
3484 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003485 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3486 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003487 Prop != PropEnd; ++Prop) {
3488 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3489 continue;
3490 if (!(*Prop)->getPropertyIvarDecl())
3491 continue;
3492 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3493 if (!PD)
3494 continue;
3495 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3496 InstanceMethods.push_back(Getter);
3497 if (PD->isReadOnly())
3498 continue;
3499 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3500 InstanceMethods.push_back(Setter);
3501 }
3502 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003503 true, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003504
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003505 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003506 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003507 false, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003508
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003509 // Protocols referenced in class declaration?
Steve Naroffd9803712009-04-29 16:37:50 +00003510 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3511 "CLASS", CDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003512
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003513 // Declaration of class/meta-class metadata
3514 /* struct _objc_class {
3515 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003516 const char *super_class_name;
3517 char *name;
3518 long version;
3519 long info;
3520 long instance_size;
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003521 struct _objc_ivar_list *ivars;
3522 struct _objc_method_list *methods;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003523 struct objc_cache *cache;
3524 struct objc_protocol_list *protocols;
3525 const char *ivar_layout;
3526 struct _objc_class_ext *ext;
Mike Stump11289f42009-09-09 15:08:12 +00003527 };
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003528 */
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003529 static bool objc_class = false;
3530 if (!objc_class) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003531 Result += "\nstruct _objc_class {\n";
3532 Result += "\tstruct _objc_class *isa;\n";
3533 Result += "\tconst char *super_class_name;\n";
3534 Result += "\tchar *name;\n";
3535 Result += "\tlong version;\n";
3536 Result += "\tlong info;\n";
3537 Result += "\tlong instance_size;\n";
3538 Result += "\tstruct _objc_ivar_list *ivars;\n";
3539 Result += "\tstruct _objc_method_list *methods;\n";
3540 Result += "\tstruct objc_cache *cache;\n";
3541 Result += "\tstruct _objc_protocol_list *protocols;\n";
3542 Result += "\tconst char *ivar_layout;\n";
3543 Result += "\tstruct _objc_class_ext *ext;\n";
3544 Result += "};\n";
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003545 objc_class = true;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003546 }
Mike Stump11289f42009-09-09 15:08:12 +00003547
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003548 // Meta-class metadata generation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003549 ObjCInterfaceDecl *RootClass = 0;
3550 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003551 while (SuperClass) {
3552 RootClass = SuperClass;
3553 SuperClass = SuperClass->getSuperClass();
3554 }
3555 SuperClass = CDecl->getSuperClass();
Mike Stump11289f42009-09-09 15:08:12 +00003556
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003557 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003558 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003559 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003560 "{\n\t(struct _objc_class *)\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003561 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003562 Result += "\"";
3563
3564 if (SuperClass) {
3565 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003566 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003567 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003568 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003569 Result += "\"";
3570 }
3571 else {
3572 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003573 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003574 Result += "\"";
3575 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003576 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003577 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003578 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003579 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff0b844f02008-03-11 18:14:26 +00003580 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003581 Result += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003582 Result += "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003583 }
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003584 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003585 Result += ", 0\n";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003586 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003587 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003588 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003589 Result += ",0,0\n";
3590 }
Fariborz Jahanian486f7182007-10-24 20:54:23 +00003591 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003592 Result += "\t,0,0,0,0\n";
3593 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003594
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003595 // class metadata generation.
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003596 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003597 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003598 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003599 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003600 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003601 if (SuperClass) {
3602 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003603 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003604 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003605 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003606 Result += "\"";
3607 }
3608 else {
3609 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003610 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003611 Result += "\"";
3612 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003613 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003614 Result += ", 0,1";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003615 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003616 Result += ",0";
3617 else {
3618 // class has size. Must synthesize its size.
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00003619 Result += ",sizeof(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003620 Result += CDecl->getNameAsString();
Steve Naroff14a07462008-03-10 23:33:22 +00003621 if (LangOpts.Microsoft)
3622 Result += "_IMPL";
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003623 Result += ")";
3624 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003625 if (NumIvars > 0) {
Steve Naroff17978c42008-03-11 17:37:02 +00003626 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003627 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003628 Result += "\n\t";
3629 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003630 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003631 Result += ",0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003632 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003633 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003634 Result += CDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003635 Result += ", 0\n\t";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003636 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003637 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003638 Result += ",0,0";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003639 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003640 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003641 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003642 Result += ", 0,0\n";
3643 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003644 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003645 Result += ",0,0,0\n";
3646 Result += "};\n";
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003647}
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003648
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003649/// RewriteImplementations - This routine rewrites all method implementations
3650/// and emits meta-data.
3651
Steve Narofff8cfd162008-11-13 20:07:04 +00003652void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003653 int ClsDefCount = ClassImplementation.size();
3654 int CatDefCount = CategoryImplementation.size();
Mike Stump11289f42009-09-09 15:08:12 +00003655
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003656 // Rewrite implemented methods
3657 for (int i = 0; i < ClsDefCount; i++)
3658 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003659
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00003660 for (int i = 0; i < CatDefCount; i++)
3661 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofff8cfd162008-11-13 20:07:04 +00003662}
Mike Stump11289f42009-09-09 15:08:12 +00003663
Steve Narofff8cfd162008-11-13 20:07:04 +00003664void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3665 int ClsDefCount = ClassImplementation.size();
3666 int CatDefCount = CategoryImplementation.size();
3667
Steve Naroff30ac2222008-05-07 21:23:49 +00003668 // This is needed for determining instance variable offsets.
Fariborz Jahanian9ab63492010-01-07 18:31:42 +00003669 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003670 // For each implemented class, write out all its meta data.
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003671 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003672 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump11289f42009-09-09 15:08:12 +00003673
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003674 // For each implemented category, write out all its meta data.
3675 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003676 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroffd9803712009-04-29 16:37:50 +00003677
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003678 // Write objc_symtab metadata
3679 /*
3680 struct _objc_symtab
3681 {
3682 long sel_ref_cnt;
3683 SEL *refs;
3684 short cls_def_cnt;
3685 short cat_def_cnt;
3686 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump11289f42009-09-09 15:08:12 +00003687 };
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003688 */
Mike Stump11289f42009-09-09 15:08:12 +00003689
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003690 Result += "\nstruct _objc_symtab {\n";
3691 Result += "\tlong sel_ref_cnt;\n";
3692 Result += "\tSEL *refs;\n";
3693 Result += "\tshort cls_def_cnt;\n";
3694 Result += "\tshort cat_def_cnt;\n";
3695 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3696 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003697
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003698 Result += "static struct _objc_symtab "
Steve Naroffb327e492008-03-12 17:18:30 +00003699 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003700 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003701 + ", " + utostr(CatDefCount) + "\n";
3702 for (int i = 0; i < ClsDefCount; i++) {
3703 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003704 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003705 Result += "\n";
3706 }
Mike Stump11289f42009-09-09 15:08:12 +00003707
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003708 for (int i = 0; i < CatDefCount; i++) {
3709 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003710 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003711 Result += "_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003712 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003713 Result += "\n";
3714 }
Mike Stump11289f42009-09-09 15:08:12 +00003715
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003716 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003717
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003718 // Write objc_module metadata
Mike Stump11289f42009-09-09 15:08:12 +00003719
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003720 /*
3721 struct _objc_module {
3722 long version;
3723 long size;
3724 const char *name;
3725 struct _objc_symtab *symtab;
3726 }
3727 */
Mike Stump11289f42009-09-09 15:08:12 +00003728
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003729 Result += "\nstruct _objc_module {\n";
3730 Result += "\tlong version;\n";
3731 Result += "\tlong size;\n";
3732 Result += "\tconst char *name;\n";
3733 Result += "\tstruct _objc_symtab *symtab;\n";
3734 Result += "};\n\n";
3735 Result += "static struct _objc_module "
Steve Naroffb327e492008-03-12 17:18:30 +00003736 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003737 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003738 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003739 Result += "};\n\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003740
3741 if (LangOpts.Microsoft) {
Steve Naroffd9803712009-04-29 16:37:50 +00003742 if (ProtocolExprDecls.size()) {
3743 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
3744 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump11289f42009-09-09 15:08:12 +00003745 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00003746 E = ProtocolExprDecls.end(); I != E; ++I) {
3747 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
3748 Result += (*I)->getNameAsString();
3749 Result += " = &_OBJC_PROTOCOL_";
3750 Result += (*I)->getNameAsString();
3751 Result += ";\n";
3752 }
3753 Result += "#pragma data_seg(pop)\n\n";
3754 }
Steve Naroff945a3b12008-03-10 20:43:59 +00003755 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffcab93d52008-05-07 00:06:16 +00003756 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003757 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3758 Result += "&_OBJC_MODULES;\n";
3759 Result += "#pragma data_seg(pop)\n\n";
3760 }
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003761}
Chris Lattnera7c19fe2007-10-16 22:36:42 +00003762
Steve Naroff677ab3a2008-10-27 17:20:55 +00003763std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3764 const char *funcName,
3765 std::string Tag) {
3766 const FunctionType *AFT = CE->getFunctionType();
3767 QualType RT = AFT->getResultType();
3768 std::string StructRef = "struct " + Tag;
3769 std::string S = "static " + RT.getAsString() + " __" +
3770 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00003771
Steve Naroff677ab3a2008-10-27 17:20:55 +00003772 BlockDecl *BD = CE->getBlockDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003773
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003774 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump11289f42009-09-09 15:08:12 +00003775 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Narofff26a1d42009-02-02 17:19:26 +00003776 // block (to reference imported block decl refs).
3777 S += "(" + StructRef + " *__cself)";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003778 } else if (BD->param_empty()) {
3779 S += "(" + StructRef + " *__cself)";
3780 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003781 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003782 assert(FT && "SynthesizeBlockFunc: No function proto");
3783 S += '(';
3784 // first add the implicit argument.
3785 S += StructRef + " *__cself, ";
3786 std::string ParamStr;
3787 for (BlockDecl::param_iterator AI = BD->param_begin(),
3788 E = BD->param_end(); AI != E; ++AI) {
3789 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003790 ParamStr = (*AI)->getNameAsString();
Douglas Gregor7de59662009-05-29 20:38:28 +00003791 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003792 S += ParamStr;
3793 }
3794 if (FT->isVariadic()) {
3795 if (!BD->param_empty()) S += ", ";
3796 S += "...";
3797 }
3798 S += ')';
3799 }
3800 S += " {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003801
Steve Naroff677ab3a2008-10-27 17:20:55 +00003802 // Create local declarations to avoid rewriting all closure decl ref exprs.
3803 // First, emit a declaration for all "by ref" decls.
Mike Stump11289f42009-09-09 15:08:12 +00003804 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003805 E = BlockByRefDecls.end(); I != E; ++I) {
3806 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003807 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003808 std::string TypeString = "struct __Block_byref_" + Name + " *";
3809 Name = TypeString + Name;
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003810 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump11289f42009-09-09 15:08:12 +00003811 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003812 // Next, emit a declaration for all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003813 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003814 E = BlockByCopyDecls.end(); I != E; ++I) {
3815 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003816 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003817 // Handle nested closure invocation. For example:
3818 //
3819 // void (^myImportedClosure)(void);
3820 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003821 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003822 // void (^anotherClosure)(void);
3823 // anotherClosure = ^(void) {
3824 // myImportedClosure(); // import and invoke the closure
3825 // };
3826 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003827 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003828 S += "struct __block_impl *";
3829 else
Douglas Gregor7de59662009-05-29 20:38:28 +00003830 (*I)->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003831 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003832 }
3833 std::string RewrittenStr = RewrittenBlockExprs[CE];
3834 const char *cstr = RewrittenStr.c_str();
3835 while (*cstr++ != '{') ;
3836 S += cstr;
3837 S += "\n";
3838 return S;
3839}
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00003840
Steve Naroff677ab3a2008-10-27 17:20:55 +00003841std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3842 const char *funcName,
3843 std::string Tag) {
3844 std::string StructRef = "struct " + Tag;
3845 std::string S = "static void __";
Mike Stump11289f42009-09-09 15:08:12 +00003846
Steve Naroff677ab3a2008-10-27 17:20:55 +00003847 S += funcName;
3848 S += "_block_copy_" + utostr(i);
3849 S += "(" + StructRef;
3850 S += "*dst, " + StructRef;
3851 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003852 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003853 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003854 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003855 S += (*I)->getNameAsString();
Steve Naroff5ac4eac2008-12-11 20:51:38 +00003856 S += ", (void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003857 S += (*I)->getNameAsString();
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003858 if (BlockByRefDecls.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003859 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003860 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003861 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003862 }
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003863 S += "}\n";
3864
Steve Naroff677ab3a2008-10-27 17:20:55 +00003865 S += "\nstatic void __";
3866 S += funcName;
3867 S += "_block_dispose_" + utostr(i);
3868 S += "(" + StructRef;
3869 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003870 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003871 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003872 S += "_Block_object_dispose((void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003873 S += (*I)->getNameAsString();
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003874 if (BlockByRefDecls.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003875 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003876 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003877 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003878 }
Mike Stump11289f42009-09-09 15:08:12 +00003879 S += "}\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003880 return S;
3881}
3882
Steve Naroff30484702009-12-06 21:14:13 +00003883std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3884 std::string Desc) {
Steve Naroff295570a2008-10-30 12:09:33 +00003885 std::string S = "\nstruct " + Tag;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003886 std::string Constructor = " " + Tag;
Mike Stump11289f42009-09-09 15:08:12 +00003887
Steve Naroff677ab3a2008-10-27 17:20:55 +00003888 S += " {\n struct __block_impl impl;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003889 S += " struct " + Desc;
3890 S += "* Desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003891
Steve Naroff30484702009-12-06 21:14:13 +00003892 Constructor += "(void *fp, "; // Invoke function pointer.
3893 Constructor += "struct " + Desc; // Descriptor pointer.
3894 Constructor += " *desc";
Mike Stump11289f42009-09-09 15:08:12 +00003895
Steve Naroff677ab3a2008-10-27 17:20:55 +00003896 if (BlockDeclRefs.size()) {
3897 // Output all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003898 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003899 E = BlockByCopyDecls.end(); I != E; ++I) {
3900 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003901 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003902 std::string ArgName = "_" + FieldName;
3903 // Handle nested closure invocation. For example:
3904 //
3905 // void (^myImportedBlock)(void);
3906 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003907 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003908 // void (^anotherBlock)(void);
3909 // anotherBlock = ^(void) {
3910 // myImportedBlock(); // import and invoke the closure
3911 // };
3912 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003913 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003914 S += "struct __block_impl *";
3915 Constructor += ", void *" + ArgName;
3916 } else {
Douglas Gregor7de59662009-05-29 20:38:28 +00003917 (*I)->getType().getAsStringInternal(FieldName, Context->PrintingPolicy);
3918 (*I)->getType().getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003919 Constructor += ", " + ArgName;
3920 }
3921 S += FieldName + ";\n";
3922 }
3923 // Output all "by ref" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003924 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003925 E = BlockByRefDecls.end(); I != E; ++I) {
3926 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003927 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003928 std::string ArgName = "_" + FieldName;
3929 // Handle nested closure invocation. For example:
3930 //
3931 // void (^myImportedBlock)(void);
3932 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003933 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003934 // void (^anotherBlock)(void);
3935 // anotherBlock = ^(void) {
3936 // myImportedBlock(); // import and invoke the closure
3937 // };
3938 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003939 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003940 S += "struct __block_impl *";
3941 Constructor += ", void *" + ArgName;
3942 } else {
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003943 std::string TypeString = "struct __Block_byref_" + FieldName;
3944 TypeString += " *";
3945 FieldName = TypeString + FieldName;
3946 ArgName = TypeString + ArgName;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003947 Constructor += ", " + ArgName;
3948 }
3949 S += FieldName + "; // by ref\n";
3950 }
3951 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00003952 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003953 if (GlobalVarDecl)
3954 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3955 else
3956 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003957 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003958
Steve Naroff30484702009-12-06 21:14:13 +00003959 Constructor += " Desc = desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003960
Steve Naroff677ab3a2008-10-27 17:20:55 +00003961 // Initialize all "by copy" arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003962 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003963 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003964 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003965 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00003966 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003967 Constructor += Name + " = (struct __block_impl *)_";
3968 else
3969 Constructor += Name + " = _";
3970 Constructor += Name + ";\n";
3971 }
3972 // Initialize all "by ref" arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003973 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003974 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003975 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003976 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00003977 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003978 Constructor += Name + " = (struct __block_impl *)_";
3979 else
3980 Constructor += Name + " = _";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003981 Constructor += Name + "->__forwarding;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003982 }
3983 } else {
3984 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00003985 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003986 if (GlobalVarDecl)
3987 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3988 else
3989 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003990 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3991 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003992 }
3993 Constructor += " ";
3994 Constructor += "}\n";
3995 S += Constructor;
3996 S += "};\n";
3997 return S;
3998}
3999
Steve Naroff30484702009-12-06 21:14:13 +00004000std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4001 std::string ImplTag, int i,
4002 const char *FunName,
4003 unsigned hasCopy) {
4004 std::string S = "\nstatic struct " + DescTag;
4005
4006 S += " {\n unsigned long reserved;\n";
4007 S += " unsigned long Block_size;\n";
4008 if (hasCopy) {
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004009 S += " void (*copy)(struct ";
4010 S += ImplTag; S += "*, struct ";
4011 S += ImplTag; S += "*);\n";
4012
4013 S += " void (*dispose)(struct ";
4014 S += ImplTag; S += "*);\n";
Steve Naroff30484702009-12-06 21:14:13 +00004015 }
4016 S += "} ";
4017
4018 S += DescTag + "_DATA = { 0, sizeof(struct ";
4019 S += ImplTag + ")";
4020 if (hasCopy) {
4021 S += ", __" + std::string(FunName) + "_block_copy_" + utostr(i);
4022 S += ", __" + std::string(FunName) + "_block_dispose_" + utostr(i);
4023 }
4024 S += "};\n";
4025 return S;
4026}
4027
Steve Naroff677ab3a2008-10-27 17:20:55 +00004028void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004029 const char *FunName) {
4030 // Insert declaration for the function in which block literal is used.
4031 if (CurFunctionDeclToDeclareForBlock)
4032 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004033 // Insert closures that were part of the function.
4034 for (unsigned i = 0; i < Blocks.size(); i++) {
4035
4036 CollectBlockDeclRefInfo(Blocks[i]);
4037
Steve Naroff30484702009-12-06 21:14:13 +00004038 std::string ImplTag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
4039 std::string DescTag = "__" + std::string(FunName) + "_block_desc_" + utostr(i);
Mike Stump11289f42009-09-09 15:08:12 +00004040
Steve Naroff30484702009-12-06 21:14:13 +00004041 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004042
4043 InsertText(FunLocStart, CI.c_str(), CI.size());
4044
Steve Naroff30484702009-12-06 21:14:13 +00004045 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump11289f42009-09-09 15:08:12 +00004046
Steve Naroff677ab3a2008-10-27 17:20:55 +00004047 InsertText(FunLocStart, CF.c_str(), CF.size());
4048
4049 if (ImportedBlockDecls.size()) {
Steve Naroff30484702009-12-06 21:14:13 +00004050 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004051 InsertText(FunLocStart, HF.c_str(), HF.size());
4052 }
Steve Naroff30484702009-12-06 21:14:13 +00004053 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4054 ImportedBlockDecls.size() > 0);
4055 InsertText(FunLocStart, BD.c_str(), BD.size());
Mike Stump11289f42009-09-09 15:08:12 +00004056
Steve Naroff677ab3a2008-10-27 17:20:55 +00004057 BlockDeclRefs.clear();
4058 BlockByRefDecls.clear();
4059 BlockByCopyDecls.clear();
4060 BlockCallExprs.clear();
4061 ImportedBlockDecls.clear();
4062 }
4063 Blocks.clear();
4064 RewrittenBlockExprs.clear();
4065}
4066
4067void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4068 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner86d7d912008-11-24 03:54:41 +00004069 const char *FuncName = FD->getNameAsCString();
Mike Stump11289f42009-09-09 15:08:12 +00004070
Steve Naroff677ab3a2008-10-27 17:20:55 +00004071 SynthesizeBlockLiterals(FunLocStart, FuncName);
4072}
4073
4074void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff295570a2008-10-30 12:09:33 +00004075 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4076 //SourceLocation FunLocStart = MD->getLocStart();
4077 // FIXME: This hack works around a bug in Rewrite.InsertText().
4078 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattnere4b95692008-11-24 03:33:13 +00004079 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004080 // Convert colons to underscores.
4081 std::string::size_type loc = 0;
4082 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4083 FuncName.replace(loc, 1, "_");
Mike Stump11289f42009-09-09 15:08:12 +00004084
Steve Naroff677ab3a2008-10-27 17:20:55 +00004085 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
4086}
4087
4088void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4089 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4090 CI != E; ++CI)
4091 if (*CI) {
4092 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4093 GetBlockDeclRefExprs(CBE->getBody());
4094 else
4095 GetBlockDeclRefExprs(*CI);
4096 }
4097 // Handle specific things.
4098 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
4099 // FIXME: Handle enums.
4100 if (!isa<FunctionDecl>(CDRE->getDecl()))
4101 BlockDeclRefs.push_back(CDRE);
4102 return;
4103}
4104
4105void RewriteObjC::GetBlockCallExprs(Stmt *S) {
4106 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4107 CI != E; ++CI)
4108 if (*CI) {
4109 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4110 GetBlockCallExprs(CBE->getBody());
4111 else
4112 GetBlockCallExprs(*CI);
4113 }
Mike Stump11289f42009-09-09 15:08:12 +00004114
Steve Naroff677ab3a2008-10-27 17:20:55 +00004115 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4116 if (CE->getCallee()->getType()->isBlockPointerType()) {
4117 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
4118 }
4119 }
4120 return;
4121}
4122
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004123Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004124 // Navigate to relevant type information.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004125 const BlockPointerType *CPT = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004126
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004127 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004128 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004129 } else if (const BlockDeclRefExpr *CDRE =
4130 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004131 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004132 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004133 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004134 }
4135 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4136 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4137 }
4138 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4139 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4140 else if (const ConditionalOperator *CEXPR =
4141 dyn_cast<ConditionalOperator>(BlockExp)) {
4142 Expr *LHSExp = CEXPR->getLHS();
4143 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4144 Expr *RHSExp = CEXPR->getRHS();
4145 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4146 Expr *CONDExp = CEXPR->getCond();
4147 ConditionalOperator *CondExpr =
4148 new (Context) ConditionalOperator(CONDExp,
4149 SourceLocation(), cast<Expr>(LHSStmt),
4150 SourceLocation(), cast<Expr>(RHSStmt),
4151 Exp->getType());
4152 return CondExpr;
Fariborz Jahanian6ab7ed42009-12-18 01:15:21 +00004153 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4154 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004155 } else {
4156 assert(1 && "RewriteBlockClass: Bad type");
4157 }
4158 assert(CPT && "RewriteBlockClass: Bad type");
John McCall9dd450b2009-09-21 23:43:11 +00004159 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004160 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004161 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004162 // FTP will be null for closures that don't take arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004163
Steve Naroff350b6652008-10-30 10:07:53 +00004164 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4165 SourceLocation(),
4166 &Context->Idents.get("__block_impl"));
4167 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff677ab3a2008-10-27 17:20:55 +00004168
Steve Naroff350b6652008-10-30 10:07:53 +00004169 // Generate a funky cast.
4170 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00004171
Steve Naroff350b6652008-10-30 10:07:53 +00004172 // Push the block argument type.
4173 ArgTypes.push_back(PtrBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004174 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004175 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff350b6652008-10-30 10:07:53 +00004176 E = FTP->arg_type_end(); I && (I != E); ++I) {
4177 QualType t = *I;
4178 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00004179 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004180 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff350b6652008-10-30 10:07:53 +00004181 t = Context->getPointerType(BPT->getPointeeType());
4182 }
4183 ArgTypes.push_back(t);
4184 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004185 }
Steve Naroff350b6652008-10-30 10:07:53 +00004186 // Now do the pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00004187 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Steve Naroff350b6652008-10-30 10:07:53 +00004188 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004189
Steve Naroff350b6652008-10-30 10:07:53 +00004190 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump11289f42009-09-09 15:08:12 +00004191
4192 CastExpr *BlkCast = new (Context) CStyleCastExpr(PtrBlock,
Anders Carlssona2615922009-07-31 00:48:10 +00004193 CastExpr::CK_Unknown,
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004194 const_cast<Expr*>(BlockExp),
Ted Kremenek5a201952009-02-07 01:47:29 +00004195 PtrBlock, SourceLocation(),
4196 SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004197 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00004198 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4199 BlkCast);
Steve Naroff350b6652008-10-30 10:07:53 +00004200 //PE->dump();
Mike Stump11289f42009-09-09 15:08:12 +00004201
Douglas Gregor91f84212008-12-11 16:49:14 +00004202 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004203 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004204 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek5a201952009-02-07 01:47:29 +00004205 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4206 FD->getType());
Mike Stump11289f42009-09-09 15:08:12 +00004207
Anders Carlssona2615922009-07-31 00:48:10 +00004208 CastExpr *FunkCast = new (Context) CStyleCastExpr(PtrToFuncCastType,
4209 CastExpr::CK_Unknown, ME,
Ted Kremenek5a201952009-02-07 01:47:29 +00004210 PtrToFuncCastType,
4211 SourceLocation(),
4212 SourceLocation());
4213 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump11289f42009-09-09 15:08:12 +00004214
Steve Naroff350b6652008-10-30 10:07:53 +00004215 llvm::SmallVector<Expr*, 8> BlkExprs;
4216 // Add the implicit argument.
4217 BlkExprs.push_back(BlkCast);
4218 // Add the user arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004219 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004220 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00004221 BlkExprs.push_back(*I);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004222 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004223 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4224 BlkExprs.size(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004225 Exp->getType(), SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004226 return CE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004227}
4228
4229void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004230 Stmt *BlockCall = SynthesizeBlockCall(Exp, Exp->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00004231 ReplaceStmt(Exp, BlockCall);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004232}
4233
Steve Naroffd9803712009-04-29 16:37:50 +00004234// We need to return the rewritten expression to handle cases where the
4235// BlockDeclRefExpr is embedded in another expression being rewritten.
4236// For example:
4237//
4238// int main() {
4239// __block Foo *f;
4240// __block int i;
Mike Stump11289f42009-09-09 15:08:12 +00004241//
Steve Naroffd9803712009-04-29 16:37:50 +00004242// void (^myblock)() = ^() {
4243// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4244// i = 77;
4245// };
4246//}
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004247Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanian25c07fa2009-12-23 19:26:34 +00004248 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004249 // for each DeclRefExp where BYREFVAR is name of the variable.
4250 ValueDecl *VD;
4251 bool isArrow = true;
4252 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4253 VD = BDRE->getDecl();
4254 else {
4255 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4256 isArrow = false;
4257 }
4258
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004259 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4260 &Context->Idents.get("__forwarding"),
4261 Context->VoidPtrTy, 0,
4262 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004263 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4264 FD, SourceLocation(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004265 FD->getType());
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004266
4267 const char *Name = VD->getNameAsCString();
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004268 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4269 &Context->Idents.get(Name),
4270 Context->VoidPtrTy, 0,
4271 /*BitWidth=*/0, /*Mutable=*/true);
4272 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004273 DeclRefExp->getType());
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004274
4275
4276
Steve Narofff26a1d42009-02-02 17:19:26 +00004277 // Need parens to enforce precedence.
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004278 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4279 ME);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004280 ReplaceStmt(DeclRefExp, PE);
Steve Naroffd9803712009-04-29 16:37:50 +00004281 return PE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004282}
4283
Steve Naroffc989a7b2008-11-03 23:29:32 +00004284void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4285 SourceLocation LocStart = CE->getLParenLoc();
4286 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofff4b992a2008-10-28 20:29:00 +00004287
4288 // Need to avoid trying to rewrite synthesized casts.
4289 if (LocStart.isInvalid())
4290 return;
Steve Naroff3e7ced12008-11-03 11:20:24 +00004291 // Need to avoid trying to rewrite casts contained in macros.
4292 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4293 return;
Mike Stump11289f42009-09-09 15:08:12 +00004294
Steve Naroff677ab3a2008-10-27 17:20:55 +00004295 const char *startBuf = SM->getCharacterData(LocStart);
4296 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00004297
Steve Naroff677ab3a2008-10-27 17:20:55 +00004298 // advance the location to startArgList.
4299 const char *argPtr = startBuf;
Mike Stump11289f42009-09-09 15:08:12 +00004300
Steve Naroff677ab3a2008-10-27 17:20:55 +00004301 while (*argPtr++ && (argPtr < endBuf)) {
4302 switch (*argPtr) {
Mike Stump11289f42009-09-09 15:08:12 +00004303 case '^':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004304 // Replace the '^' with '*'.
4305 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
4306 ReplaceText(LocStart, 1, "*", 1);
4307 break;
4308 }
4309 }
4310 return;
4311}
4312
4313void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4314 SourceLocation DeclLoc = FD->getLocation();
4315 unsigned parenCount = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004316
Steve Naroff677ab3a2008-10-27 17:20:55 +00004317 // We have 1 or more arguments that have closure pointers.
4318 const char *startBuf = SM->getCharacterData(DeclLoc);
4319 const char *startArgList = strchr(startBuf, '(');
Mike Stump11289f42009-09-09 15:08:12 +00004320
Steve Naroff677ab3a2008-10-27 17:20:55 +00004321 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004322
Steve Naroff677ab3a2008-10-27 17:20:55 +00004323 parenCount++;
4324 // advance the location to startArgList.
4325 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4326 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump11289f42009-09-09 15:08:12 +00004327
Steve Naroff677ab3a2008-10-27 17:20:55 +00004328 const char *argPtr = startArgList;
Mike Stump11289f42009-09-09 15:08:12 +00004329
Steve Naroff677ab3a2008-10-27 17:20:55 +00004330 while (*argPtr++ && parenCount) {
4331 switch (*argPtr) {
Mike Stump11289f42009-09-09 15:08:12 +00004332 case '^':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004333 // Replace the '^' with '*'.
4334 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
4335 ReplaceText(DeclLoc, 1, "*", 1);
4336 break;
Mike Stump11289f42009-09-09 15:08:12 +00004337 case '(':
4338 parenCount++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004339 break;
Mike Stump11289f42009-09-09 15:08:12 +00004340 case ')':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004341 parenCount--;
4342 break;
4343 }
4344 }
4345 return;
4346}
4347
4348bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004349 const FunctionProtoType *FTP;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004350 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004351 if (PT) {
John McCall9dd450b2009-09-21 23:43:11 +00004352 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004353 } else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004354 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004355 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall9dd450b2009-09-21 23:43:11 +00004356 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004357 }
4358 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004359 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004360 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +00004361 if (isTopLevelBlockPointerType(*I))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004362 return true;
4363 }
4364 return false;
4365}
4366
Ted Kremenek5a201952009-02-07 01:47:29 +00004367void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4368 const char *&RParen) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004369 const char *argPtr = strchr(Name, '(');
4370 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004371
Steve Naroff677ab3a2008-10-27 17:20:55 +00004372 LParen = argPtr; // output the start.
4373 argPtr++; // skip past the left paren.
4374 unsigned parenCount = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004375
Steve Naroff677ab3a2008-10-27 17:20:55 +00004376 while (*argPtr && parenCount) {
4377 switch (*argPtr) {
4378 case '(': parenCount++; break;
4379 case ')': parenCount--; break;
4380 default: break;
4381 }
4382 if (parenCount) argPtr++;
4383 }
4384 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4385 RParen = argPtr; // output the end
4386}
4387
4388void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4389 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4390 RewriteBlockPointerFunctionArgs(FD);
4391 return;
Mike Stump11289f42009-09-09 15:08:12 +00004392 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004393 // Handle Variables and Typedefs.
4394 SourceLocation DeclLoc = ND->getLocation();
4395 QualType DeclT;
4396 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4397 DeclT = VD->getType();
4398 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4399 DeclT = TDD->getUnderlyingType();
4400 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4401 DeclT = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004402 else
Steve Naroff677ab3a2008-10-27 17:20:55 +00004403 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump11289f42009-09-09 15:08:12 +00004404
Steve Naroff677ab3a2008-10-27 17:20:55 +00004405 const char *startBuf = SM->getCharacterData(DeclLoc);
4406 const char *endBuf = startBuf;
4407 // scan backward (from the decl location) for the end of the previous decl.
4408 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4409 startBuf--;
Mike Stump11289f42009-09-09 15:08:12 +00004410
Steve Naroff677ab3a2008-10-27 17:20:55 +00004411 // *startBuf != '^' if we are dealing with a pointer to function that
4412 // may take block argument types (which will be handled below).
4413 if (*startBuf == '^') {
4414 // Replace the '^' with '*', computing a negative offset.
4415 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4416 ReplaceText(DeclLoc, 1, "*", 1);
4417 }
4418 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4419 // Replace the '^' with '*' for arguments.
4420 DeclLoc = ND->getLocation();
4421 startBuf = SM->getCharacterData(DeclLoc);
4422 const char *argListBegin, *argListEnd;
4423 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4424 while (argListBegin < argListEnd) {
4425 if (*argListBegin == '^') {
4426 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4427 ReplaceText(CaretLoc, 1, "*", 1);
4428 }
4429 argListBegin++;
4430 }
4431 }
4432 return;
4433}
4434
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004435
4436/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4437/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4438/// struct Block_byref_id_object *src) {
4439/// _Block_object_assign (&_dest->object, _src->object,
4440/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4441/// [|BLOCK_FIELD_IS_WEAK]) // object
4442/// _Block_object_assign(&_dest->object, _src->object,
4443/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4444/// [|BLOCK_FIELD_IS_WEAK]) // block
4445/// }
4446/// And:
4447/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4448/// _Block_object_dispose(_src->object,
4449/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4450/// [|BLOCK_FIELD_IS_WEAK]) // object
4451/// _Block_object_dispose(_src->object,
4452/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4453/// [|BLOCK_FIELD_IS_WEAK]) // block
4454/// }
4455
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004456std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4457 int flag) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004458 std::string S;
Benjamin Kramere056cea2010-01-10 19:57:50 +00004459 if (CopyDestroyCache.count(flag))
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004460 return S;
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004461 CopyDestroyCache.insert(flag);
4462 S = "static void __Block_byref_id_object_copy_";
4463 S += utostr(flag);
4464 S += "(void *dst, void *src) {\n";
4465
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004466 // offset into the object pointer is computed as:
4467 // void * + void* + int + int + void* + void *
4468 unsigned IntSize =
4469 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4470 unsigned VoidPtrSize =
4471 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4472
4473 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
4474 S += " _Block_object_assign((char*)dst + ";
4475 S += utostr(offset);
4476 S += ", *(void * *) ((char*)src + ";
4477 S += utostr(offset);
4478 S += "), ";
4479 S += utostr(flag);
4480 S += ");\n}\n";
4481
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004482 S += "static void __Block_byref_id_object_dispose_";
4483 S += utostr(flag);
4484 S += "(void *src) {\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004485 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4486 S += utostr(offset);
4487 S += "), ";
4488 S += utostr(flag);
4489 S += ");\n}\n";
4490 return S;
4491}
4492
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004493/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4494/// the declaration into:
4495/// struct __Block_byref_ND {
4496/// void *__isa; // NULL for everything except __weak pointers
4497/// struct __Block_byref_ND *__forwarding;
4498/// int32_t __flags;
4499/// int32_t __size;
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004500/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4501/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004502/// typex ND;
4503/// };
4504///
4505/// It then replaces declaration of ND variable with:
4506/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4507/// __size=sizeof(struct __Block_byref_ND),
4508/// ND=initializer-if-any};
4509///
4510///
4511void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004512 // Insert declaration for the function in which block literal is
4513 // used.
4514 if (CurFunctionDeclToDeclareForBlock)
4515 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004516 int flag = 0;
4517 int isa = 0;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004518 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4519 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian92368a12009-12-30 20:38:08 +00004520 SourceLocation X = ND->getLocEnd();
4521 X = SM->getInstantiationLoc(X);
4522 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004523 std::string Name(ND->getNameAsString());
4524 std::string ByrefType = "struct __Block_byref_";
4525 ByrefType += Name;
4526 ByrefType += " {\n";
4527 ByrefType += " void *__isa;\n";
4528 ByrefType += " struct __Block_byref_" + Name + " *__forwarding;\n";
4529 ByrefType += " int __flags;\n";
4530 ByrefType += " int __size;\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004531 // Add void *__Block_byref_id_object_copy;
4532 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004533 QualType Ty = ND->getType();
4534 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4535 if (HasCopyAndDispose) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004536 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4537 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004538 }
4539
4540 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004541 ByrefType += " " + Name + ";\n";
4542 ByrefType += "};\n";
4543 // Insert this type in global scope. It is needed by helper function.
4544 assert(CurFunctionDef && "RewriteByRefVar - CurFunctionDef is null");
4545 SourceLocation FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4546 InsertText(FunLocStart, ByrefType.c_str(), ByrefType.size());
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004547 if (Ty.isObjCGCWeak()) {
4548 flag |= BLOCK_FIELD_IS_WEAK;
4549 isa = 1;
4550 }
4551
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004552 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004553 flag = BLOCK_BYREF_CALLER;
4554 QualType Ty = ND->getType();
4555 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4556 if (Ty->isBlockPointerType())
4557 flag |= BLOCK_FIELD_IS_BLOCK;
4558 else
4559 flag |= BLOCK_FIELD_IS_OBJECT;
4560 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004561 if (!HF.empty())
4562 InsertText(FunLocStart, HF.c_str(), HF.size());
4563 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004564
4565 // struct __Block_byref_ND ND =
4566 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4567 // initializer-if-any};
4568 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanianf7945432010-01-05 18:15:57 +00004569 unsigned flags = 0;
4570 if (HasCopyAndDispose)
4571 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004572 Name = ND->getNameAsString();
4573 ByrefType = "struct __Block_byref_" + Name;
4574 if (!hasInit) {
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004575 ByrefType += " " + Name + " = {(void*)";
4576 ByrefType += utostr(isa);
4577 ByrefType += ", &" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004578 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004579 ByrefType += ", ";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004580 ByrefType += "sizeof(struct __Block_byref_" + Name + ")";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004581 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004582 ByrefType += ", __Block_byref_id_object_copy_";
4583 ByrefType += utostr(flag);
4584 ByrefType += ", __Block_byref_id_object_dispose_";
4585 ByrefType += utostr(flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004586 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004587 ByrefType += "};\n";
4588 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(),
4589 ByrefType.c_str(), ByrefType.size());
4590 }
4591 else {
4592 SourceLocation startLoc = ND->getInit()->getLocStart();
Fariborz Jahanianb8646ed2010-01-05 23:06:29 +00004593 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004594 ByrefType += " " + Name;
4595 ReplaceText(DeclLoc, endBuf-startBuf,
4596 ByrefType.c_str(), ByrefType.size());
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004597 ByrefType = " = {(void*)";
4598 ByrefType += utostr(isa);
4599 ByrefType += ", &" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004600 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004601 ByrefType += ", ";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004602 ByrefType += "sizeof(struct __Block_byref_" + Name + "), ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004603 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004604 ByrefType += "__Block_byref_id_object_copy_";
4605 ByrefType += utostr(flag);
4606 ByrefType += ", __Block_byref_id_object_dispose_";
4607 ByrefType += utostr(flag);
4608 ByrefType += ", ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004609 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004610 InsertText(startLoc, ByrefType.c_str(), ByrefType.size());
Steve Naroff13468372009-12-23 17:24:33 +00004611
4612 // Complete the newly synthesized compound expression by inserting a right
4613 // curly brace before the end of the declaration.
4614 // FIXME: This approach avoids rewriting the initializer expression. It
4615 // also assumes there is only one declarator. For example, the following
4616 // isn't currently supported by this routine (in general):
4617 //
4618 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4619 //
4620 const char *startBuf = SM->getCharacterData(startLoc);
4621 const char *semiBuf = strchr(startBuf, ';');
4622 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4623 SourceLocation semiLoc =
4624 startLoc.getFileLocWithOffset(semiBuf-startBuf);
4625
4626 InsertText(semiLoc, "}", 1);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004627 }
Fariborz Jahanian81203462009-12-22 00:48:54 +00004628 return;
4629}
4630
Mike Stump11289f42009-09-09 15:08:12 +00004631void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004632 // Add initializers for any closure decl refs.
4633 GetBlockDeclRefExprs(Exp->getBody());
4634 if (BlockDeclRefs.size()) {
4635 // Unique all "by copy" declarations.
4636 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4637 if (!BlockDeclRefs[i]->isByRef())
4638 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
4639 // Unique all "by ref" declarations.
4640 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4641 if (BlockDeclRefs[i]->isByRef()) {
4642 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4643 }
4644 // Find any imported blocks...they will need special attention.
4645 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004646 if (BlockDeclRefs[i]->isByRef() ||
4647 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4648 BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroff832d8902008-11-13 17:40:07 +00004649 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004650 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4651 }
4652 }
4653}
4654
Steve Narofff4b992a2008-10-28 20:29:00 +00004655FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4656 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004657 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump11289f42009-09-09 15:08:12 +00004658 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004659 ID, FType, 0, FunctionDecl::Extern, false,
Douglas Gregor739ef0c2009-02-25 16:33:18 +00004660 false);
Steve Narofff4b992a2008-10-28 20:29:00 +00004661}
4662
Steve Naroffd8907b72008-10-29 18:15:37 +00004663Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004664 Blocks.push_back(Exp);
4665
4666 CollectBlockDeclRefInfo(Exp);
4667 std::string FuncName;
Mike Stump11289f42009-09-09 15:08:12 +00004668
Steve Narofff4b992a2008-10-28 20:29:00 +00004669 if (CurFunctionDef)
Chris Lattnere4b95692008-11-24 03:33:13 +00004670 FuncName = CurFunctionDef->getNameAsString();
Steve Narofff4b992a2008-10-28 20:29:00 +00004671 else if (CurMethodDef) {
Chris Lattnere4b95692008-11-24 03:33:13 +00004672 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofff4b992a2008-10-28 20:29:00 +00004673 // Convert colons to underscores.
4674 std::string::size_type loc = 0;
4675 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4676 FuncName.replace(loc, 1, "_");
Steve Naroffd8907b72008-10-29 18:15:37 +00004677 } else if (GlobalVarDecl)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004678 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +00004679
Steve Narofff4b992a2008-10-28 20:29:00 +00004680 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump11289f42009-09-09 15:08:12 +00004681
Steve Narofff4b992a2008-10-28 20:29:00 +00004682 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4683 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump11289f42009-09-09 15:08:12 +00004684
Steve Narofff4b992a2008-10-28 20:29:00 +00004685 // Get a pointer to the function type so we can cast appropriately.
4686 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4687
4688 FunctionDecl *FD;
4689 Expr *NewRep;
Mike Stump11289f42009-09-09 15:08:12 +00004690
Steve Narofff4b992a2008-10-28 20:29:00 +00004691 // Simulate a contructor call...
4692 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004693 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004694
Steve Narofff4b992a2008-10-28 20:29:00 +00004695 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00004696
Steve Naroffe2514232008-10-29 21:23:59 +00004697 // Initialize the block function.
Steve Narofff4b992a2008-10-28 20:29:00 +00004698 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004699 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4700 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004701 CastExpr *castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4702 CastExpr::CK_Unknown, Arg,
Ted Kremenek5a201952009-02-07 01:47:29 +00004703 Context->VoidPtrTy, SourceLocation(),
4704 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004705 InitExprs.push_back(castExpr);
4706
Steve Naroff30484702009-12-06 21:14:13 +00004707 // Initialize the block descriptor.
4708 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump11289f42009-09-09 15:08:12 +00004709
Steve Naroff30484702009-12-06 21:14:13 +00004710 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
4711 &Context->Idents.get(DescData.c_str()),
4712 Context->VoidPtrTy, 0,
4713 VarDecl::Static);
4714 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
4715 new (Context) DeclRefExpr(NewVD,
4716 Context->VoidPtrTy, SourceLocation()),
4717 UnaryOperator::AddrOf,
4718 Context->getPointerType(Context->VoidPtrTy),
4719 SourceLocation());
4720 InitExprs.push_back(DescRefExpr);
4721
Steve Narofff4b992a2008-10-28 20:29:00 +00004722 // Add initializers for any closure decl refs.
4723 if (BlockDeclRefs.size()) {
Steve Naroffe2514232008-10-29 21:23:59 +00004724 Expr *Exp;
Steve Narofff4b992a2008-10-28 20:29:00 +00004725 // Output all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004726 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004727 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004728 if (isObjCType((*I)->getType())) {
Steve Naroffe2514232008-10-29 21:23:59 +00004729 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner86d7d912008-11-24 03:54:41 +00004730 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004731 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroffa5c0db82008-12-11 21:05:33 +00004732 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004733 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004734 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004735 Exp = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4736 CastExpr::CK_Unknown, Arg,
4737 Context->VoidPtrTy,
Anders Carlssona2615922009-07-31 00:48:10 +00004738 SourceLocation(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004739 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004740 } else {
Chris Lattner86d7d912008-11-24 03:54:41 +00004741 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004742 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004743 }
Mike Stump11289f42009-09-09 15:08:12 +00004744 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004745 }
4746 // Output all "by ref" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004747 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004748 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004749 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004750 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4751 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004752 Context->getPointerType(Exp->getType()),
Steve Naroffe2514232008-10-29 21:23:59 +00004753 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004754 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004755 }
4756 }
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004757 if (ImportedBlockDecls.size()) {
4758 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4759 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff30484702009-12-06 21:14:13 +00004760 unsigned IntSize =
4761 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004762 Expr *FlagExp = new (Context) IntegerLiteral(llvm::APInt(IntSize, flag),
4763 Context->IntTy, SourceLocation());
4764 InitExprs.push_back(FlagExp);
Steve Naroff30484702009-12-06 21:14:13 +00004765 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004766 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4767 FType, SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00004768 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004769 Context->getPointerType(NewRep->getType()),
Steve Narofff4b992a2008-10-28 20:29:00 +00004770 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004771 NewRep = new (Context) CStyleCastExpr(FType, CastExpr::CK_Unknown, NewRep,
Anders Carlssona2615922009-07-31 00:48:10 +00004772 FType, SourceLocation(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004773 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004774 BlockDeclRefs.clear();
4775 BlockByRefDecls.clear();
4776 BlockByCopyDecls.clear();
4777 ImportedBlockDecls.clear();
4778 return NewRep;
4779}
4780
4781//===----------------------------------------------------------------------===//
4782// Function Body / Expression rewriting
4783//===----------------------------------------------------------------------===//
4784
Steve Naroff4588d0f2008-12-04 16:24:46 +00004785// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4786// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4787// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4788// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4789// Since the rewriter isn't capable of rewriting rewritten code, it's important
4790// we get this right.
4791void RewriteObjC::CollectPropertySetters(Stmt *S) {
4792 // Perform a bottom up traversal of all children.
4793 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4794 CI != E; ++CI)
4795 if (*CI)
4796 CollectPropertySetters(*CI);
4797
4798 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4799 if (BinOp->isAssignmentOp()) {
4800 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4801 PropSetters[PRE] = BinOp;
4802 }
4803 }
4804}
4805
Steve Narofff4b992a2008-10-28 20:29:00 +00004806Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump11289f42009-09-09 15:08:12 +00004807 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004808 isa<DoStmt>(S) || isa<ForStmt>(S))
4809 Stmts.push_back(S);
4810 else if (isa<ObjCForCollectionStmt>(S)) {
4811 Stmts.push_back(S);
Chris Lattnerb71980f2010-01-09 21:45:57 +00004812 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofff4b992a2008-10-28 20:29:00 +00004813 }
Mike Stump11289f42009-09-09 15:08:12 +00004814
Steve Narofff4b992a2008-10-28 20:29:00 +00004815 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004816
Steve Narofff4b992a2008-10-28 20:29:00 +00004817 // Perform a bottom up rewrite of all children.
4818 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4819 CI != E; ++CI)
4820 if (*CI) {
4821 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Mike Stump11289f42009-09-09 15:08:12 +00004822 if (newStmt)
Steve Narofff4b992a2008-10-28 20:29:00 +00004823 *CI = newStmt;
4824 }
Mike Stump11289f42009-09-09 15:08:12 +00004825
Steve Narofff4b992a2008-10-28 20:29:00 +00004826 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4827 // Rewrite the block body in place.
4828 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Mike Stump11289f42009-09-09 15:08:12 +00004829
Steve Narofff4b992a2008-10-28 20:29:00 +00004830 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenekdb2ef372010-01-07 18:00:35 +00004831 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroffd8907b72008-10-29 18:15:37 +00004832 RewrittenBlockExprs[BE] = Str;
Mike Stump11289f42009-09-09 15:08:12 +00004833
Steve Narofff4b992a2008-10-28 20:29:00 +00004834 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4835 //blockTranscribed->dump();
Steve Naroffd8907b72008-10-29 18:15:37 +00004836 ReplaceStmt(S, blockTranscribed);
Steve Narofff4b992a2008-10-28 20:29:00 +00004837 return blockTranscribed;
4838 }
4839 // Handle specific things.
4840 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4841 return RewriteAtEncode(AtEncode);
Mike Stump11289f42009-09-09 15:08:12 +00004842
Steve Narofff4b992a2008-10-28 20:29:00 +00004843 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4844 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4845
Steve Naroff4588d0f2008-12-04 16:24:46 +00004846 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4847 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4848 if (BinOp) {
4849 // Because the rewriter doesn't allow us to rewrite rewritten code,
4850 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroff08628db2008-12-09 12:56:34 +00004851 DisableReplaceStmt = true;
4852 // Save the source range. Even if we disable the replacement, the
4853 // rewritten node will have been inserted into the tree. If the synthesized
4854 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump11289f42009-09-09 15:08:12 +00004855 // self.errorHandler = handler ? handler :
Steve Naroff08628db2008-12-09 12:56:34 +00004856 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4857 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroff4588d0f2008-12-04 16:24:46 +00004858 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroff08628db2008-12-09 12:56:34 +00004859 DisableReplaceStmt = false;
Steve Naroff22216db2008-12-04 23:50:32 +00004860 //
4861 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4862 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4863 // to see the original expression). Consider this example:
4864 //
4865 // Foo *obj1, *obj2;
4866 //
4867 // obj1.i = [obj2 rrrr];
4868 //
4869 // 'BinOp' for the previous expression looks like:
4870 //
4871 // (BinaryOperator 0x231ccf0 'int' '='
4872 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4873 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4874 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4875 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4876 //
4877 // 'newStmt' represents the rewritten message expression. For example:
4878 //
4879 // (CallExpr 0x231d300 'id':'struct objc_object *'
4880 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4881 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4882 // (CStyleCastExpr 0x231d220 'void *'
4883 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4884 //
4885 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4886 // can be used as the setter argument. ReplaceStmt() will still 'see'
4887 // the original RHS (since we haven't altered BinOp).
4888 //
Mike Stump11289f42009-09-09 15:08:12 +00004889 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff22216db2008-12-04 23:50:32 +00004890 // node. As a result, we now leak the original AST nodes.
4891 //
Steve Naroff08628db2008-12-09 12:56:34 +00004892 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroff4588d0f2008-12-04 16:24:46 +00004893 } else {
4894 return RewritePropertyGetter(PropRefExpr);
Steve Narofff326f402008-12-03 00:56:33 +00004895 }
4896 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004897 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4898 return RewriteAtSelector(AtSelector);
Mike Stump11289f42009-09-09 15:08:12 +00004899
Steve Narofff4b992a2008-10-28 20:29:00 +00004900 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4901 return RewriteObjCStringLiteral(AtString);
Mike Stump11289f42009-09-09 15:08:12 +00004902
Steve Narofff4b992a2008-10-28 20:29:00 +00004903 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00004904#if 0
Steve Narofff4b992a2008-10-28 20:29:00 +00004905 // Before we rewrite it, put the original message expression in a comment.
4906 SourceLocation startLoc = MessExpr->getLocStart();
4907 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00004908
Steve Narofff4b992a2008-10-28 20:29:00 +00004909 const char *startBuf = SM->getCharacterData(startLoc);
4910 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004911
Steve Narofff4b992a2008-10-28 20:29:00 +00004912 std::string messString;
4913 messString += "// ";
4914 messString.append(startBuf, endBuf-startBuf+1);
4915 messString += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00004916
4917 // FIXME: Missing definition of
Steve Narofff4b992a2008-10-28 20:29:00 +00004918 // InsertText(clang::SourceLocation, char const*, unsigned int).
4919 // InsertText(startLoc, messString.c_str(), messString.size());
4920 // Tried this, but it didn't work either...
4921 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff4588d0f2008-12-04 16:24:46 +00004922#endif
Steve Narofff4b992a2008-10-28 20:29:00 +00004923 return RewriteMessageExpr(MessExpr);
4924 }
Mike Stump11289f42009-09-09 15:08:12 +00004925
Steve Narofff4b992a2008-10-28 20:29:00 +00004926 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4927 return RewriteObjCTryStmt(StmtTry);
4928
4929 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4930 return RewriteObjCSynchronizedStmt(StmtTry);
4931
4932 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4933 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump11289f42009-09-09 15:08:12 +00004934
Steve Narofff4b992a2008-10-28 20:29:00 +00004935 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4936 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump11289f42009-09-09 15:08:12 +00004937
4938 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofff4b992a2008-10-28 20:29:00 +00004939 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump11289f42009-09-09 15:08:12 +00004940 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofff4b992a2008-10-28 20:29:00 +00004941 OrigStmtRange.getEnd());
4942 if (BreakStmt *StmtBreakStmt =
4943 dyn_cast<BreakStmt>(S))
4944 return RewriteBreakStmt(StmtBreakStmt);
4945 if (ContinueStmt *StmtContinueStmt =
4946 dyn_cast<ContinueStmt>(S))
4947 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump11289f42009-09-09 15:08:12 +00004948
4949 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofff4b992a2008-10-28 20:29:00 +00004950 // and cast exprs.
4951 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4952 // FIXME: What we're doing here is modifying the type-specifier that
4953 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump11289f42009-09-09 15:08:12 +00004954 // a separate type-specifier that we can rewrite.
Steve Naroffe70a52a2009-12-05 15:55:59 +00004955 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4956 // the context of an ObjCForCollectionStmt. For example:
4957 // NSArray *someArray;
4958 // for (id <FooProtocol> index in someArray) ;
4959 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4960 // and it depends on the original text locations/positions.
Benjamin Krameracc5fa12009-12-05 22:16:51 +00004961 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroffe70a52a2009-12-05 15:55:59 +00004962 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump11289f42009-09-09 15:08:12 +00004963
Steve Narofff4b992a2008-10-28 20:29:00 +00004964 // Blocks rewrite rules.
4965 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4966 DI != DE; ++DI) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004967 Decl *SD = *DI;
Steve Narofff4b992a2008-10-28 20:29:00 +00004968 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004969 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004970 RewriteBlockPointerDecl(ND);
Mike Stump11289f42009-09-09 15:08:12 +00004971 else if (ND->getType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004972 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004973 if (VarDecl *VD = dyn_cast<VarDecl>(SD))
4974 if (VD->hasAttr<BlocksAttr>())
4975 RewriteByRefVar(VD);
Steve Narofff4b992a2008-10-28 20:29:00 +00004976 }
4977 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004978 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004979 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00004980 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004981 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4982 }
4983 }
4984 }
Mike Stump11289f42009-09-09 15:08:12 +00004985
Steve Narofff4b992a2008-10-28 20:29:00 +00004986 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4987 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump11289f42009-09-09 15:08:12 +00004988
4989 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004990 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4991 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump11289f42009-09-09 15:08:12 +00004992 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4993 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004994 && "Statement stack mismatch");
4995 Stmts.pop_back();
4996 }
4997 // Handle blocks rewriting.
4998 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4999 if (BDRE->isByRef())
Steve Naroffd9803712009-04-29 16:37:50 +00005000 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofff4b992a2008-10-28 20:29:00 +00005001 }
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005002 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5003 ValueDecl *VD = DRE->getDecl();
5004 if (VD->hasAttr<BlocksAttr>())
5005 return RewriteBlockDeclRefExpr(DRE);
5006 }
5007
Steve Narofff4b992a2008-10-28 20:29:00 +00005008 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff350b6652008-10-30 10:07:53 +00005009 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00005010 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00005011 ReplaceStmt(S, BlockCall);
5012 return BlockCall;
5013 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005014 }
Steve Naroffc989a7b2008-11-03 23:29:32 +00005015 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005016 RewriteCastExpr(CE);
5017 }
5018#if 0
5019 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek5a201952009-02-07 01:47:29 +00005020 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00005021 // Get the new text.
5022 std::string SStr;
5023 llvm::raw_string_ostream Buf(SStr);
Eli Friedman0905f142009-05-30 05:19:26 +00005024 Replacement->printPretty(Buf, *Context);
Steve Narofff4b992a2008-10-28 20:29:00 +00005025 const std::string &Str = Buf.str();
5026
5027 printf("CAST = %s\n", &Str[0]);
5028 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5029 delete S;
5030 return Replacement;
5031 }
5032#endif
5033 // Return this stmt unmodified.
5034 return S;
5035}
5036
Steve Naroffe70a52a2009-12-05 15:55:59 +00005037void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5038 for (RecordDecl::field_iterator i = RD->field_begin(),
5039 e = RD->field_end(); i != e; ++i) {
5040 FieldDecl *FD = *i;
5041 if (isTopLevelBlockPointerType(FD->getType()))
5042 RewriteBlockPointerDecl(FD);
5043 if (FD->getType()->isObjCQualifiedIdType() ||
5044 FD->getType()->isObjCQualifiedInterfaceType())
5045 RewriteObjCQualifiedInterfaceTypes(FD);
5046 }
5047}
5048
Steve Narofff4b992a2008-10-28 20:29:00 +00005049/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5050/// main file of the input.
5051void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5052 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffb1368882008-12-17 00:20:22 +00005053 if (FD->isOverloadedOperator())
5054 return;
Mike Stump11289f42009-09-09 15:08:12 +00005055
Steve Narofff4b992a2008-10-28 20:29:00 +00005056 // Since function prototypes don't have ParmDecl's, we check the function
5057 // prototype. This enables us to rewrite function declarations and
5058 // definitions using the same code.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005059 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005060
Sebastian Redla7b98a72009-04-26 20:35:05 +00005061 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005062 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005063 CurFunctionDef = FD;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005064 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005065 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005066 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005067 Body =
5068 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5069 FD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005070 CurrentBody = 0;
5071 if (PropParentMap) {
5072 delete PropParentMap;
5073 PropParentMap = 0;
5074 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005075 // This synthesizes and inserts the block "impl" struct, invoke function,
5076 // and any copy/dispose helper functions.
5077 InsertBlockLiteralsWithinFunction(FD);
5078 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005079 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005080 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005081 return;
5082 }
5083 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005084 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005085 CurMethodDef = MD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005086 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005087 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005088 Body =
5089 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5090 MD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005091 CurrentBody = 0;
5092 if (PropParentMap) {
5093 delete PropParentMap;
5094 PropParentMap = 0;
5095 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005096 InsertBlockLiteralsWithinMethod(MD);
5097 CurMethodDef = 0;
5098 }
5099 }
5100 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5101 ClassImplementation.push_back(CI);
5102 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5103 CategoryImplementation.push_back(CI);
5104 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5105 RewriteForwardClassDecl(CD);
5106 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5107 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroffa5c0db82008-12-11 21:05:33 +00005108 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005109 RewriteBlockPointerDecl(VD);
Steve Naroffd8907b72008-10-29 18:15:37 +00005110 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005111 CheckFunctionPointerDecl(VD->getType(), VD);
5112 if (VD->getInit()) {
Steve Naroffc989a7b2008-11-03 23:29:32 +00005113 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005114 RewriteCastExpr(CE);
5115 }
5116 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00005117 } else if (VD->getType()->isRecordType()) {
5118 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5119 if (RD->isDefinition())
5120 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005121 }
Steve Naroffd8907b72008-10-29 18:15:37 +00005122 if (VD->getInit()) {
5123 GlobalVarDecl = VD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005124 CollectPropertySetters(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005125 CurrentBody = VD->getInit();
Steve Naroffd8907b72008-10-29 18:15:37 +00005126 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005127 CurrentBody = 0;
5128 if (PropParentMap) {
5129 delete PropParentMap;
5130 PropParentMap = 0;
5131 }
Mike Stump11289f42009-09-09 15:08:12 +00005132 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner86d7d912008-11-24 03:54:41 +00005133 VD->getNameAsCString());
Steve Naroffd8907b72008-10-29 18:15:37 +00005134 GlobalVarDecl = 0;
5135
5136 // This is needed for blocks.
Steve Naroffc989a7b2008-11-03 23:29:32 +00005137 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroffd8907b72008-10-29 18:15:37 +00005138 RewriteCastExpr(CE);
5139 }
5140 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005141 return;
5142 }
5143 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005144 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005145 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005146 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005147 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Steve Naroffe70a52a2009-12-05 15:55:59 +00005148 else if (TD->getUnderlyingType()->isRecordType()) {
5149 RecordDecl *RD = TD->getUnderlyingType()->getAs<RecordType>()->getDecl();
5150 if (RD->isDefinition())
5151 RewriteRecordBody(RD);
5152 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005153 return;
5154 }
5155 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroffe70a52a2009-12-05 15:55:59 +00005156 if (RD->isDefinition())
5157 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005158 return;
5159 }
5160 // Nothing yet.
5161}
5162
Chris Lattnercf169832009-03-28 04:11:33 +00005163void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005164 // Get the top-level buffer that this corresponds to.
Mike Stump11289f42009-09-09 15:08:12 +00005165
Steve Narofff4b992a2008-10-28 20:29:00 +00005166 // Rewrite tabs if we care.
5167 //RewriteTabs();
Mike Stump11289f42009-09-09 15:08:12 +00005168
Steve Narofff4b992a2008-10-28 20:29:00 +00005169 if (Diags.hasErrorOccurred())
5170 return;
Mike Stump11289f42009-09-09 15:08:12 +00005171
Steve Narofff4b992a2008-10-28 20:29:00 +00005172 RewriteInclude();
Mike Stump11289f42009-09-09 15:08:12 +00005173
Steve Naroffd9803712009-04-29 16:37:50 +00005174 // Here's a great place to add any extra declarations that may be needed.
5175 // Write out meta data for each @protocol(<expr>).
Mike Stump11289f42009-09-09 15:08:12 +00005176 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00005177 E = ProtocolExprDecls.end(); I != E; ++I)
5178 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5179
Mike Stump11289f42009-09-09 15:08:12 +00005180 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Narofff4b992a2008-10-28 20:29:00 +00005181 Preamble.c_str(), Preamble.size(), false);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005182 if (ClassImplementation.size() || CategoryImplementation.size())
5183 RewriteImplementations();
Steve Naroffd9803712009-04-29 16:37:50 +00005184
Steve Narofff4b992a2008-10-28 20:29:00 +00005185 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5186 // we are done.
Mike Stump11289f42009-09-09 15:08:12 +00005187 if (const RewriteBuffer *RewriteBuf =
Steve Narofff4b992a2008-10-28 20:29:00 +00005188 Rewrite.getRewriteBufferFor(MainFileID)) {
5189 //printf("Changed:\n");
5190 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5191 } else {
5192 fprintf(stderr, "No changes\n");
5193 }
Steve Narofff8cfd162008-11-13 20:07:04 +00005194
Steve Naroffd9803712009-04-29 16:37:50 +00005195 if (ClassImplementation.size() || CategoryImplementation.size() ||
5196 ProtocolExprDecls.size()) {
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005197 // Rewrite Objective-c meta data*
5198 std::string ResultStr;
5199 SynthesizeMetaDataIntoBuffer(ResultStr);
5200 // Emit metadata.
5201 *OutFile << ResultStr;
5202 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005203 OutFile->flush();
5204}
5205