blob: a13bccbb91ecf2b002ce3eb4b4cc5fe1e6bcace4 [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"
Fariborz Jahanianf4609d42010-03-01 23:36:21 +000029
Chris Lattnere99c8322007-10-11 00:43:27 +000030using namespace clang;
Chris Lattner211f8b82007-10-25 17:07:24 +000031using llvm::utostr;
Chris Lattnere99c8322007-10-11 00:43:27 +000032
Chris Lattnere99c8322007-10-11 00:43:27 +000033namespace {
Steve Naroff1dc53ef2008-04-14 22:03:09 +000034 class RewriteObjC : public ASTConsumer {
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000035 enum {
36 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
37 block, ... */
38 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
39 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
40 __block variable */
41 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
42 helpers */
43 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
44 support routines */
45 BLOCK_BYREF_CURRENT_MAX = 256
46 };
47
48 enum {
49 BLOCK_NEEDS_FREE = (1 << 24),
50 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
51 BLOCK_HAS_CXX_OBJ = (1 << 26),
52 BLOCK_IS_GC = (1 << 27),
53 BLOCK_IS_GLOBAL = (1 << 28),
54 BLOCK_HAS_DESCRIPTOR = (1 << 29)
55 };
56
Chris Lattner0bd1c972007-10-16 21:07:07 +000057 Rewriter Rewrite;
Chris Lattnere9c810c2007-11-30 22:25:36 +000058 Diagnostic &Diags;
Steve Naroff945a3b12008-03-10 20:43:59 +000059 const LangOptions &LangOpts;
Steve Naroff7b3579b2008-01-30 19:17:43 +000060 unsigned RewriteFailedDiag;
Steve Naroff6d6da252008-12-05 17:03:39 +000061 unsigned TryFinallyContainsReturnDiag;
Mike Stump11289f42009-09-09 15:08:12 +000062
Chris Lattnerc6d91c02007-10-17 22:35:30 +000063 ASTContext *Context;
Chris Lattnere99c8322007-10-11 00:43:27 +000064 SourceManager *SM;
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +000065 TranslationUnitDecl *TUDecl;
Chris Lattnerd32480d2009-01-17 06:22:33 +000066 FileID MainFileID;
Chris Lattnerf3a59a12007-12-02 01:13:47 +000067 const char *MainFileStart, *MainFileEnd;
Chris Lattner0bd1c972007-10-16 21:07:07 +000068 SourceLocation LastIncLoc;
Mike Stump11289f42009-09-09 15:08:12 +000069
Ted Kremenek1b0ea822008-01-07 19:49:32 +000070 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
71 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
72 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Naroff13e74872008-05-06 18:26:51 +000073 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremenek1b0ea822008-01-07 19:49:32 +000074 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
75 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +000076 llvm::SmallVector<Stmt *, 32> Stmts;
77 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffd9803712009-04-29 16:37:50 +000078 // Remember all the @protocol(<expr>) expressions.
79 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahaniane3891582010-01-05 18:04:40 +000080
81 llvm::DenseSet<uint64_t> CopyDestroyCache;
82
Steve Naroffce8e8862008-03-15 00:55:56 +000083 unsigned NumObjCStringLiterals;
Mike Stump11289f42009-09-09 15:08:12 +000084
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000085 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +000086 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +000087 FunctionDecl *MsgSendStretFunctionDecl;
88 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian4f76f222007-12-03 21:26:48 +000089 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000090 FunctionDecl *GetClassFunctionDecl;
Steve Naroffb2f8ff12007-12-07 03:50:46 +000091 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff574440f2007-10-24 22:48:43 +000092 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff265a6b92007-11-08 14:30:50 +000093 FunctionDecl *CFStringFunctionDecl;
Steve Naroff17978c42008-03-11 17:37:02 +000094 FunctionDecl *SuperContructorFunctionDecl;
Mike Stump11289f42009-09-09 15:08:12 +000095
Steve Naroffa397efd2007-11-03 11:27:19 +000096 // ObjC string constant support.
Steve Naroff08899ff2008-04-15 22:42:06 +000097 VarDecl *ConstantStringClassReference;
Steve Naroffa397efd2007-11-03 11:27:19 +000098 RecordDecl *NSStringRecord;
Mike Stump11289f42009-09-09 15:08:12 +000099
Fariborz Jahanian19d42bf2008-01-16 00:09:11 +0000100 // ObjC foreach break/continue generation support.
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000101 int BcLabelCount;
Mike Stump11289f42009-09-09 15:08:12 +0000102
Steve Naroff7fa2f042007-11-15 10:28:18 +0000103 // Needed for super.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000104 ObjCMethodDecl *CurMethodDef;
Steve Naroff7fa2f042007-11-15 10:28:18 +0000105 RecordDecl *SuperStructDecl;
Steve Naroffce8e8862008-03-15 00:55:56 +0000106 RecordDecl *ConstantStringDecl;
Mike Stump11289f42009-09-09 15:08:12 +0000107
Steve Naroffd9803712009-04-29 16:37:50 +0000108 TypeDecl *ProtocolTypeDecl;
109 QualType getProtocolType();
Mike Stump11289f42009-09-09 15:08:12 +0000110
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000111 // Needed for header files being rewritten
112 bool IsHeader;
Mike Stump11289f42009-09-09 15:08:12 +0000113
Steve Narofff9e7c902008-03-28 22:26:09 +0000114 std::string InFileName;
Eli Friedman94cf21e2009-05-18 22:20:00 +0000115 llvm::raw_ostream* OutFile;
Eli Friedmanf22439a2009-05-18 22:39:16 +0000116
117 bool SilenceRewriteMacroWarning;
Fariborz Jahanianbc6811c2010-01-07 22:51:18 +0000118 bool objc_impl_method;
Eli Friedmanf22439a2009-05-18 22:39:16 +0000119
Steve Naroff00a31762008-03-27 22:29:16 +0000120 std::string Preamble;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000121
122 // Block expressions.
123 llvm::SmallVector<BlockExpr *, 32> Blocks;
Fariborz Jahanian8652be02010-02-24 22:48:18 +0000124 llvm::SmallVector<int, 32> InnerDeclRefsCount;
125 llvm::SmallVector<BlockDeclRefExpr *, 32> InnerDeclRefs;
126
Steve Naroff677ab3a2008-10-27 17:20:55 +0000127 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
Mike Stump11289f42009-09-09 15:08:12 +0000128
Steve Naroff677ab3a2008-10-27 17:20:55 +0000129 // Block related declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +0000130 llvm::SmallVector<ValueDecl *, 8> BlockByCopyDecls;
131 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
132 llvm::SmallVector<ValueDecl *, 8> BlockByRefDecls;
133 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +0000134 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000135 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
136
137 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
138
Steve Naroff4588d0f2008-12-04 16:24:46 +0000139 // This maps a property to it's assignment statement.
140 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Naroff1042ff32008-12-08 16:43:47 +0000141 // This maps a property to it's synthesied message expression.
142 // This allows us to rewrite chained getters (e.g. o.a.b.c).
143 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
Mike Stump11289f42009-09-09 15:08:12 +0000144
Steve Naroff22216db2008-12-04 23:50:32 +0000145 // This maps an original source AST to it's rewritten form. This allows
146 // us to avoid rewriting the same node twice (which is very uncommon).
147 // This is needed to support some of the exotic property rewriting.
148 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Narofff326f402008-12-03 00:56:33 +0000149
Steve Naroff677ab3a2008-10-27 17:20:55 +0000150 FunctionDecl *CurFunctionDef;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000151 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Steve Naroffd8907b72008-10-29 18:15:37 +0000152 VarDecl *GlobalVarDecl;
Mike Stump11289f42009-09-09 15:08:12 +0000153
Steve Naroff08628db2008-12-09 12:56:34 +0000154 bool DisableReplaceStmt;
Mike Stump11289f42009-09-09 15:08:12 +0000155
Fariborz Jahanian93191af2007-10-18 19:23:00 +0000156 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnere99c8322007-10-11 00:43:27 +0000157 public:
Ted Kremenek380df932008-05-31 20:11:04 +0000158 virtual void Initialize(ASTContext &context);
159
Chris Lattner3c799d72007-10-24 17:06:59 +0000160 // Top Level Driver code.
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000161 virtual void HandleTopLevelDecl(DeclGroupRef D) {
162 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
163 HandleTopLevelSingleDecl(*I);
164 }
165 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000166 void HandleDeclInMainFile(Decl *D);
Eli Friedman94cf21e2009-05-18 22:20:00 +0000167 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000168 Diagnostic &D, const LangOptions &LOpts,
169 bool silenceMacroWarn);
Ted Kremenek6231e7e2008-08-08 04:15:52 +0000170
171 ~RewriteObjC() {}
Mike Stump11289f42009-09-09 15:08:12 +0000172
Chris Lattnercf169832009-03-28 04:11:33 +0000173 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump11289f42009-09-09 15:08:12 +0000174
Fariborz Jahaniana7e1dcd2010-02-05 16:43:40 +0000175 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff22216db2008-12-04 23:50:32 +0000176 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump11289f42009-09-09 15:08:12 +0000177
Steve Naroff22216db2008-12-04 23:50:32 +0000178 if (ReplacingStmt)
179 return; // We can't rewrite the same node twice.
Chris Lattner2e0d2602008-01-31 19:37:57 +0000180
Steve Naroff08628db2008-12-09 12:56:34 +0000181 if (DisableReplaceStmt)
182 return; // Used when rewriting the assignment of a property setter.
183
Steve Naroff22216db2008-12-04 23:50:32 +0000184 // If replacement succeeded or warning disabled return with no warning.
Fariborz Jahaniana7e1dcd2010-02-05 16:43:40 +0000185 if (!Rewrite.ReplaceStmt(Old, New)) {
Steve Naroff22216db2008-12-04 23:50:32 +0000186 ReplacedNodes[Old] = New;
187 return;
188 }
189 if (SilenceRewriteMacroWarning)
190 return;
Chris Lattner8488c822008-11-18 07:04:44 +0000191 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
192 << Old->getSourceRange();
Chris Lattner2e0d2602008-01-31 19:37:57 +0000193 }
Steve Naroff08628db2008-12-09 12:56:34 +0000194
195 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
196 // Measaure the old text.
197 int Size = Rewrite.getRangeSize(SrcRange);
198 if (Size == -1) {
199 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
200 << Old->getSourceRange();
201 return;
202 }
203 // Get the new text.
204 std::string SStr;
205 llvm::raw_string_ostream S(SStr);
Chris Lattnerc61089a2009-06-30 01:26:17 +0000206 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroff08628db2008-12-09 12:56:34 +0000207 const std::string &Str = S.str();
208
209 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000210 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroff08628db2008-12-09 12:56:34 +0000211 ReplacedNodes[Old] = New;
212 return;
213 }
214 if (SilenceRewriteMacroWarning)
215 return;
216 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
217 << Old->getSourceRange();
218 }
219
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000220 void InsertText(SourceLocation Loc, llvm::StringRef Str,
Steve Naroff00a31762008-03-27 22:29:16 +0000221 bool InsertAfter = true) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000222 // If insertion succeeded or warning disabled return with no warning.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000223 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
Chris Lattner1780a852008-01-31 19:42:41 +0000224 SilenceRewriteMacroWarning)
225 return;
Mike Stump11289f42009-09-09 15:08:12 +0000226
Chris Lattner1780a852008-01-31 19:42:41 +0000227 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
228 }
Mike Stump11289f42009-09-09 15:08:12 +0000229
Chris Lattner9cc55f52008-01-31 19:51:04 +0000230 void RemoveText(SourceLocation Loc, unsigned StrLen) {
231 // If removal succeeded or warning disabled return with no warning.
232 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
233 return;
Mike Stump11289f42009-09-09 15:08:12 +0000234
Chris Lattner9cc55f52008-01-31 19:51:04 +0000235 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
236 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000237
Chris Lattner9cc55f52008-01-31 19:51:04 +0000238 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000239 llvm::StringRef Str) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000240 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000241 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattner9cc55f52008-01-31 19:51:04 +0000242 SilenceRewriteMacroWarning)
243 return;
Mike Stump11289f42009-09-09 15:08:12 +0000244
Chris Lattner9cc55f52008-01-31 19:51:04 +0000245 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
246 }
Mike Stump11289f42009-09-09 15:08:12 +0000247
Chris Lattner3c799d72007-10-24 17:06:59 +0000248 // Syntactic Rewriting.
Steve Narofff36987c2007-11-04 22:37:50 +0000249 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000250 void RewriteInclude();
Chris Lattner3c799d72007-10-24 17:06:59 +0000251 void RewriteTabs();
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000252 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffc038b3a2008-12-02 17:36:43 +0000253 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
254 ObjCImplementationDecl *IMD,
255 ObjCCategoryImplDecl *CID);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000256 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000257 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000258 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000259 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
260 const FunctionType *&FPRetType);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +0000261 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
262 ValueDecl *VD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000263 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
264 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
265 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
266 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000267 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000268 void RewriteFunctionDecl(FunctionDecl *FD);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000269 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000270 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +0000271 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff873bd842008-07-29 18:15:38 +0000272 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroff50d42052007-11-01 13:24:47 +0000273 bool needToScanForQualifiers(QualType T);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000274 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff7fa2f042007-11-15 10:28:18 +0000275 QualType getSuperStructType();
Steve Naroffce8e8862008-03-15 00:55:56 +0000276 QualType getConstantStringStructType();
Steve Naroffcd92aeb2008-05-31 14:15:04 +0000277 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump11289f42009-09-09 15:08:12 +0000278
Chris Lattner3c799d72007-10-24 17:06:59 +0000279 // Expression Rewriting.
Steve Naroff20113382007-11-09 15:20:18 +0000280 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroff4588d0f2008-12-04 16:24:46 +0000281 void CollectPropertySetters(Stmt *S);
Mike Stump11289f42009-09-09 15:08:12 +0000282
Steve Naroff1042ff32008-12-08 16:43:47 +0000283 Stmt *CurrentBody;
284 ParentMap *PropParentMap; // created lazily.
Mike Stump11289f42009-09-09 15:08:12 +0000285
Chris Lattner69534692007-10-24 16:57:36 +0000286 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +0000287 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart,
288 bool &replaced);
289 Stmt *RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced);
Steve Naroff4588d0f2008-12-04 16:24:46 +0000290 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Mike Stump11289f42009-09-09 15:08:12 +0000291 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroff08628db2008-12-09 12:56:34 +0000292 SourceRange SrcRange);
Steve Naroffe4f9b232007-11-05 14:50:49 +0000293 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner69534692007-10-24 16:57:36 +0000294 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffa397efd2007-11-03 11:27:19 +0000295 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian33c0e812007-12-07 18:47:10 +0000296 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffec60b432009-12-05 21:43:12 +0000297 void WarnAboutReturnGotoStmts(Stmt *S);
298 void HasReturnStmts(Stmt *S, bool &hasReturns);
299 void RewriteTryReturnStmts(Stmt *S);
300 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000301 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian284011b2008-01-29 22:59:37 +0000302 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000303 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
304 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
305 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattnera779d692008-01-31 05:10:40 +0000306 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
307 SourceLocation OrigEnd);
Mike Stump11289f42009-09-09 15:08:12 +0000308 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +0000309 Expr **args, unsigned nargs,
310 SourceLocation StartLoc=SourceLocation(),
311 SourceLocation EndLoc=SourceLocation());
312 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
313 SourceLocation StartLoc=SourceLocation(),
314 SourceLocation EndLoc=SourceLocation());
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000315 Stmt *RewriteBreakStmt(BreakStmt *S);
316 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian965a8962008-01-08 22:06:28 +0000317 void SynthCountByEnumWithState(std::string &buf);
Mike Stump11289f42009-09-09 15:08:12 +0000318
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000319 void SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +0000320 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000321 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +0000322 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000323 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000324 void SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +0000325 void SynthGetMetaClassFunctionDecl();
Fariborz Jahanian31e18502007-12-04 21:47:40 +0000326 void SynthSelGetUidFunctionDecl();
Steve Naroff17978c42008-03-11 17:37:02 +0000327 void SynthSuperContructorFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000328
Chris Lattner3c799d72007-10-24 17:06:59 +0000329 // Metadata emission.
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000330 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000331 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000332
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000333 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000334 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000335
Douglas Gregor29bd76f2009-04-23 01:02:12 +0000336 template<typename MethodIterator>
337 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
338 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +0000339 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +0000340 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +0000341 const char *ClassName,
342 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000343
Steve Naroffd9803712009-04-29 16:37:50 +0000344 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
345 const char *prefix,
346 const char *ClassName,
347 std::string &Result);
348 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Mike Stump11289f42009-09-09 15:08:12 +0000349 const char *prefix,
Steve Naroffd9803712009-04-29 16:37:50 +0000350 const char *ClassName,
351 std::string &Result);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000352 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000353 std::string &Result);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000354 void SynthesizeIvarOffsetComputation(ObjCContainerDecl *IDecl,
Mike Stump11289f42009-09-09 15:08:12 +0000355 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000356 std::string &Result);
Steve Narofff8cfd162008-11-13 20:07:04 +0000357 void RewriteImplementations();
358 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000359
Steve Naroff677ab3a2008-10-27 17:20:55 +0000360 // Block rewriting.
Mike Stump11289f42009-09-09 15:08:12 +0000361 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000362 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump11289f42009-09-09 15:08:12 +0000363
Steve Naroff677ab3a2008-10-27 17:20:55 +0000364 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
365 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump11289f42009-09-09 15:08:12 +0000366
367 // Block specific rewrite rules.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000368 void RewriteBlockCall(CallExpr *Exp);
369 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000370 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahaniane3891582010-01-05 18:04:40 +0000371 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +0000372 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000373 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump11289f42009-09-09 15:08:12 +0000374
375 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000376 const char *funcName, std::string Tag);
Mike Stump11289f42009-09-09 15:08:12 +0000377 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000378 const char *funcName, std::string Tag);
Steve Naroff30484702009-12-06 21:14:13 +0000379 std::string SynthesizeBlockImpl(BlockExpr *CE,
380 std::string Tag, std::string Desc);
381 std::string SynthesizeBlockDescriptor(std::string DescTag,
382 std::string ImplTag,
383 int i, const char *funcName,
384 unsigned hasCopy);
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +0000385 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000386 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000387 const char *FunName);
Steve Naroffe70a52a2009-12-05 15:55:59 +0000388 void RewriteRecordBody(RecordDecl *RD);
Mike Stump11289f42009-09-09 15:08:12 +0000389
Steve Naroff677ab3a2008-10-27 17:20:55 +0000390 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000391 void GetBlockDeclRefExprs(Stmt *S);
Fariborz Jahanian8652be02010-02-24 22:48:18 +0000392 void GetInnerBlockDeclRefExprs(Stmt *S,
393 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +0000394 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
Mike Stump11289f42009-09-09 15:08:12 +0000395
Steve Naroff677ab3a2008-10-27 17:20:55 +0000396 // We avoid calling Type::isBlockPointerType(), since it operates on the
397 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek5a201952009-02-07 01:47:29 +0000398 bool isTopLevelBlockPointerType(QualType T) {
399 return isa<BlockPointerType>(T);
400 }
Mike Stump11289f42009-09-09 15:08:12 +0000401
Steve Naroff677ab3a2008-10-27 17:20:55 +0000402 // FIXME: This predicate seems like it would be useful to add to ASTContext.
403 bool isObjCType(QualType T) {
404 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
405 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000406
Steve Naroff677ab3a2008-10-27 17:20:55 +0000407 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000408
Steve Naroff677ab3a2008-10-27 17:20:55 +0000409 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
410 OCT == Context->getCanonicalType(Context->getObjCClassType()))
411 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000412
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000413 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +0000414 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Narofffb4330f2009-06-17 22:40:22 +0000415 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff677ab3a2008-10-27 17:20:55 +0000416 return true;
417 }
418 return false;
419 }
420 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek5a201952009-02-07 01:47:29 +0000421 void GetExtentOfArgList(const char *Name, const char *&LParen,
422 const char *&RParen);
Steve Naroffc989a7b2008-11-03 23:29:32 +0000423 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump11289f42009-09-09 15:08:12 +0000424
Steve Narofff4b992a2008-10-28 20:29:00 +0000425 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Fariborz Jahanian8652be02010-02-24 22:48:18 +0000426 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
427 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
Mike Stump11289f42009-09-09 15:08:12 +0000428
Steve Naroffd9803712009-04-29 16:37:50 +0000429 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump11289f42009-09-09 15:08:12 +0000430 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroffd9803712009-04-29 16:37:50 +0000431 if (From[i] == '"')
432 To += "\\\"";
433 else
434 To += From[i];
435 }
436 }
Chris Lattnere99c8322007-10-11 00:43:27 +0000437 };
John McCall97513962010-01-15 18:39:57 +0000438
439 // Helper function: create a CStyleCastExpr with trivial type source info.
440 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
441 CastExpr::CastKind Kind, Expr *E) {
442 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
443 return new (Ctx) CStyleCastExpr(Ty, Kind, E, TInfo,
444 SourceLocation(), SourceLocation());
445 }
Chris Lattnere99c8322007-10-11 00:43:27 +0000446}
447
Mike Stump11289f42009-09-09 15:08:12 +0000448void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
449 NamedDecl *D) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000450 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000451 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +0000452 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +0000453 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +0000454 // All the args are checked/rewritten. Don't call twice!
455 RewriteBlockPointerDecl(D);
456 break;
457 }
458 }
459}
460
461void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000462 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +0000463 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000464 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000465}
466
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000467static bool IsHeaderFile(const std::string &Filename) {
468 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump11289f42009-09-09 15:08:12 +0000469
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000470 if (DotPos == std::string::npos) {
471 // no file extension
Mike Stump11289f42009-09-09 15:08:12 +0000472 return false;
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000473 }
Mike Stump11289f42009-09-09 15:08:12 +0000474
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000475 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
476 // C header: .h
477 // C++ header: .hh or .H;
478 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump11289f42009-09-09 15:08:12 +0000479}
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000480
Eli Friedman94cf21e2009-05-18 22:20:00 +0000481RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000482 Diagnostic &D, const LangOptions &LOpts,
483 bool silenceMacroWarn)
484 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
485 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Narofff9e7c902008-03-28 22:26:09 +0000486 IsHeader = IsHeaderFile(inFile);
Mike Stump11289f42009-09-09 15:08:12 +0000487 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Narofff9e7c902008-03-28 22:26:09 +0000488 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump11289f42009-09-09 15:08:12 +0000489 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek5a201952009-02-07 01:47:29 +0000490 "rewriter doesn't support user-specified control flow semantics "
491 "for @try/@finally (code may not execute properly)");
Steve Narofff9e7c902008-03-28 22:26:09 +0000492}
493
Eli Friedmana63ab2d2009-05-18 22:29:17 +0000494ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
495 llvm::raw_ostream* OS,
Mike Stump11289f42009-09-09 15:08:12 +0000496 Diagnostic &Diags,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000497 const LangOptions &LOpts,
498 bool SilenceRewriteMacroWarning) {
499 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere9c810c2007-11-30 22:25:36 +0000500}
Chris Lattnere99c8322007-10-11 00:43:27 +0000501
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000502void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner187f6262008-01-31 19:38:44 +0000503 Context = &context;
504 SM = &Context->getSourceManager();
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +0000505 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner187f6262008-01-31 19:38:44 +0000506 MsgSendFunctionDecl = 0;
507 MsgSendSuperFunctionDecl = 0;
508 MsgSendStretFunctionDecl = 0;
509 MsgSendSuperStretFunctionDecl = 0;
510 MsgSendFpretFunctionDecl = 0;
511 GetClassFunctionDecl = 0;
512 GetMetaClassFunctionDecl = 0;
513 SelGetUidFunctionDecl = 0;
514 CFStringFunctionDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000515 ConstantStringClassReference = 0;
516 NSStringRecord = 0;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000517 CurMethodDef = 0;
518 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000519 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000520 GlobalVarDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000521 SuperStructDecl = 0;
Steve Naroffd9803712009-04-29 16:37:50 +0000522 ProtocolTypeDecl = 0;
Steve Naroff60a9ef62008-03-27 22:59:54 +0000523 ConstantStringDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000524 BcLabelCount = 0;
Steve Naroff17978c42008-03-11 17:37:02 +0000525 SuperContructorFunctionDecl = 0;
Steve Naroffce8e8862008-03-15 00:55:56 +0000526 NumObjCStringLiterals = 0;
Steve Narofff1ab6002008-12-08 20:01:41 +0000527 PropParentMap = 0;
528 CurrentBody = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000529 DisableReplaceStmt = false;
Fariborz Jahanianbc6811c2010-01-07 22:51:18 +0000530 objc_impl_method = false;
Mike Stump11289f42009-09-09 15:08:12 +0000531
Chris Lattner187f6262008-01-31 19:38:44 +0000532 // Get the ID and start/end of the main file.
533 MainFileID = SM->getMainFileID();
534 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
535 MainFileStart = MainBuf->getBufferStart();
536 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000537
Chris Lattner184e65d2009-04-14 23:22:57 +0000538 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump11289f42009-09-09 15:08:12 +0000539
Chris Lattner187f6262008-01-31 19:38:44 +0000540 // declaring objc_selector outside the parameter list removes a silly
541 // scope related warning...
Steve Naroff00a31762008-03-27 22:29:16 +0000542 if (IsHeader)
Steve Narofffcc6fd52009-02-03 20:39:18 +0000543 Preamble = "#pragma once\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000544 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff6ab6dc72008-12-23 20:11:22 +0000545 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroff00a31762008-03-27 22:29:16 +0000546 Preamble += "struct objc_object *superClass; ";
Steve Naroff17978c42008-03-11 17:37:02 +0000547 if (LangOpts.Microsoft) {
548 // Add a constructor for creating temporary objects.
Ted Kremenek5a201952009-02-07 01:47:29 +0000549 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
550 ": ";
Steve Naroff00a31762008-03-27 22:29:16 +0000551 Preamble += "object(o), superClass(s) {} ";
Steve Naroff17978c42008-03-11 17:37:02 +0000552 }
Steve Naroff00a31762008-03-27 22:29:16 +0000553 Preamble += "};\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000554 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
555 Preamble += "typedef struct objc_object Protocol;\n";
556 Preamble += "#define _REWRITER_typedef_Protocol\n";
557 Preamble += "#endif\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000558 if (LangOpts.Microsoft) {
559 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
560 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
561 } else
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000562 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000563 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroff00a31762008-03-27 22:29:16 +0000564 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000565 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroff00a31762008-03-27 22:29:16 +0000566 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000567 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000568 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000569 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000570 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000571 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroff00a31762008-03-27 22:29:16 +0000572 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000573 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000574 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000575 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000576 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000577 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
578 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
579 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
580 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
581 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroffd30f8c52008-05-09 21:17:56 +0000582 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff8dd15252008-07-16 18:58:11 +0000583 // @synchronized hooks.
Steve Narofff122ff02008-12-08 17:30:33 +0000584 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
585 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
586 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000587 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
588 Preamble += "struct __objcFastEnumerationState {\n\t";
589 Preamble += "unsigned long state;\n\t";
Steve Naroff4dbab8a2008-04-04 22:58:22 +0000590 Preamble += "void **itemsPtr;\n\t";
Steve Naroff00a31762008-03-27 22:29:16 +0000591 Preamble += "unsigned long *mutationsPtr;\n\t";
592 Preamble += "unsigned long extra[5];\n};\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000593 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000594 Preamble += "#define __FASTENUMERATIONSTATE\n";
595 Preamble += "#endif\n";
596 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
597 Preamble += "struct __NSConstantStringImpl {\n";
598 Preamble += " int *isa;\n";
599 Preamble += " int flags;\n";
600 Preamble += " char *str;\n";
601 Preamble += " long length;\n";
602 Preamble += "};\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000603 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
604 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
605 Preamble += "#else\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000606 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000607 Preamble += "#endif\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000608 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
609 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000610 // Blocks preamble.
611 Preamble += "#ifndef BLOCK_IMPL\n";
612 Preamble += "#define BLOCK_IMPL\n";
613 Preamble += "struct __block_impl {\n";
614 Preamble += " void *isa;\n";
615 Preamble += " int Flags;\n";
Steve Naroff30484702009-12-06 21:14:13 +0000616 Preamble += " int Reserved;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000617 Preamble += " void *FuncPtr;\n";
618 Preamble += "};\n";
Steve Naroff61d879e2008-12-16 15:50:30 +0000619 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroff287a2bf2009-12-06 01:52:22 +0000620 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000621 Preamble += "extern \"C\" __declspec(dllexport) "
622 "void _Block_object_assign(void *, const void *, const int);\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000623 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
624 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
625 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
626 Preamble += "#else\n";
Steve Naroff7bf01ea2010-01-05 18:09:31 +0000627 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
628 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000629 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
630 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
631 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000632 Preamble += "#endif\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000633 if (LangOpts.Microsoft) {
Steve Narofff122ff02008-12-08 17:30:33 +0000634 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
635 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000636 Preamble += "#define __attribute__(X)\n";
Fariborz Jahanianf0462ff2010-01-15 22:29:39 +0000637 Preamble += "#define __weak\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000638 }
Fariborz Jahanian7fac6552010-01-05 19:21:35 +0000639 else {
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000640 Preamble += "#define __block\n";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +0000641 Preamble += "#define __weak\n";
642 }
Fariborz Jahaniandb217c42010-03-02 01:19:04 +0000643 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
644 // as this avoids warning in any 64bit/32bit compilation model.
645 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
Chris Lattner187f6262008-01-31 19:38:44 +0000646}
647
648
Chris Lattner3c799d72007-10-24 17:06:59 +0000649//===----------------------------------------------------------------------===//
650// Top Level Driver Code
651//===----------------------------------------------------------------------===//
652
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000653void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremenek31e7f0f2010-02-05 21:28:51 +0000654 if (Diags.hasErrorOccurred())
655 return;
656
Chris Lattner0bd1c972007-10-16 21:07:07 +0000657 // Two cases: either the decl could be in the main file, or it could be in a
658 // #included file. If the former, rewrite it now. If the later, check to see
659 // if we rewrote the #include/#import.
660 SourceLocation Loc = D->getLocation();
Chris Lattner8a425862009-01-16 07:36:28 +0000661 Loc = SM->getInstantiationLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000662
Chris Lattner0bd1c972007-10-16 21:07:07 +0000663 // If this is for a builtin, ignore it.
664 if (Loc.isInvalid()) return;
665
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000666 // Look for built-in declarations that we need to refer during the rewrite.
667 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000668 RewriteFunctionDecl(FD);
Steve Naroff08899ff2008-04-15 22:42:06 +0000669 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000670 // declared in <Foundation/NSString.h>
Chris Lattner86d7d912008-11-24 03:54:41 +0000671 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000672 ConstantStringClassReference = FVD;
673 return;
674 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000675 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff161a92b2007-10-26 20:53:56 +0000676 RewriteInterfaceDecl(MD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000677 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000678 RewriteCategoryDecl(CD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000679 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff921385f2007-10-30 16:42:30 +0000680 RewriteProtocolDecl(PD);
Mike Stump11289f42009-09-09 15:08:12 +0000681 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000682 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000683 RewriteForwardProtocolDecl(FP);
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000684 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
685 // Recurse into linkage specifications
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000686 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
687 DIEnd = LSD->decls_end();
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000688 DI != DIEnd; ++DI)
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000689 HandleTopLevelSingleDecl(*DI);
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000690 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000691 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekd61ed3b2008-04-14 21:24:13 +0000692 if (SM->isFromMainFile(Loc))
Chris Lattner0bd1c972007-10-16 21:07:07 +0000693 return HandleDeclInMainFile(D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000694}
695
Chris Lattner3c799d72007-10-24 17:06:59 +0000696//===----------------------------------------------------------------------===//
697// Syntactic (non-AST) Rewriting Code
698//===----------------------------------------------------------------------===//
699
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000700void RewriteObjC::RewriteInclude() {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000701 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000702 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
703 const char *MainBufStart = MainBuf.first;
704 const char *MainBufEnd = MainBuf.second;
705 size_t ImportLen = strlen("import");
Mike Stump11289f42009-09-09 15:08:12 +0000706
Fariborz Jahanian137d6932008-01-19 01:03:17 +0000707 // Loop over the whole file, looking for includes.
Fariborz Jahanian80258362008-01-19 00:30:35 +0000708 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
709 if (*BufPtr == '#') {
710 if (++BufPtr == MainBufEnd)
711 return;
712 while (*BufPtr == ' ' || *BufPtr == '\t')
713 if (++BufPtr == MainBufEnd)
714 return;
715 if (!strncmp(BufPtr, "import", ImportLen)) {
716 // replace import with include
Mike Stump11289f42009-09-09 15:08:12 +0000717 SourceLocation ImportLoc =
Fariborz Jahanian80258362008-01-19 00:30:35 +0000718 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000719 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian80258362008-01-19 00:30:35 +0000720 BufPtr += ImportLen;
721 }
722 }
723 }
Chris Lattner0bd1c972007-10-16 21:07:07 +0000724}
725
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000726void RewriteObjC::RewriteTabs() {
Chris Lattner3c799d72007-10-24 17:06:59 +0000727 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
728 const char *MainBufStart = MainBuf.first;
729 const char *MainBufEnd = MainBuf.second;
Mike Stump11289f42009-09-09 15:08:12 +0000730
Chris Lattner3c799d72007-10-24 17:06:59 +0000731 // Loop over the whole file, looking for tabs.
732 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
733 if (*BufPtr != '\t')
734 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000735
Chris Lattner3c799d72007-10-24 17:06:59 +0000736 // Okay, we found a tab. This tab will turn into at least one character,
737 // but it depends on which 'virtual column' it is in. Compute that now.
738 unsigned VCol = 0;
739 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
740 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
741 ++VCol;
Mike Stump11289f42009-09-09 15:08:12 +0000742
Chris Lattner3c799d72007-10-24 17:06:59 +0000743 // Okay, now that we know the virtual column, we know how many spaces to
744 // insert. We assume 8-character tab-stops.
745 unsigned Spaces = 8-(VCol & 7);
Mike Stump11289f42009-09-09 15:08:12 +0000746
Chris Lattner3c799d72007-10-24 17:06:59 +0000747 // Get the location of the tab.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000748 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
749 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Mike Stump11289f42009-09-09 15:08:12 +0000750
Chris Lattner3c799d72007-10-24 17:06:59 +0000751 // Rewrite the single tab character into a sequence of spaces.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000752 ReplaceText(TabLoc, 1, llvm::StringRef(" ", Spaces));
Chris Lattner3c799d72007-10-24 17:06:59 +0000753 }
Chris Lattner16a0de42007-10-11 18:38:32 +0000754}
755
Steve Naroff9af94912008-12-02 15:48:25 +0000756static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
757 ObjCIvarDecl *OID) {
758 std::string S;
759 S = "((struct ";
760 S += ClassDecl->getIdentifier()->getName();
761 S += "_IMPL *)self)->";
Daniel Dunbar70e7ead2009-10-18 20:26:27 +0000762 S += OID->getName();
Steve Naroff9af94912008-12-02 15:48:25 +0000763 return S;
764}
765
Steve Naroffc038b3a2008-12-02 17:36:43 +0000766void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
767 ObjCImplementationDecl *IMD,
768 ObjCCategoryImplDecl *CID) {
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000769 static bool objcGetPropertyDefined = false;
770 static bool objcSetPropertyDefined = false;
Steve Naroffe1908e32008-12-01 20:33:01 +0000771 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000772 InsertText(startLoc, "// ");
Steve Naroff9af94912008-12-02 15:48:25 +0000773 const char *startBuf = SM->getCharacterData(startLoc);
774 assert((*startBuf == '@') && "bogus @synthesize location");
775 const char *semiBuf = strchr(startBuf, ';');
776 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek5a201952009-02-07 01:47:29 +0000777 SourceLocation onePastSemiLoc =
778 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroff9af94912008-12-02 15:48:25 +0000779
780 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
781 return; // FIXME: is this correct?
Mike Stump11289f42009-09-09 15:08:12 +0000782
Steve Naroff9af94912008-12-02 15:48:25 +0000783 // Generate the 'getter' function.
Steve Naroff9af94912008-12-02 15:48:25 +0000784 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroff9af94912008-12-02 15:48:25 +0000785 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroff9af94912008-12-02 15:48:25 +0000786 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000787
Steve Naroff003d00e2008-12-02 16:05:55 +0000788 if (!OID)
789 return;
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000790 unsigned Attributes = PD->getPropertyAttributes();
791 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
792 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
793 ObjCPropertyDecl::OBJC_PR_copy));
Steve Naroff003d00e2008-12-02 16:05:55 +0000794 std::string Getr;
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000795 if (GenGetProperty && !objcGetPropertyDefined) {
796 objcGetPropertyDefined = true;
797 // FIXME. Is this attribute correct in all cases?
798 Getr = "\nextern \"C\" __declspec(dllimport) "
799 "id objc_getProperty(id, SEL, long, bool);\n";
800 }
Steve Naroff003d00e2008-12-02 16:05:55 +0000801 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
802 Getr += "{ ";
803 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff06297042008-12-02 17:54:50 +0000804 // See objc-act.c:objc_synthesize_new_getter() for details.
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000805 if (GenGetProperty) {
806 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
807 Getr += "typedef ";
808 const FunctionType *FPRetType = 0;
809 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
810 FPRetType);
811 Getr += " _TYPE";
812 if (FPRetType) {
813 Getr += ")"; // close the precedence "scope" for "*".
814
815 // Now, emit the argument types (if any).
816 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
817 Getr += "(";
818 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
819 if (i) Getr += ", ";
820 std::string ParamStr = FT->getArgType(i).getAsString();
821 Getr += ParamStr;
822 }
823 if (FT->isVariadic()) {
824 if (FT->getNumArgs()) Getr += ", ";
825 Getr += "...";
826 }
827 Getr += ")";
828 } else
829 Getr += "()";
830 }
831 Getr += ";\n";
832 Getr += "return (_TYPE)";
833 Getr += "objc_getProperty(self, _cmd, ";
834 SynthesizeIvarOffsetComputation(ClassDecl, OID, Getr);
835 Getr += ", 1)";
836 }
837 else
838 Getr += "return " + getIvarAccessString(ClassDecl, OID);
Steve Naroff003d00e2008-12-02 16:05:55 +0000839 Getr += "; }";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000840 InsertText(onePastSemiLoc, Getr);
Steve Naroff9af94912008-12-02 15:48:25 +0000841 if (PD->isReadOnly())
842 return;
Mike Stump11289f42009-09-09 15:08:12 +0000843
Steve Naroff9af94912008-12-02 15:48:25 +0000844 // Generate the 'setter' function.
845 std::string Setr;
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000846 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
847 ObjCPropertyDecl::OBJC_PR_copy);
848 if (GenSetProperty && !objcSetPropertyDefined) {
849 objcSetPropertyDefined = true;
850 // FIXME. Is this attribute correct in all cases?
851 Setr = "\nextern \"C\" __declspec(dllimport) "
852 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
853 }
854
Steve Naroff9af94912008-12-02 15:48:25 +0000855 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroff9af94912008-12-02 15:48:25 +0000856 Setr += "{ ";
Steve Naroff003d00e2008-12-02 16:05:55 +0000857 // Synthesize an explicit cast to initialize the ivar.
Steve Narofff326f402008-12-03 00:56:33 +0000858 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000859 if (GenSetProperty) {
860 Setr += "objc_setProperty (self, _cmd, ";
861 SynthesizeIvarOffsetComputation(ClassDecl, OID, Setr);
862 Setr += ", (id)";
863 Setr += PD->getNameAsCString();
864 Setr += ", ";
865 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
866 Setr += "0, ";
867 else
868 Setr += "1, ";
869 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
870 Setr += "1)";
871 else
872 Setr += "0)";
873 }
874 else {
875 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
876 Setr += PD->getNameAsCString();
877 }
Steve Naroff003d00e2008-12-02 16:05:55 +0000878 Setr += "; }";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000879 InsertText(onePastSemiLoc, Setr);
Steve Naroffe1908e32008-12-01 20:33:01 +0000880}
Chris Lattner16a0de42007-10-11 18:38:32 +0000881
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000882void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattner3c799d72007-10-24 17:06:59 +0000883 // Get the start location and compute the semi location.
884 SourceLocation startLoc = ClassDecl->getLocation();
885 const char *startBuf = SM->getCharacterData(startLoc);
886 const char *semiPtr = strchr(startBuf, ';');
Mike Stump11289f42009-09-09 15:08:12 +0000887
Chris Lattner3c799d72007-10-24 17:06:59 +0000888 // Translate to typedef's that forward reference structs with the same name
889 // as the class. As a convenience, we include the original declaration
890 // as a comment.
891 std::string typedefString;
Fariborz Jahanian1c2cb6d2010-01-11 22:48:40 +0000892 typedefString += "// @class ";
893 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
894 I != E; ++I) {
895 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
896 typedefString += ForwardDecl->getNameAsString();
897 if (I+1 != E)
898 typedefString += ", ";
899 else
900 typedefString += ";\n";
901 }
902
Chris Lattner9ee23b72009-02-20 18:04:31 +0000903 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
904 I != E; ++I) {
Ted Kremenek9b124e12009-11-18 00:28:11 +0000905 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff1b232132007-11-09 12:50:28 +0000906 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000907 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000908 typedefString += "\n";
909 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000910 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000911 typedefString += "\n";
Steve Naroff98eb8d12007-11-05 14:36:37 +0000912 typedefString += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000913 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000914 typedefString += ";\n#endif\n";
Steve Naroff574440f2007-10-24 22:48:43 +0000915 }
Mike Stump11289f42009-09-09 15:08:12 +0000916
Steve Naroff574440f2007-10-24 22:48:43 +0000917 // Replace the @class with typedefs corresponding to the classes.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000918 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
Chris Lattner3c799d72007-10-24 17:06:59 +0000919}
920
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000921void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000922 // When method is a synthesized one, such as a getter/setter there is
923 // nothing to rewrite.
924 if (Method->isSynthesized())
925 return;
Steve Naroff3ce37a62007-12-14 23:37:57 +0000926 SourceLocation LocStart = Method->getLocStart();
927 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000928
Chris Lattner88ea93e2009-02-04 01:06:56 +0000929 if (SM->getInstantiationLineNumber(LocEnd) >
930 SM->getInstantiationLineNumber(LocStart)) {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000931 InsertText(LocStart, "#if 0\n");
932 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff3ce37a62007-12-14 23:37:57 +0000933 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000934 InsertText(LocStart, "// ");
Steve Naroff5448cf62007-10-30 13:30:57 +0000935 }
936}
937
Mike Stump11289f42009-09-09 15:08:12 +0000938void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000939 SourceLocation Loc = prop->getAtLoc();
Mike Stump11289f42009-09-09 15:08:12 +0000940
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000941 ReplaceText(Loc, 0, "// ");
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000942 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahaniane8a30162007-11-07 00:09:37 +0000943}
944
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000945void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000946 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000947
Steve Naroff5448cf62007-10-30 13:30:57 +0000948 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000949 ReplaceText(LocStart, 0, "// ");
Mike Stump11289f42009-09-09 15:08:12 +0000950
Fariborz Jahanian68ebe632010-02-10 01:15:09 +0000951 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
952 E = CatDecl->prop_end(); I != E; ++I)
953 RewriteProperty(*I);
954
Mike Stump11289f42009-09-09 15:08:12 +0000955 for (ObjCCategoryDecl::instmeth_iterator
956 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000957 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000958 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +0000959 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000960 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000961 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000962 RewriteMethodDeclaration(*I);
963
Steve Naroff5448cf62007-10-30 13:30:57 +0000964 // Lastly, comment out the @end.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000965 ReplaceText(CatDecl->getAtEndRange().getBegin(), 0, "// ");
Steve Naroff5448cf62007-10-30 13:30:57 +0000966}
967
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000968void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000969 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Mike Stump11289f42009-09-09 15:08:12 +0000970
Steve Narofff921385f2007-10-30 16:42:30 +0000971 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000972
Steve Narofff921385f2007-10-30 16:42:30 +0000973 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000974 ReplaceText(LocStart, 0, "// ");
Mike Stump11289f42009-09-09 15:08:12 +0000975
976 for (ObjCProtocolDecl::instmeth_iterator
977 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000978 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000979 RewriteMethodDeclaration(*I);
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000980 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000981 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000982 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000983 RewriteMethodDeclaration(*I);
984
Steve Narofff921385f2007-10-30 16:42:30 +0000985 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +0000986 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000987 ReplaceText(LocEnd, 0, "// ");
Steve Naroffa509f042007-11-14 15:03:57 +0000988
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000989 // Must comment out @optional/@required
990 const char *startBuf = SM->getCharacterData(LocStart);
991 const char *endBuf = SM->getCharacterData(LocEnd);
992 for (const char *p = startBuf; p < endBuf; p++) {
993 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Steve Naroffa509f042007-11-14 15:03:57 +0000994 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000995 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump11289f42009-09-09 15:08:12 +0000996
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000997 }
998 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Steve Naroffa509f042007-11-14 15:03:57 +0000999 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001000 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump11289f42009-09-09 15:08:12 +00001001
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +00001002 }
1003 }
Steve Narofff921385f2007-10-30 16:42:30 +00001004}
1005
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001006void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanianda6165c2007-11-14 00:42:16 +00001007 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffc17b0562007-11-14 03:37:28 +00001008 if (LocStart.isInvalid())
1009 assert(false && "Invalid SourceLocation");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +00001010 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001011 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +00001012}
1013
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001014void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1015 const FunctionType *&FPRetType) {
1016 if (T->isObjCQualifiedIdType())
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +00001017 ResultStr += "id";
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001018 else if (T->isFunctionPointerType() ||
1019 T->isBlockPointerType()) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001020 // needs special handling, since pointer-to-functions have special
1021 // syntax (where a decaration models use).
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001022 QualType retType = T;
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001023 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001024 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001025 PointeeTy = PT->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001026 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001027 PointeeTy = BPT->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00001028 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001029 ResultStr += FPRetType->getResultType().getAsString();
1030 ResultStr += "(*";
Steve Naroffb067bbd2008-07-16 14:40:40 +00001031 }
1032 } else
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001033 ResultStr += T.getAsString();
1034}
1035
1036void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
1037 std::string &ResultStr) {
1038 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1039 const FunctionType *FPRetType = 0;
1040 ResultStr += "\nstatic ";
1041 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001042 ResultStr += " ";
Mike Stump11289f42009-09-09 15:08:12 +00001043
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001044 // Unique method name
Fariborz Jahanian56338352007-11-13 21:02:00 +00001045 std::string NameStr;
Mike Stump11289f42009-09-09 15:08:12 +00001046
Douglas Gregorffca3a22009-01-09 17:18:27 +00001047 if (OMD->isInstanceMethod())
Fariborz Jahanian56338352007-11-13 21:02:00 +00001048 NameStr += "_I_";
1049 else
1050 NameStr += "_C_";
Mike Stump11289f42009-09-09 15:08:12 +00001051
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001052 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +00001053 NameStr += "_";
Mike Stump11289f42009-09-09 15:08:12 +00001054
1055 if (ObjCCategoryImplDecl *CID =
Steve Naroff11b387f2009-01-08 19:41:02 +00001056 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001057 NameStr += CID->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +00001058 NameStr += "_";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001059 }
Mike Stump11289f42009-09-09 15:08:12 +00001060 // Append selector names, replacing ':' with '_'
Chris Lattnere4b95692008-11-24 03:33:13 +00001061 {
1062 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001063 int len = selString.size();
1064 for (int i = 0; i < len; i++)
1065 if (selString[i] == ':')
1066 selString[i] = '_';
Fariborz Jahanian56338352007-11-13 21:02:00 +00001067 NameStr += selString;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001068 }
Fariborz Jahanian56338352007-11-13 21:02:00 +00001069 // Remember this name for metadata emission
1070 MethodInternalNames[OMD] = NameStr;
1071 ResultStr += NameStr;
Mike Stump11289f42009-09-09 15:08:12 +00001072
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001073 // Rewrite arguments
1074 ResultStr += "(";
Mike Stump11289f42009-09-09 15:08:12 +00001075
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001076 // invisible arguments
Douglas Gregorffca3a22009-01-09 17:18:27 +00001077 if (OMD->isInstanceMethod()) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001078 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001079 selfTy = Context->getPointerType(selfTy);
Steve Naroffdc5b6b22008-03-12 00:25:36 +00001080 if (!LangOpts.Microsoft) {
1081 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
1082 ResultStr += "struct ";
1083 }
1084 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001085 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00001086 ResultStr += " *";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001087 }
1088 else
Steve Naroffd9803712009-04-29 16:37:50 +00001089 ResultStr += Context->getObjCClassType().getAsString();
Mike Stump11289f42009-09-09 15:08:12 +00001090
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001091 ResultStr += " self, ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001092 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001093 ResultStr += " _cmd";
Mike Stump11289f42009-09-09 15:08:12 +00001094
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001095 // Method arguments.
Chris Lattnera4997152009-02-20 18:43:26 +00001096 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1097 E = OMD->param_end(); PI != E; ++PI) {
1098 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001099 ResultStr += ", ";
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001100 if (PDecl->getType()->isObjCQualifiedIdType()) {
1101 ResultStr += "id ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001102 ResultStr += PDecl->getNameAsString();
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001103 } else {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001104 std::string Name = PDecl->getNameAsString();
Steve Naroffa5c0db82008-12-11 21:05:33 +00001105 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroff44df6a22008-10-30 14:45:29 +00001106 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001107 const BlockPointerType *BPT = PDecl->getType()->getAs<BlockPointerType>();
Douglas Gregor7de59662009-05-29 20:38:28 +00001108 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name,
1109 Context->PrintingPolicy);
Steve Naroff44df6a22008-10-30 14:45:29 +00001110 } else
Douglas Gregor7de59662009-05-29 20:38:28 +00001111 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001112 ResultStr += Name;
1113 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001114 }
Fariborz Jahanianeab81cd2008-01-21 20:14:23 +00001115 if (OMD->isVariadic())
1116 ResultStr += ", ...";
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001117 ResultStr += ") ";
Mike Stump11289f42009-09-09 15:08:12 +00001118
Steve Naroffb067bbd2008-07-16 14:40:40 +00001119 if (FPRetType) {
1120 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump11289f42009-09-09 15:08:12 +00001121
Steve Naroffb067bbd2008-07-16 14:40:40 +00001122 // Now, emit the argument types (if any).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001123 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001124 ResultStr += "(";
1125 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1126 if (i) ResultStr += ", ";
1127 std::string ParamStr = FT->getArgType(i).getAsString();
1128 ResultStr += ParamStr;
1129 }
1130 if (FT->isVariadic()) {
1131 if (FT->getNumArgs()) ResultStr += ", ";
1132 ResultStr += "...";
1133 }
1134 ResultStr += ")";
1135 } else {
1136 ResultStr += "()";
1137 }
1138 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001139}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001140void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001141 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1142 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump11289f42009-09-09 15:08:12 +00001143
Fariborz Jahanian02d964b2010-02-15 21:11:41 +00001144 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump11289f42009-09-09 15:08:12 +00001145
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001146 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001147 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1148 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001149 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001150 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001151 ObjCMethodDecl *OMD = *I;
1152 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001153 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001154 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redla7b98a72009-04-26 20:35:05 +00001155
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001156 const char *startBuf = SM->getCharacterData(LocStart);
1157 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001158 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001159 }
Mike Stump11289f42009-09-09 15:08:12 +00001160
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001161 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001162 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1163 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001164 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001165 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001166 ObjCMethodDecl *OMD = *I;
1167 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001168 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001169 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +00001170
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001171 const char *startBuf = SM->getCharacterData(LocStart);
1172 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001173 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001174 }
Steve Naroffe1908e32008-12-01 20:33:01 +00001175 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001176 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001177 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001178 I != E; ++I) {
Steve Naroffc038b3a2008-12-02 17:36:43 +00001179 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffe1908e32008-12-01 20:33:01 +00001180 }
1181
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001182 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001183}
1184
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001185void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffc5484042007-10-30 02:23:23 +00001186 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001187 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff2f55b982007-11-01 03:35:41 +00001188 // we haven't seen a forward decl - generate a typedef.
Steve Naroff03f27672007-11-14 23:02:56 +00001189 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001190 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001191 ResultStr += "\n";
1192 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001193 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001194 ResultStr += "\n";
Steve Naroffa1e115e2008-03-10 23:16:54 +00001195 ResultStr += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001196 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001197 ResultStr += ";\n#endif\n";
Steve Naroff2f55b982007-11-01 03:35:41 +00001198 // Mark this typedef as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001199 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff2f55b982007-11-01 03:35:41 +00001200 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001201 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump11289f42009-09-09 15:08:12 +00001202
1203 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001204 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff0c0f5ba2009-01-11 01:06:09 +00001205 RewriteProperty(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001206 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001207 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001208 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001209 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001210 for (ObjCInterfaceDecl::classmeth_iterator
1211 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001212 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001213 RewriteMethodDeclaration(*I);
1214
Steve Naroff4cd61ac2007-10-30 03:43:13 +00001215 // Lastly, comment out the @end.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001216 ReplaceText(ClassDecl->getAtEndRange().getBegin(), 0, "// ");
Steve Naroff161a92b2007-10-26 20:53:56 +00001217}
1218
Steve Naroff08628db2008-12-09 12:56:34 +00001219Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1220 SourceRange SrcRange) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00001221 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1222 // This allows us to reuse all the fun and games in SynthMessageExpr().
1223 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1224 ObjCMessageExpr *MsgExpr;
1225 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1226 llvm::SmallVector<Expr *, 1> ExprVec;
1227 ExprVec.push_back(newStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001228
Steve Naroff1042ff32008-12-08 16:43:47 +00001229 Stmt *Receiver = PropRefExpr->getBase();
1230 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1231 if (PRE && PropGetters[PRE]) {
1232 // This allows us to handle chain/nested property getters.
1233 Receiver = PropGetters[PRE];
1234 }
Ted Kremenek2c809302010-02-11 22:41:21 +00001235 MsgExpr = new (Context) ObjCMessageExpr(*Context, dyn_cast<Expr>(Receiver),
Mike Stump11289f42009-09-09 15:08:12 +00001236 PDecl->getSetterName(), PDecl->getType(),
1237 PDecl->getSetterMethodDecl(),
1238 SourceLocation(), SourceLocation(),
Steve Naroff4588d0f2008-12-04 16:24:46 +00001239 &ExprVec[0], 1);
1240 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001241
Steve Naroff4588d0f2008-12-04 16:24:46 +00001242 // Now do the actual rewrite.
Steve Naroff08628db2008-12-09 12:56:34 +00001243 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffdf705772008-12-10 14:53:27 +00001244 //delete BinOp;
Ted Kremenek5a201952009-02-07 01:47:29 +00001245 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1246 // to things that stay around.
1247 Context->Deallocate(MsgExpr);
Steve Naroff4588d0f2008-12-04 16:24:46 +00001248 return ReplacingStmt;
Steve Narofff326f402008-12-03 00:56:33 +00001249}
1250
Steve Naroff4588d0f2008-12-04 16:24:46 +00001251Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Narofff326f402008-12-03 00:56:33 +00001252 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1253 // This allows us to reuse all the fun and games in SynthMessageExpr().
1254 ObjCMessageExpr *MsgExpr;
1255 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
Mike Stump11289f42009-09-09 15:08:12 +00001256
Steve Naroff1042ff32008-12-08 16:43:47 +00001257 Stmt *Receiver = PropRefExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00001258
Steve Naroff1042ff32008-12-08 16:43:47 +00001259 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1260 if (PRE && PropGetters[PRE]) {
1261 // This allows us to handle chain/nested property getters.
1262 Receiver = PropGetters[PRE];
1263 }
Ted Kremenek2c809302010-02-11 22:41:21 +00001264 MsgExpr = new (Context) ObjCMessageExpr(*Context, dyn_cast<Expr>(Receiver),
Mike Stump11289f42009-09-09 15:08:12 +00001265 PDecl->getGetterName(), PDecl->getType(),
1266 PDecl->getGetterMethodDecl(),
1267 SourceLocation(), SourceLocation(),
Steve Narofff326f402008-12-03 00:56:33 +00001268 0, 0);
1269
Steve Naroff22216db2008-12-04 23:50:32 +00001270 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001271
1272 if (!PropParentMap)
1273 PropParentMap = new ParentMap(CurrentBody);
1274
1275 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1276 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1277 // We stash away the ReplacingStmt since actually doing the
1278 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1279 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek5a201952009-02-07 01:47:29 +00001280 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1281 // to things that stay around.
1282 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001283 return PropRefExpr; // return the original...
1284 } else {
1285 ReplaceStmt(PropRefExpr, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001286 // delete PropRefExpr; elsewhere...
Ted Kremenek5a201952009-02-07 01:47:29 +00001287 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1288 // to things that stay around.
1289 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001290 return ReplacingStmt;
1291 }
Steve Narofff326f402008-12-03 00:56:33 +00001292}
1293
Mike Stump11289f42009-09-09 15:08:12 +00001294Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001295 SourceLocation OrigStart,
1296 bool &replaced) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001297 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001298 const Expr *BaseExpr = IV->getBase();
Steve Naroff677ab3a2008-10-27 17:20:55 +00001299 if (CurMethodDef) {
Fariborz Jahanianf9e8c2b2010-01-26 18:28:51 +00001300 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001301 ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001302 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianf0ed69c2010-01-26 20:37:44 +00001303 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Naroffb1c02372008-05-08 17:52:16 +00001304 // lookup which class implements the instance variable.
1305 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001306 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001307 clsDeclared);
Steve Naroffb1c02372008-05-08 17:52:16 +00001308 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001309
Steve Naroffb1c02372008-05-08 17:52:16 +00001310 // Synthesize an explicit cast to gain access to the ivar.
1311 std::string RecName = clsDeclared->getIdentifier()->getName();
1312 RecName += "_IMPL";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001313 IdentifierInfo *II = &Context->Idents.get(RecName);
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001314 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001315 SourceLocation(), II);
Steve Naroffb1c02372008-05-08 17:52:16 +00001316 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1317 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall97513962010-01-15 18:39:57 +00001318 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1319 CastExpr::CK_Unknown,
1320 IV->getBase());
Steve Naroffb1c02372008-05-08 17:52:16 +00001321 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001322 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1323 IV->getBase()->getLocEnd(),
1324 castExpr);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001325 replaced = true;
Mike Stump11289f42009-09-09 15:08:12 +00001326 if (IV->isFreeIvar() &&
Steve Naroff677ab3a2008-10-27 17:20:55 +00001327 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001328 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1329 IV->getLocation(),
1330 D->getType());
Steve Naroff22216db2008-12-04 23:50:32 +00001331 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb1c02372008-05-08 17:52:16 +00001332 return ME;
Steve Naroff05caa482007-11-15 11:33:00 +00001333 }
Fariborz Jahanian81310812010-01-28 01:41:20 +00001334 // Get the new text
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001335 // Cannot delete IV->getBase(), since PE points to it.
1336 // Replace the old base with the cast. This is important when doing
1337 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001338 IV->setBase(PE);
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001339 return IV;
Steve Naroff05caa482007-11-15 11:33:00 +00001340 }
Steve Naroff24840f62008-04-18 21:55:08 +00001341 } else { // we are outside a method.
Steve Naroff29ce4e52008-05-06 23:20:07 +00001342 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump11289f42009-09-09 15:08:12 +00001343
Steve Naroff29ce4e52008-05-06 23:20:07 +00001344 // Explicit ivar refs need to have a cast inserted.
1345 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian12e2e862010-01-12 17:31:23 +00001346 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Fariborz Jahanian9146e442010-01-11 17:50:35 +00001347 ObjCInterfaceType *iFaceDecl =
1348 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001349 // lookup which class implements the instance variable.
1350 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001351 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001352 clsDeclared);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001353 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001354
Steve Naroff29ce4e52008-05-06 23:20:07 +00001355 // Synthesize an explicit cast to gain access to the ivar.
1356 std::string RecName = clsDeclared->getIdentifier()->getName();
1357 RecName += "_IMPL";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001358 IdentifierInfo *II = &Context->Idents.get(RecName);
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001359 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001360 SourceLocation(), II);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001361 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1362 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall97513962010-01-15 18:39:57 +00001363 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1364 CastExpr::CK_Unknown,
1365 IV->getBase());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001366 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001367 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner34873d22008-05-28 16:38:23 +00001368 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001369 replaced = true;
Steve Naroff29ce4e52008-05-06 23:20:07 +00001370 // Cannot delete IV->getBase(), since PE points to it.
1371 // Replace the old base with the cast. This is important when doing
1372 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001373 IV->setBase(PE);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001374 return IV;
1375 }
Steve Naroff05caa482007-11-15 11:33:00 +00001376 }
Steve Naroff24840f62008-04-18 21:55:08 +00001377 return IV;
Steve Narofff60782b2007-11-15 02:58:25 +00001378}
1379
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001380Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
1381 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1382 CI != E; ++CI) {
1383 if (*CI) {
1384 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1385 if (newStmt)
1386 *CI = newStmt;
1387 }
1388 }
1389 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1390 SourceRange OrigStmtRange = S->getSourceRange();
1391 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1392 replaced);
1393 return newStmt;
Fariborz Jahanian31433382010-02-05 17:48:10 +00001394 }
1395 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1396 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1397 return newStmt;
1398 }
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001399 return S;
1400}
1401
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001402/// SynthCountByEnumWithState - To print:
1403/// ((unsigned int (*)
1404/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001405/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001406/// sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001407/// "countByEnumeratingWithState:objects:count:"),
1408/// &enumState,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001409/// (id *)items, (unsigned int)16)
1410///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001411void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001412 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1413 "id *, unsigned int))(void *)objc_msgSend)";
1414 buf += "\n\t\t";
1415 buf += "((id)l_collection,\n\t\t";
1416 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1417 buf += "\n\t\t";
1418 buf += "&enumState, "
1419 "(id *)items, (unsigned int)16)";
1420}
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001421
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001422/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1423/// statement to exit to its outer synthesized loop.
1424///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001425Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001426 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1427 return S;
1428 // replace break with goto __break_label
1429 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001430
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001431 SourceLocation startLoc = S->getLocStart();
1432 buf = "goto __break_label_";
1433 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001434 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001435
1436 return 0;
1437}
1438
1439/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1440/// statement to continue with its inner synthesized loop.
1441///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001442Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001443 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1444 return S;
1445 // replace continue with goto __continue_label
1446 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001447
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001448 SourceLocation startLoc = S->getLocStart();
1449 buf = "goto __continue_label_";
1450 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001451 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump11289f42009-09-09 15:08:12 +00001452
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001453 return 0;
1454}
1455
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001456/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001457/// It rewrites:
1458/// for ( type elem in collection) { stmts; }
Mike Stump11289f42009-09-09 15:08:12 +00001459
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001460/// Into:
1461/// {
Mike Stump11289f42009-09-09 15:08:12 +00001462/// type elem;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001463/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001464/// id items[16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001465/// id l_collection = (id)collection;
Mike Stump11289f42009-09-09 15:08:12 +00001466/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001467/// objects:items count:16];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001468/// if (limit) {
1469/// unsigned long startMutations = *enumState.mutationsPtr;
1470/// do {
1471/// unsigned long counter = 0;
1472/// do {
Mike Stump11289f42009-09-09 15:08:12 +00001473/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001474/// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001475/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001476/// stmts;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001477/// __continue_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001478/// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001479/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001480/// objects:items count:16]);
1481/// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001482/// __break_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001483/// }
1484/// else
1485/// elem = nil;
1486/// }
1487///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001488Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattnera779d692008-01-31 05:10:40 +00001489 SourceLocation OrigEnd) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001490 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001491 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001492 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump11289f42009-09-09 15:08:12 +00001493 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001494 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001495
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001496 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001497 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001498 const char *elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001499 std::string elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001500 std::string buf;
1501 buf = "\n{\n\t";
1502 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1503 // type elem;
Chris Lattner529efc72009-03-28 06:33:19 +00001504 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek292b3842008-10-06 22:16:13 +00001505 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001506 if (ElementType->isObjCQualifiedIdType() ||
1507 ElementType->isObjCQualifiedInterfaceType())
1508 // Simply use 'id' for all qualified types.
1509 elementTypeAsString = "id";
1510 else
1511 elementTypeAsString = ElementType.getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001512 buf += elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001513 buf += " ";
Chris Lattner86d7d912008-11-24 03:54:41 +00001514 elementName = D->getNameAsCString();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001515 buf += elementName;
1516 buf += ";\n\t";
1517 }
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001518 else {
1519 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner86d7d912008-11-24 03:54:41 +00001520 elementName = DR->getDecl()->getNameAsCString();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001521 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1522 if (VD->getType()->isObjCQualifiedIdType() ||
1523 VD->getType()->isObjCQualifiedInterfaceType())
1524 // Simply use 'id' for all qualified types.
1525 elementTypeAsString = "id";
1526 else
1527 elementTypeAsString = VD->getType().getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001528 }
Mike Stump11289f42009-09-09 15:08:12 +00001529
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001530 // struct __objcFastEnumerationState enumState = { 0 };
1531 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1532 // id items[16];
1533 buf += "id items[16];\n\t";
1534 // id l_collection = (id)
1535 buf += "id l_collection = (id)";
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001536 // Find start location of 'collection' the hard way!
1537 const char *startCollectionBuf = startBuf;
1538 startCollectionBuf += 3; // skip 'for'
1539 startCollectionBuf = strchr(startCollectionBuf, '(');
1540 startCollectionBuf++; // skip '('
1541 // find 'in' and skip it.
1542 while (*startCollectionBuf != ' ' ||
1543 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1544 (*(startCollectionBuf+3) != ' ' &&
1545 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1546 startCollectionBuf++;
1547 startCollectionBuf += 3;
Mike Stump11289f42009-09-09 15:08:12 +00001548
1549 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001550 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001551 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001552 SourceLocation rightParenLoc = S->getRParenLoc();
1553 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1554 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001555 buf = ";\n\t";
Mike Stump11289f42009-09-09 15:08:12 +00001556
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001557 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1558 // objects:items count:16];
1559 // which is synthesized into:
Mike Stump11289f42009-09-09 15:08:12 +00001560 // unsigned int limit =
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001561 // ((unsigned int (*)
1562 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001563 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001564 // sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001565 // "countByEnumeratingWithState:objects:count:"),
1566 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001567 // (id *)items, (unsigned int)16);
1568 buf += "unsigned long limit =\n\t\t";
1569 SynthCountByEnumWithState(buf);
1570 buf += ";\n\t";
1571 /// if (limit) {
1572 /// unsigned long startMutations = *enumState.mutationsPtr;
1573 /// do {
1574 /// unsigned long counter = 0;
1575 /// do {
Mike Stump11289f42009-09-09 15:08:12 +00001576 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001577 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001578 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001579 buf += "if (limit) {\n\t";
1580 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1581 buf += "do {\n\t\t";
1582 buf += "unsigned long counter = 0;\n\t\t";
1583 buf += "do {\n\t\t\t";
1584 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1585 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1586 buf += elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001587 buf += " = (";
1588 buf += elementTypeAsString;
1589 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001590 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001591 ReplaceText(lparenLoc, 1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001592
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001593 /// __continue_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001594 /// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001595 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001596 /// objects:items count:16]);
1597 /// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001598 /// __break_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001599 /// }
1600 /// else
1601 /// elem = nil;
1602 /// }
Mike Stump11289f42009-09-09 15:08:12 +00001603 ///
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001604 buf = ";\n\t";
1605 buf += "__continue_label_";
1606 buf += utostr(ObjCBcLabelNo.back());
1607 buf += ": ;";
1608 buf += "\n\t\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001609 buf += "} while (counter < limit);\n\t";
1610 buf += "} while (limit = ";
1611 SynthCountByEnumWithState(buf);
1612 buf += ");\n\t";
1613 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001614 buf += " = ((";
1615 buf += elementTypeAsString;
1616 buf += ")0);\n\t";
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001617 buf += "__break_label_";
1618 buf += utostr(ObjCBcLabelNo.back());
1619 buf += ": ;\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001620 buf += "}\n\t";
1621 buf += "else\n\t\t";
1622 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001623 buf += " = ((";
1624 buf += elementTypeAsString;
1625 buf += ")0);\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001626 buf += "}\n";
Mike Stump11289f42009-09-09 15:08:12 +00001627
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001628 // Insert all these *after* the statement body.
Sebastian Redla7b98a72009-04-26 20:35:05 +00001629 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Narofff0ff8792008-07-21 18:26:02 +00001630 if (isa<CompoundStmt>(S->getBody())) {
1631 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001632 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001633 } else {
1634 /* Need to treat single statements specially. For example:
1635 *
1636 * for (A *a in b) if (stuff()) break;
1637 * for (A *a in b) xxxyy;
1638 *
1639 * The following code simply scans ahead to the semi to find the actual end.
1640 */
1641 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1642 const char *semiBuf = strchr(stmtBuf, ';');
1643 assert(semiBuf && "Can't find ';'");
1644 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001645 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001646 }
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001647 Stmts.pop_back();
1648 ObjCBcLabelNo.pop_back();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001649 return 0;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001650}
1651
Mike Stump11289f42009-09-09 15:08:12 +00001652/// RewriteObjCSynchronizedStmt -
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001653/// This routine rewrites @synchronized(expr) stmt;
1654/// into:
1655/// objc_sync_enter(expr);
1656/// @try stmt @finally { objc_sync_exit(expr); }
1657///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001658Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001659 // Get the start location and compute the semi location.
1660 SourceLocation startLoc = S->getLocStart();
1661 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001662
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001663 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump11289f42009-09-09 15:08:12 +00001664
1665 std::string buf;
Steve Naroffb2fc0522008-08-21 13:03:03 +00001666 buf = "objc_sync_enter((id)";
1667 const char *lparenBuf = startBuf;
1668 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001669 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001670 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1671 // the sync expression is typically a message expression that's already
Steve Naroffad7013b2008-08-19 13:04:19 +00001672 // been rewritten! (which implies the SourceLocation's are invalid).
1673 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001674 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffad7013b2008-08-19 13:04:19 +00001675 while (*endBuf != ')') endBuf--;
1676 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001677 buf = ");\n";
1678 // declare a new scope with two variables, _stack and _rethrow.
1679 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1680 buf += "int buf[18/*32-bit i386*/];\n";
1681 buf += "char *pointers[4];} _stack;\n";
1682 buf += "id volatile _rethrow = 0;\n";
1683 buf += "objc_exception_try_enter(&_stack);\n";
1684 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001685 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001686 startLoc = S->getSynchBody()->getLocEnd();
1687 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001688
Steve Naroffad7013b2008-08-19 13:04:19 +00001689 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001690 SourceLocation lastCurlyLoc = startLoc;
1691 buf = "}\nelse {\n";
1692 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroffd9803712009-04-29 16:37:50 +00001693 buf += "}\n";
1694 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001695 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffec60b432009-12-05 21:43:12 +00001696
1697 std::string syncBuf;
1698 syncBuf += " objc_sync_exit(";
John McCall97513962010-01-15 18:39:57 +00001699 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1700 CastExpr::CK_Unknown,
1701 S->getSynchExpr());
Ted Kremenek2d470fc2008-09-13 05:16:45 +00001702 std::string syncExprBufS;
1703 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00001704 syncExpr->printPretty(syncExprBuf, *Context, 0,
1705 PrintingPolicy(LangOpts));
Steve Naroffec60b432009-12-05 21:43:12 +00001706 syncBuf += syncExprBuf.str();
1707 syncBuf += ");";
1708
1709 buf += syncBuf;
1710 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001711 buf += "}\n";
1712 buf += "}";
Mike Stump11289f42009-09-09 15:08:12 +00001713
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001714 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00001715
1716 bool hasReturns = false;
1717 HasReturnStmts(S->getSynchBody(), hasReturns);
1718 if (hasReturns)
1719 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1720
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001721 return 0;
1722}
1723
Steve Naroffec60b432009-12-05 21:43:12 +00001724void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1725{
Steve Naroff6d6da252008-12-05 17:03:39 +00001726 // Perform a bottom up traversal of all children.
1727 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1728 CI != E; ++CI)
1729 if (*CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001730 WarnAboutReturnGotoStmts(*CI);
Steve Naroff6d6da252008-12-05 17:03:39 +00001731
Steve Naroffec60b432009-12-05 21:43:12 +00001732 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump11289f42009-09-09 15:08:12 +00001733 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff6d6da252008-12-05 17:03:39 +00001734 TryFinallyContainsReturnDiag);
1735 }
1736 return;
1737}
1738
Steve Naroffec60b432009-12-05 21:43:12 +00001739void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1740{
1741 // Perform a bottom up traversal of all children.
1742 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1743 CI != E; ++CI)
1744 if (*CI)
1745 HasReturnStmts(*CI, hasReturns);
1746
1747 if (isa<ReturnStmt>(S))
1748 hasReturns = true;
1749 return;
1750}
1751
1752void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1753 // Perform a bottom up traversal of all children.
1754 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1755 CI != E; ++CI)
1756 if (*CI) {
1757 RewriteTryReturnStmts(*CI);
1758 }
1759 if (isa<ReturnStmt>(S)) {
1760 SourceLocation startLoc = S->getLocStart();
1761 const char *startBuf = SM->getCharacterData(startLoc);
1762
1763 const char *semiBuf = strchr(startBuf, ';');
1764 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1765 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1766
1767 std::string buf;
1768 buf = "{ objc_exception_try_exit(&_stack); return";
1769
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001770 ReplaceText(startLoc, 6, buf);
1771 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001772 }
1773 return;
1774}
1775
1776void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1777 // Perform a bottom up traversal of all children.
1778 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1779 CI != E; ++CI)
1780 if (*CI) {
1781 RewriteSyncReturnStmts(*CI, syncExitBuf);
1782 }
1783 if (isa<ReturnStmt>(S)) {
1784 SourceLocation startLoc = S->getLocStart();
1785 const char *startBuf = SM->getCharacterData(startLoc);
1786
1787 const char *semiBuf = strchr(startBuf, ';');
1788 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1789 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1790
1791 std::string buf;
1792 buf = "{ objc_exception_try_exit(&_stack);";
1793 buf += syncExitBuf;
1794 buf += " return";
1795
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001796 ReplaceText(startLoc, 6, buf);
1797 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001798 }
1799 return;
1800}
1801
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001802Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001803 // Get the start location and compute the semi location.
1804 SourceLocation startLoc = S->getLocStart();
1805 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001806
Steve Naroffbf478ec2007-11-07 04:08:17 +00001807 assert((*startBuf == '@') && "bogus @try location");
1808
1809 std::string buf;
1810 // declare a new scope with two variables, _stack and _rethrow.
1811 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1812 buf += "int buf[18/*32-bit i386*/];\n";
1813 buf += "char *pointers[4];} _stack;\n";
1814 buf += "id volatile _rethrow = 0;\n";
1815 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff16018582007-11-07 18:43:40 +00001816 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffbf478ec2007-11-07 04:08:17 +00001817
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001818 ReplaceText(startLoc, 4, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001819
Steve Naroffbf478ec2007-11-07 04:08:17 +00001820 startLoc = S->getTryBody()->getLocEnd();
1821 startBuf = SM->getCharacterData(startLoc);
1822
1823 assert((*startBuf == '}') && "bogus @try block");
Mike Stump11289f42009-09-09 15:08:12 +00001824
Steve Naroffbf478ec2007-11-07 04:08:17 +00001825 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffce2dca12008-07-16 15:31:30 +00001826 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1827 if (catchList) {
1828 startLoc = startLoc.getFileLocWithOffset(1);
1829 buf = " /* @catch begin */ else {\n";
1830 buf += " id _caught = objc_exception_extract(&_stack);\n";
1831 buf += " objc_exception_try_enter (&_stack);\n";
1832 buf += " if (_setjmp(_stack.buf))\n";
1833 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1834 buf += " else { /* @catch continue */";
Mike Stump11289f42009-09-09 15:08:12 +00001835
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001836 InsertText(startLoc, buf);
Steve Narofffac18fe2008-09-09 19:59:12 +00001837 } else { /* no catch list */
1838 buf = "}\nelse {\n";
1839 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1840 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001841 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffce2dca12008-07-16 15:31:30 +00001842 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001843 bool sawIdTypedCatch = false;
1844 Stmt *lastCatchBody = 0;
Steve Naroffbf478ec2007-11-07 04:08:17 +00001845 while (catchList) {
Steve Naroff371b8fb2009-03-03 19:52:17 +00001846 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001847
Mike Stump11289f42009-09-09 15:08:12 +00001848 if (catchList == S->getCatchStmts())
Steve Naroffbf478ec2007-11-07 04:08:17 +00001849 buf = "if ("; // we are generating code for the first catch clause
1850 else
1851 buf = "else if (";
1852 startLoc = catchList->getLocStart();
1853 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001854
Steve Naroffbf478ec2007-11-07 04:08:17 +00001855 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump11289f42009-09-09 15:08:12 +00001856
Steve Naroffbf478ec2007-11-07 04:08:17 +00001857 const char *lParenLoc = strchr(startBuf, '(');
1858
Steve Naroffe6b7ffd2008-02-01 22:08:12 +00001859 if (catchList->hasEllipsis()) {
Steve Naroffedb5bc62008-02-01 20:02:07 +00001860 // Now rewrite the body...
1861 lastCatchBody = catchList->getCatchBody();
Steve Naroffedb5bc62008-02-01 20:02:07 +00001862 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1863 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001864 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1865 "bogus @catch paren location");
Steve Naroffedb5bc62008-02-01 20:02:07 +00001866 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001867
Steve Naroffedb5bc62008-02-01 20:02:07 +00001868 buf += "1) { id _tmp = _caught;";
Daniel Dunbardec484a2009-08-19 19:10:30 +00001869 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff371b8fb2009-03-03 19:52:17 +00001870 } else if (catchDecl) {
1871 QualType t = catchDecl->getType();
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001872 if (t == Context->getObjCIdType()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001873 buf += "1) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001874 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroffbf478ec2007-11-07 04:08:17 +00001875 sawIdTypedCatch = true;
Fariborz Jahanian59516092010-01-12 01:22:23 +00001876 } else if (t->isObjCObjectPointerType()) {
1877 QualType InterfaceTy = t->getPointeeType();
1878 const ObjCInterfaceType *cls = // Should be a pointer to a class.
1879 InterfaceTy->getAs<ObjCInterfaceType>();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001880 if (cls) {
Steve Naroff16018582007-11-07 18:43:40 +00001881 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001882 buf += cls->getDecl()->getNameAsString();
Steve Naroff16018582007-11-07 18:43:40 +00001883 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001884 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroffbf478ec2007-11-07 04:08:17 +00001885 }
1886 }
1887 // Now rewrite the body...
1888 lastCatchBody = catchList->getCatchBody();
1889 SourceLocation rParenLoc = catchList->getRParenLoc();
1890 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1891 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1892 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1893 assert((*rParenBuf == ')') && "bogus @catch paren location");
1894 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001895
Mike Stump11289f42009-09-09 15:08:12 +00001896 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroffbf478ec2007-11-07 04:08:17 +00001897 // declares the @catch parameter).
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001898 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff371b8fb2009-03-03 19:52:17 +00001899 } else {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001900 assert(false && "@catch rewrite bug");
Steve Naroffa733c7f2007-11-07 15:32:26 +00001901 }
Steve Naroffedb5bc62008-02-01 20:02:07 +00001902 // make sure all the catch bodies get rewritten!
Steve Naroffbf478ec2007-11-07 04:08:17 +00001903 catchList = catchList->getNextCatchStmt();
1904 }
1905 // Complete the catch list...
1906 if (lastCatchBody) {
1907 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001908 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1909 "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001910
Steve Naroff4adbe312008-09-11 15:29:03 +00001911 // Insert the last (implicit) else clause *before* the right curly brace.
1912 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1913 buf = "} /* last catch end */\n";
1914 buf += "else {\n";
1915 buf += " _rethrow = _caught;\n";
1916 buf += " objc_exception_try_exit(&_stack);\n";
1917 buf += "} } /* @catch end */\n";
1918 if (!S->getFinallyStmt())
1919 buf += "}\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001920 InsertText(bodyLoc, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001921
Steve Naroffbf478ec2007-11-07 04:08:17 +00001922 // Set lastCurlyLoc
1923 lastCurlyLoc = lastCatchBody->getLocEnd();
1924 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001925 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001926 startLoc = finalStmt->getLocStart();
1927 startBuf = SM->getCharacterData(startLoc);
1928 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump11289f42009-09-09 15:08:12 +00001929
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001930 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump11289f42009-09-09 15:08:12 +00001931
Steve Naroffbf478ec2007-11-07 04:08:17 +00001932 Stmt *body = finalStmt->getFinallyBody();
1933 SourceLocation startLoc = body->getLocStart();
1934 SourceLocation endLoc = body->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001935 assert(*SM->getCharacterData(startLoc) == '{' &&
1936 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001937 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001938 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001939
Steve Naroffbf478ec2007-11-07 04:08:17 +00001940 startLoc = startLoc.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001941 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Steve Naroffbf478ec2007-11-07 04:08:17 +00001942 endLoc = endLoc.getFileLocWithOffset(-1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001943 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump11289f42009-09-09 15:08:12 +00001944
Steve Naroffbf478ec2007-11-07 04:08:17 +00001945 // Set lastCurlyLoc
1946 lastCurlyLoc = body->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00001947
Steve Naroff6d6da252008-12-05 17:03:39 +00001948 // Now check for any return/continue/go statements within the @try.
Steve Naroffec60b432009-12-05 21:43:12 +00001949 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff4adbe312008-09-11 15:29:03 +00001950 } else { /* no finally clause - make sure we synthesize an implicit one */
1951 buf = "{ /* implicit finally clause */\n";
1952 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1953 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1954 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001955 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00001956
1957 // Now check for any return/continue/go statements within the @try.
1958 // The implicit finally clause won't called if the @try contains any
1959 // jump statements.
1960 bool hasReturns = false;
1961 HasReturnStmts(S->getTryBody(), hasReturns);
1962 if (hasReturns)
1963 RewriteTryReturnStmts(S->getTryBody());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001964 }
1965 // Now emit the final closing curly brace...
1966 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001967 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001968 return 0;
1969}
1970
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001971Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001972 return 0;
1973}
1974
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001975Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001976 return 0;
1977}
1978
Mike Stump11289f42009-09-09 15:08:12 +00001979// This can't be done with ReplaceStmt(S, ThrowExpr), since
1980// the throw expression is typically a message expression that's already
Steve Naroffa733c7f2007-11-07 15:32:26 +00001981// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001982Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroffa733c7f2007-11-07 15:32:26 +00001983 // Get the start location and compute the semi location.
1984 SourceLocation startLoc = S->getLocStart();
1985 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001986
Steve Naroffa733c7f2007-11-07 15:32:26 +00001987 assert((*startBuf == '@') && "bogus @throw location");
1988
1989 std::string buf;
1990 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffc7d2df22008-01-19 00:42:38 +00001991 if (S->getThrowExpr())
1992 buf = "objc_exception_throw(";
1993 else // add an implicit argument
1994 buf = "objc_exception_throw(_caught";
Mike Stump11289f42009-09-09 15:08:12 +00001995
Steve Naroff29788342008-07-25 15:41:30 +00001996 // handle "@ throw" correctly.
1997 const char *wBuf = strchr(startBuf, 'w');
1998 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001999 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00002000
Steve Naroffa733c7f2007-11-07 15:32:26 +00002001 const char *semiBuf = strchr(startBuf, ';');
2002 assert((*semiBuf == ';') && "@throw: can't find ';'");
2003 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002004 ReplaceText(semiLoc, 1, ");");
Steve Naroffa733c7f2007-11-07 15:32:26 +00002005 return 0;
2006}
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00002007
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002008Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerc6d91c02007-10-17 22:35:30 +00002009 // Create a new string expression.
2010 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlssond8499822007-10-29 05:01:08 +00002011 std::string StrEncoding;
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00002012 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002013 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
2014 StrEncoding.length(), false,StrType,
2015 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002016 ReplaceStmt(Exp, Replacement);
Mike Stump11289f42009-09-09 15:08:12 +00002017
Chris Lattner4431a1b2007-11-30 22:53:43 +00002018 // Replace this subexpr in the parent.
Steve Naroff22216db2008-12-04 23:50:32 +00002019 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattner69534692007-10-24 16:57:36 +00002020 return Replacement;
Chris Lattnera7c19fe2007-10-16 22:36:42 +00002021}
2022
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002023Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff2654e182008-12-22 22:16:07 +00002024 if (!SelGetUidFunctionDecl)
2025 SynthSelGetUidFunctionDecl();
Steve Naroffe4f9b232007-11-05 14:50:49 +00002026 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2027 // Create a call to sel_registerName("selName").
2028 llvm::SmallVector<Expr*, 8> SelExprs;
2029 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002030 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002031 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002032 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002033 false, argType, SourceLocation()));
Steve Naroffe4f9b232007-11-05 14:50:49 +00002034 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2035 &SelExprs[0], SelExprs.size());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002036 ReplaceStmt(Exp, SelExp);
Steve Naroff22216db2008-12-04 23:50:32 +00002037 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffe4f9b232007-11-05 14:50:49 +00002038 return SelExp;
2039}
2040
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002041CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002042 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2043 SourceLocation EndLoc) {
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002044 // Get the type, we will need to reference it in a couple spots.
Steve Naroff574440f2007-10-24 22:48:43 +00002045 QualType msgSendType = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002046
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002047 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek5a201952009-02-07 01:47:29 +00002048 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002049
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002050 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattner3c799d72007-10-24 17:06:59 +00002051 QualType pToFunc = Context->getPointerType(msgSendType);
Mike Stump11289f42009-09-09 15:08:12 +00002052 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc,
Anders Carlssona2615922009-07-31 00:48:10 +00002053 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002054 DRE,
Douglas Gregora11693b2008-11-12 17:17:38 +00002055 /*isLvalue=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002056
John McCall9dd450b2009-09-21 23:43:11 +00002057 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00002058
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002059 CallExpr *Exp =
2060 new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
2061 EndLoc);
2062 return Exp;
Steve Naroff574440f2007-10-24 22:48:43 +00002063}
2064
Steve Naroff50d42052007-11-01 13:24:47 +00002065static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2066 const char *&startRef, const char *&endRef) {
2067 while (startBuf < endBuf) {
2068 if (*startBuf == '<')
2069 startRef = startBuf; // mark the start.
2070 if (*startBuf == '>') {
Steve Naroff1b232132007-11-09 12:50:28 +00002071 if (startRef && *startRef == '<') {
2072 endRef = startBuf; // mark the end.
2073 return true;
2074 }
2075 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002076 }
2077 startBuf++;
2078 }
2079 return false;
2080}
2081
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002082static void scanToNextArgument(const char *&argRef) {
2083 int angle = 0;
2084 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2085 if (*argRef == '<')
2086 angle++;
2087 else if (*argRef == '>')
2088 angle--;
2089 argRef++;
2090 }
2091 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2092}
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002093
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002094bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian80c54b02010-02-03 21:29:28 +00002095 if (T->isObjCQualifiedIdType())
2096 return true;
Fariborz Jahanian06769f92010-02-02 18:35:07 +00002097 if (const PointerType *PT = T->getAs<PointerType>()) {
2098 if (PT->getPointeeType()->isObjCQualifiedIdType())
2099 return true;
2100 }
2101 if (T->isObjCObjectPointerType()) {
2102 T = T->getPointeeType();
2103 return T->isObjCQualifiedInterfaceType();
2104 }
2105 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002106}
2107
Steve Naroff873bd842008-07-29 18:15:38 +00002108void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2109 QualType Type = E->getType();
2110 if (needToScanForQualifiers(Type)) {
Steve Naroffdbfc6932008-11-19 21:15:47 +00002111 SourceLocation Loc, EndLoc;
Mike Stump11289f42009-09-09 15:08:12 +00002112
Steve Naroffdbfc6932008-11-19 21:15:47 +00002113 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2114 Loc = ECE->getLParenLoc();
2115 EndLoc = ECE->getRParenLoc();
2116 } else {
2117 Loc = E->getLocStart();
2118 EndLoc = E->getLocEnd();
2119 }
2120 // This will defend against trying to rewrite synthesized expressions.
2121 if (Loc.isInvalid() || EndLoc.isInvalid())
2122 return;
2123
Steve Naroff873bd842008-07-29 18:15:38 +00002124 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffdbfc6932008-11-19 21:15:47 +00002125 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff873bd842008-07-29 18:15:38 +00002126 const char *startRef = 0, *endRef = 0;
2127 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2128 // Get the locations of the startRef, endRef.
2129 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2130 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2131 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002132 InsertText(LessLoc, "/*");
2133 InsertText(GreaterLoc, "*/");
Steve Naroff873bd842008-07-29 18:15:38 +00002134 }
2135 }
2136}
2137
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002138void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002139 SourceLocation Loc;
2140 QualType Type;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002141 const FunctionProtoType *proto = 0;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002142 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2143 Loc = VD->getLocation();
2144 Type = VD->getType();
2145 }
2146 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2147 Loc = FD->getLocation();
2148 // Check for ObjC 'id' and class types that have been adorned with protocol
2149 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall9dd450b2009-09-21 23:43:11 +00002150 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002151 assert(funcType && "missing function type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002152 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002153 if (!proto)
2154 return;
2155 Type = proto->getResultType();
2156 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00002157 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2158 Loc = FD->getLocation();
2159 Type = FD->getType();
2160 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002161 else
2162 return;
Mike Stump11289f42009-09-09 15:08:12 +00002163
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002164 if (needToScanForQualifiers(Type)) {
Steve Naroff50d42052007-11-01 13:24:47 +00002165 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002166
Steve Naroff50d42052007-11-01 13:24:47 +00002167 const char *endBuf = SM->getCharacterData(Loc);
2168 const char *startBuf = endBuf;
Steve Naroff930e0992008-05-31 05:02:17 +00002169 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroff50d42052007-11-01 13:24:47 +00002170 startBuf--; // scan backward (from the decl location) for return type.
2171 const char *startRef = 0, *endRef = 0;
2172 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2173 // Get the locations of the startRef, endRef.
2174 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2175 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2176 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002177 InsertText(LessLoc, "/*");
2178 InsertText(GreaterLoc, "*/");
Steve Naroff37e011c2007-10-31 04:38:33 +00002179 }
2180 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002181 if (!proto)
2182 return; // most likely, was a variable
Steve Naroff50d42052007-11-01 13:24:47 +00002183 // Now check arguments.
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002184 const char *startBuf = SM->getCharacterData(Loc);
2185 const char *startFuncBuf = startBuf;
Steve Naroff50d42052007-11-01 13:24:47 +00002186 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2187 if (needToScanForQualifiers(proto->getArgType(i))) {
2188 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002189
Steve Naroff50d42052007-11-01 13:24:47 +00002190 const char *endBuf = startBuf;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002191 // scan forward (from the decl location) for argument types.
2192 scanToNextArgument(endBuf);
Steve Naroff50d42052007-11-01 13:24:47 +00002193 const char *startRef = 0, *endRef = 0;
2194 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2195 // Get the locations of the startRef, endRef.
Mike Stump11289f42009-09-09 15:08:12 +00002196 SourceLocation LessLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002197 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump11289f42009-09-09 15:08:12 +00002198 SourceLocation GreaterLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002199 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002200 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002201 InsertText(LessLoc, "/*");
2202 InsertText(GreaterLoc, "*/");
Steve Naroff50d42052007-11-01 13:24:47 +00002203 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002204 startBuf = ++endBuf;
2205 }
2206 else {
Steve Naroffc884aa82008-08-06 15:58:23 +00002207 // If the function name is derived from a macro expansion, then the
2208 // argument buffer will not follow the name. Need to speak with Chris.
2209 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002210 startBuf++; // scan forward (from the decl location) for argument types.
2211 startBuf++;
2212 }
Steve Naroff50d42052007-11-01 13:24:47 +00002213 }
Steve Naroff37e011c2007-10-31 04:38:33 +00002214}
2215
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002216void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2217 QualType QT = ND->getType();
2218 const Type* TypePtr = QT->getAs<Type>();
2219 if (!isa<TypeOfExprType>(TypePtr))
2220 return;
2221 while (isa<TypeOfExprType>(TypePtr)) {
2222 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2223 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2224 TypePtr = QT->getAs<Type>();
2225 }
2226 // FIXME. This will not work for multiple declarators; as in:
2227 // __typeof__(a) b,c,d;
2228 std::string TypeAsString(QT.getAsString());
2229 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2230 const char *startBuf = SM->getCharacterData(DeclLoc);
2231 if (ND->getInit()) {
2232 std::string Name(ND->getNameAsString());
2233 TypeAsString += " " + Name + " = ";
2234 Expr *E = ND->getInit();
2235 SourceLocation startLoc;
2236 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2237 startLoc = ECE->getLParenLoc();
2238 else
2239 startLoc = E->getLocStart();
2240 startLoc = SM->getInstantiationLoc(startLoc);
2241 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002242 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002243 }
2244 else {
2245 SourceLocation X = ND->getLocEnd();
2246 X = SM->getInstantiationLoc(X);
2247 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002248 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002249 }
2250}
2251
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002252// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002253void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002254 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2255 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002256 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002257 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002258 &ArgTys[0], ArgTys.size(),
2259 false /*isVariadic*/, 0,
2260 false, false, 0, 0, false,
2261 CC_Default);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002262 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002263 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002264 SelGetUidIdent, getFuncType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002265 FunctionDecl::Extern, false);
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002266}
2267
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002268void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002269 // declared in <objc/objc.h>
Douglas Gregor1e21c192009-01-09 01:47:02 +00002270 if (FD->getIdentifier() &&
2271 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002272 SelGetUidFunctionDecl = FD;
Steve Naroff37e011c2007-10-31 04:38:33 +00002273 return;
2274 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002275 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002276}
2277
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002278static void RewriteBlockPointerType(std::string& Str, QualType Type) {
2279 std::string TypeString(Type.getAsString());
2280 const char *argPtr = TypeString.c_str();
2281 if (!strchr(argPtr, '^')) {
2282 Str += TypeString;
2283 return;
2284 }
2285 while (*argPtr) {
2286 Str += (*argPtr == '^' ? '*' : *argPtr);
2287 argPtr++;
2288 }
2289}
2290
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002291// FIXME. Consolidate this routine with RewriteBlockPointerType.
2292static void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD) {
2293 QualType Type = VD->getType();
2294 std::string TypeString(Type.getAsString());
2295 const char *argPtr = TypeString.c_str();
2296 int paren = 0;
2297 while (*argPtr) {
2298 switch (*argPtr) {
2299 case '(':
2300 Str += *argPtr;
2301 paren++;
2302 break;
2303 case ')':
2304 Str += *argPtr;
2305 paren--;
2306 break;
2307 case '^':
2308 Str += '*';
2309 if (paren == 1)
2310 Str += VD->getNameAsString();
2311 break;
2312 default:
2313 Str += *argPtr;
2314 break;
2315 }
2316 argPtr++;
2317 }
2318}
2319
2320
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002321void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2322 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2323 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2324 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2325 if (!proto)
2326 return;
2327 QualType Type = proto->getResultType();
2328 std::string FdStr = Type.getAsString();
2329 FdStr += " ";
2330 FdStr += FD->getNameAsCString();
2331 FdStr += "(";
2332 unsigned numArgs = proto->getNumArgs();
2333 for (unsigned i = 0; i < numArgs; i++) {
2334 QualType ArgType = proto->getArgType(i);
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002335 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002336 if (i+1 < numArgs)
2337 FdStr += ", ";
2338 }
2339 FdStr += ");\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002340 InsertText(FunLocStart, FdStr);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002341 CurFunctionDeclToDeclareForBlock = 0;
2342}
2343
Steve Naroff17978c42008-03-11 17:37:02 +00002344// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002345void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroff17978c42008-03-11 17:37:02 +00002346 if (SuperContructorFunctionDecl)
2347 return;
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002348 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroff17978c42008-03-11 17:37:02 +00002349 llvm::SmallVector<QualType, 16> ArgTys;
2350 QualType argT = Context->getObjCIdType();
2351 assert(!argT.isNull() && "Can't find 'id' type");
2352 ArgTys.push_back(argT);
2353 ArgTys.push_back(argT);
2354 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2355 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002356 false, 0,
2357 false, false, 0, 0, false,
2358 CC_Default);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002359 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002360 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002361 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002362 FunctionDecl::Extern, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002363}
2364
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002365// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002366void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002367 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2368 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002369 QualType argT = Context->getObjCIdType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002370 assert(!argT.isNull() && "Can't find 'id' type");
2371 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002372 argT = Context->getObjCSelType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002373 assert(!argT.isNull() && "Can't find 'SEL' type");
2374 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002375 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002376 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002377 true /*isVariadic*/, 0,
2378 false, false, 0, 0, false,
2379 CC_Default);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002380 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002381 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002382 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002383 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002384}
2385
Steve Naroff7fa2f042007-11-15 10:28:18 +00002386// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002387void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002388 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2389 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002390 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002391 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002392 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002393 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2394 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2395 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002396 argT = Context->getObjCSelType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002397 assert(!argT.isNull() && "Can't find 'SEL' type");
2398 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002399 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff7fa2f042007-11-15 10:28:18 +00002400 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002401 true /*isVariadic*/, 0,
2402 false, false, 0, 0, false,
2403 CC_Default);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002404 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002405 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002406 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002407 FunctionDecl::Extern, false);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002408}
2409
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002410// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002411void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002412 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2413 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002414 QualType argT = Context->getObjCIdType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002415 assert(!argT.isNull() && "Can't find 'id' type");
2416 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002417 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002418 assert(!argT.isNull() && "Can't find 'SEL' type");
2419 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002420 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002421 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002422 true /*isVariadic*/, 0,
2423 false, false, 0, 0, false,
2424 CC_Default);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002425 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002426 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002427 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002428 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002429}
2430
Mike Stump11289f42009-09-09 15:08:12 +00002431// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002432// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002433void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump11289f42009-09-09 15:08:12 +00002434 IdentifierInfo *msgSendIdent =
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002435 &Context->Idents.get("objc_msgSendSuper_stret");
2436 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002437 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002438 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002439 &Context->Idents.get("objc_super"));
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002440 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2441 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2442 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002443 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002444 assert(!argT.isNull() && "Can't find 'SEL' type");
2445 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002446 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002447 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002448 true /*isVariadic*/, 0,
2449 false, false, 0, 0, false,
2450 CC_Default);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002451 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002452 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002453 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002454 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002455}
2456
Steve Naroff2e4e3852008-05-08 22:02:18 +00002457// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002458void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002459 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2460 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002461 QualType argT = Context->getObjCIdType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002462 assert(!argT.isNull() && "Can't find 'id' type");
2463 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002464 argT = Context->getObjCSelType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002465 assert(!argT.isNull() && "Can't find 'SEL' type");
2466 ArgTys.push_back(argT);
Steve Naroff2e4e3852008-05-08 22:02:18 +00002467 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002468 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002469 true /*isVariadic*/, 0,
2470 false, false, 0, 0, false,
2471 CC_Default);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002472 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002473 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002474 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002475 FunctionDecl::Extern, false);
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002476}
2477
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002478// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002479void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002480 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2481 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002482 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002483 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002484 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002485 false /*isVariadic*/, 0,
2486 false, false, 0, 0, false,
2487 CC_Default);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002488 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002489 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002490 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002491 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002492}
2493
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002494// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002495void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002496 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2497 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002498 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002499 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002500 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002501 false /*isVariadic*/, 0,
2502 false, false, 0, 0, false,
2503 CC_Default);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002504 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002505 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002506 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002507 FunctionDecl::Extern, false);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002508}
2509
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002510Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffce8e8862008-03-15 00:55:56 +00002511 QualType strType = getConstantStringStructType();
2512
2513 std::string S = "__NSConstantStringImpl_";
Steve Naroffa6141f02008-05-31 03:35:42 +00002514
2515 std::string tmpName = InFileName;
2516 unsigned i;
2517 for (i=0; i < tmpName.length(); i++) {
2518 char c = tmpName.at(i);
2519 // replace any non alphanumeric characters with '_'.
2520 if (!isalpha(c) && (c < '0' || c > '9'))
2521 tmpName[i] = '_';
2522 }
2523 S += tmpName;
2524 S += "_";
Steve Naroffce8e8862008-03-15 00:55:56 +00002525 S += utostr(NumObjCStringLiterals++);
2526
Steve Naroff00a31762008-03-27 22:29:16 +00002527 Preamble += "static __NSConstantStringImpl " + S;
2528 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2529 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffce8e8862008-03-15 00:55:56 +00002530 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek2d470fc2008-09-13 05:16:45 +00002531 std::string prettyBufS;
2532 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00002533 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2534 PrintingPolicy(LangOpts));
Steve Naroff00a31762008-03-27 22:29:16 +00002535 Preamble += prettyBuf.str();
2536 Preamble += ",";
Steve Naroff94ed6dc2009-12-06 01:48:44 +00002537 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002538
2539 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002540 &Context->Idents.get(S), strType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002541 VarDecl::Static);
Ted Kremenek5a201952009-02-07 01:47:29 +00002542 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2543 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002544 Context->getPointerType(DRE->getType()),
Steve Naroffce8e8862008-03-15 00:55:56 +00002545 SourceLocation());
Steve Naroff265a6b92007-11-08 14:30:50 +00002546 // cast to NSConstantString *
John McCall97513962010-01-15 18:39:57 +00002547 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2548 CastExpr::CK_Unknown, Unop);
Chris Lattner2e0d2602008-01-31 19:37:57 +00002549 ReplaceStmt(Exp, cast);
Steve Naroff22216db2008-12-04 23:50:32 +00002550 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff265a6b92007-11-08 14:30:50 +00002551 return cast;
Steve Naroffa397efd2007-11-03 11:27:19 +00002552}
2553
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002554ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002555 // check if we are sending a message to 'super'
Douglas Gregorffca3a22009-01-09 17:18:27 +00002556 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002557
Douglas Gregor8ea1f532008-11-04 14:56:14 +00002558 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
Mike Stump11289f42009-09-09 15:08:12 +00002559 const ObjCObjectPointerType *OPT =
John McCall9dd450b2009-09-21 23:43:11 +00002560 Super->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00002561 assert(OPT);
2562 const ObjCInterfaceType *IT = OPT->getInterfaceType();
Chris Lattnera9b3cae2008-06-21 18:04:54 +00002563 return IT->getDecl();
2564 }
2565 return 0;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002566}
2567
2568// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002569QualType RewriteObjC::getSuperStructType() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002570 if (!SuperStructDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002571 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002572 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002573 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002574 QualType FieldTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002575
Steve Naroff7fa2f042007-11-15 10:28:18 +00002576 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002577 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002578 // struct objc_class *super;
Mike Stump11289f42009-09-09 15:08:12 +00002579 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor91f84212008-12-11 16:49:14 +00002580
Steve Naroff7fa2f042007-11-15 10:28:18 +00002581 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002582 for (unsigned i = 0; i < 2; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002583 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2584 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002585 FieldTypes[i], 0,
2586 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002587 /*Mutable=*/false));
Douglas Gregor91f84212008-12-11 16:49:14 +00002588 }
Mike Stump11289f42009-09-09 15:08:12 +00002589
Douglas Gregord5058122010-02-11 01:19:42 +00002590 SuperStructDecl->completeDefinition();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002591 }
2592 return Context->getTagDeclType(SuperStructDecl);
2593}
2594
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002595QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffce8e8862008-03-15 00:55:56 +00002596 if (!ConstantStringDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002597 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002598 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002599 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffce8e8862008-03-15 00:55:56 +00002600 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002601
Steve Naroffce8e8862008-03-15 00:55:56 +00002602 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002603 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffce8e8862008-03-15 00:55:56 +00002604 // int flags;
Mike Stump11289f42009-09-09 15:08:12 +00002605 FieldTypes[1] = Context->IntTy;
Steve Naroffce8e8862008-03-15 00:55:56 +00002606 // char *str;
Mike Stump11289f42009-09-09 15:08:12 +00002607 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffce8e8862008-03-15 00:55:56 +00002608 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002609 FieldTypes[3] = Context->LongTy;
Douglas Gregor91f84212008-12-11 16:49:14 +00002610
Steve Naroffce8e8862008-03-15 00:55:56 +00002611 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002612 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002613 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2614 ConstantStringDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002615 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002616 FieldTypes[i], 0,
Douglas Gregor91f84212008-12-11 16:49:14 +00002617 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002618 /*Mutable=*/true));
Douglas Gregor91f84212008-12-11 16:49:14 +00002619 }
2620
Douglas Gregord5058122010-02-11 01:19:42 +00002621 ConstantStringDecl->completeDefinition();
Steve Naroffce8e8862008-03-15 00:55:56 +00002622 }
2623 return Context->getTagDeclType(ConstantStringDecl);
2624}
2625
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002626Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2627 SourceLocation StartLoc,
2628 SourceLocation EndLoc) {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002629 if (!SelGetUidFunctionDecl)
2630 SynthSelGetUidFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002631 if (!MsgSendFunctionDecl)
2632 SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002633 if (!MsgSendSuperFunctionDecl)
2634 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002635 if (!MsgSendStretFunctionDecl)
2636 SynthMsgSendStretFunctionDecl();
2637 if (!MsgSendSuperStretFunctionDecl)
2638 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002639 if (!MsgSendFpretFunctionDecl)
2640 SynthMsgSendFpretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002641 if (!GetClassFunctionDecl)
2642 SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002643 if (!GetMetaClassFunctionDecl)
2644 SynthGetMetaClassFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002645
Steve Naroff7fa2f042007-11-15 10:28:18 +00002646 // default to objc_msgSend().
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002647 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2648 // May need to use objc_msgSend_stret() as well.
2649 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroffd9803712009-04-29 16:37:50 +00002650 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2651 QualType resultType = mDecl->getResultType();
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002652 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002653 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002654 else if (resultType->isRealFloatingType())
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002655 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002656 }
Mike Stump11289f42009-09-09 15:08:12 +00002657
Steve Naroff574440f2007-10-24 22:48:43 +00002658 // Synthesize a call to objc_msgSend().
2659 llvm::SmallVector<Expr*, 8> MsgExprs;
2660 IdentifierInfo *clsName = Exp->getClassName();
Mike Stump11289f42009-09-09 15:08:12 +00002661
Steve Naroff574440f2007-10-24 22:48:43 +00002662 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2663 if (clsName) { // class message.
Steve Naroff6c79f972008-07-24 19:44:33 +00002664 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2665 // the 'super' idiom within a class method.
Daniel Dunbar07d07852009-10-18 21:17:35 +00002666 if (clsName->getName() == "super") {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002667 MsgSendFlavor = MsgSendSuperFunctionDecl;
2668 if (MsgSendStretFlavor)
2669 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2670 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002671
2672 ObjCInterfaceDecl *SuperDecl =
Steve Naroff677ab3a2008-10-27 17:20:55 +00002673 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002674
2675 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002676
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002677 // set the receiver to self, the first argument to all methods.
Steve Naroffd9803712009-04-29 16:37:50 +00002678 InitExprs.push_back(
John McCall97513962010-01-15 18:39:57 +00002679 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2680 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002681 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroffd9803712009-04-29 16:37:50 +00002682 Context->getObjCIdType(),
John McCall97513962010-01-15 18:39:57 +00002683 SourceLocation()))
2684 ); // set the 'receiver'.
Steve Naroffd9803712009-04-29 16:37:50 +00002685
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002686 llvm::SmallVector<Expr*, 8> ClsExprs;
2687 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002688 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002689 SuperDecl->getIdentifier()->getNameStart(),
2690 SuperDecl->getIdentifier()->getLength(),
2691 false, argType, SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002692 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002693 &ClsExprs[0],
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002694 ClsExprs.size(),
2695 StartLoc,
2696 EndLoc);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002697 // To turn off a warning, type-cast to 'id'
Douglas Gregore200adc2008-10-27 19:41:14 +00002698 InitExprs.push_back( // set 'super class', using objc_getClass().
John McCall97513962010-01-15 18:39:57 +00002699 NoTypeInfoCStyleCastExpr(Context,
2700 Context->getObjCIdType(),
2701 CastExpr::CK_Unknown, Cls));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002702 // struct objc_super
2703 QualType superType = getSuperStructType();
Steve Naroff0b844f02008-03-11 18:14:26 +00002704 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002705
Steve Naroff0b844f02008-03-11 18:14:26 +00002706 if (LangOpts.Microsoft) {
2707 SynthSuperContructorFunctionDecl();
2708 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002709 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff0b844f02008-03-11 18:14:26 +00002710 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002711 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002712 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002713 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002714 // The code for super is a little tricky to prevent collision with
2715 // the structure definition in the header. The rewriter has it's own
2716 // internal definition (__rw_objc_super) that is uses. This is why
2717 // we need the cast below. For example:
2718 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2719 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002720 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002721 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002722 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00002723 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2724 Context->getPointerType(superType),
2725 CastExpr::CK_Unknown, SuperRep);
Mike Stump11289f42009-09-09 15:08:12 +00002726 } else {
Steve Naroff0b844f02008-03-11 18:14:26 +00002727 // (struct objc_super) { <exprs from above> }
Ted Kremenek013041e2010-02-19 01:50:18 +00002728 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2729 &InitExprs[0], InitExprs.size(),
2730 SourceLocation());
John McCalle15bbff2010-01-18 19:35:47 +00002731 TypeSourceInfo *superTInfo
2732 = Context->getTrivialTypeSourceInfo(superType);
John McCall5d7aa7f2010-01-19 22:33:45 +00002733 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2734 superType, ILE, false);
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002735 // struct objc_super *
Ted Kremenek5a201952009-02-07 01:47:29 +00002736 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002737 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002738 SourceLocation());
Steve Naroff0b844f02008-03-11 18:14:26 +00002739 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002740 MsgExprs.push_back(SuperRep);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002741 } else {
2742 llvm::SmallVector<Expr*, 8> ClsExprs;
2743 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002744 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002745 clsName->getNameStart(),
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002746 clsName->getLength(),
2747 false, argType,
2748 SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002749 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002750 &ClsExprs[0],
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002751 ClsExprs.size(),
2752 StartLoc, EndLoc);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002753 MsgExprs.push_back(Cls);
2754 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002755 } else { // instance message.
2756 Expr *recExpr = Exp->getReceiver();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002757
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002758 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002759 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002760 if (MsgSendStretFlavor)
2761 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002762 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002763
Steve Naroff7fa2f042007-11-15 10:28:18 +00002764 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002765
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002766 InitExprs.push_back(
John McCall97513962010-01-15 18:39:57 +00002767 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2768 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002769 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff97adf602008-07-16 22:35:27 +00002770 Context->getObjCIdType(),
John McCall97513962010-01-15 18:39:57 +00002771 SourceLocation()))
2772 ); // set the 'receiver'.
Mike Stump11289f42009-09-09 15:08:12 +00002773
Steve Naroff7fa2f042007-11-15 10:28:18 +00002774 llvm::SmallVector<Expr*, 8> ClsExprs;
2775 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002776 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002777 SuperDecl->getIdentifier()->getNameStart(),
2778 SuperDecl->getIdentifier()->getLength(),
2779 false, argType, SourceLocation()));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002780 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002781 &ClsExprs[0],
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002782 ClsExprs.size(),
2783 StartLoc, EndLoc);
Fariborz Jahaniand5db92b2007-12-05 17:29:46 +00002784 // To turn off a warning, type-cast to 'id'
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002785 InitExprs.push_back(
Douglas Gregore200adc2008-10-27 19:41:14 +00002786 // set 'super class', using objc_getClass().
John McCall97513962010-01-15 18:39:57 +00002787 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2788 CastExpr::CK_Unknown, Cls));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002789 // struct objc_super
2790 QualType superType = getSuperStructType();
Steve Naroff17978c42008-03-11 17:37:02 +00002791 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002792
Steve Naroff17978c42008-03-11 17:37:02 +00002793 if (LangOpts.Microsoft) {
2794 SynthSuperContructorFunctionDecl();
2795 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002796 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff17978c42008-03-11 17:37:02 +00002797 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002798 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002799 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002800 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002801 // The code for super is a little tricky to prevent collision with
2802 // the structure definition in the header. The rewriter has it's own
2803 // internal definition (__rw_objc_super) that is uses. This is why
2804 // we need the cast below. For example:
2805 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2806 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002807 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002808 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002809 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00002810 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2811 Context->getPointerType(superType),
2812 CastExpr::CK_Unknown, SuperRep);
Steve Naroff17978c42008-03-11 17:37:02 +00002813 } else {
2814 // (struct objc_super) { <exprs from above> }
Ted Kremenek013041e2010-02-19 01:50:18 +00002815 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2816 &InitExprs[0], InitExprs.size(),
2817 SourceLocation());
John McCalle15bbff2010-01-18 19:35:47 +00002818 TypeSourceInfo *superTInfo
2819 = Context->getTrivialTypeSourceInfo(superType);
John McCall5d7aa7f2010-01-19 22:33:45 +00002820 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2821 superType, ILE, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002822 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002823 MsgExprs.push_back(SuperRep);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002824 } else {
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002825 // Remove all type-casts because it may contain objc-style types; e.g.
2826 // Foo<Proto> *.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002827 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002828 recExpr = CE->getSubExpr();
John McCall97513962010-01-15 18:39:57 +00002829 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2830 CastExpr::CK_Unknown, recExpr);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002831 MsgExprs.push_back(recExpr);
2832 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002833 }
Steve Naroffa397efd2007-11-03 11:27:19 +00002834 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff574440f2007-10-24 22:48:43 +00002835 llvm::SmallVector<Expr*, 8> SelExprs;
2836 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002837 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002838 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002839 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002840 false, argType, SourceLocation()));
Steve Naroff574440f2007-10-24 22:48:43 +00002841 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002842 &SelExprs[0], SelExprs.size(),
2843 StartLoc,
2844 EndLoc);
Steve Naroff574440f2007-10-24 22:48:43 +00002845 MsgExprs.push_back(SelExp);
Mike Stump11289f42009-09-09 15:08:12 +00002846
Steve Naroff574440f2007-10-24 22:48:43 +00002847 // Now push any user supplied arguments.
2848 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroffe7f18192007-11-14 23:54:14 +00002849 Expr *userExpr = Exp->getArg(i);
Steve Narofff60782b2007-11-15 02:58:25 +00002850 // Make all implicit casts explicit...ICE comes in handy:-)
2851 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2852 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregore200adc2008-10-27 19:41:14 +00002853 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002854 ? Context->getObjCIdType()
Douglas Gregore200adc2008-10-27 19:41:14 +00002855 : ICE->getType();
John McCall97513962010-01-15 18:39:57 +00002856 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CastExpr::CK_Unknown,
2857 userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002858 }
2859 // Make id<P...> cast into an 'id' cast.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002860 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002861 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregorf19b2312008-10-28 15:36:24 +00002862 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002863 userExpr = CE->getSubExpr();
John McCall97513962010-01-15 18:39:57 +00002864 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2865 CastExpr::CK_Unknown, userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002866 }
Mike Stump11289f42009-09-09 15:08:12 +00002867 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002868 MsgExprs.push_back(userExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002869 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2870 // out the argument in the original expression (since we aren't deleting
2871 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2872 //Exp->setArg(i, 0);
Steve Naroff574440f2007-10-24 22:48:43 +00002873 }
Steve Narofff36987c2007-11-04 22:37:50 +00002874 // Generate the funky cast.
2875 CastExpr *cast;
2876 llvm::SmallVector<QualType, 8> ArgTypes;
2877 QualType returnType;
Mike Stump11289f42009-09-09 15:08:12 +00002878
Steve Narofff36987c2007-11-04 22:37:50 +00002879 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff44864e42007-11-15 10:43:57 +00002880 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2881 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2882 else
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002883 ArgTypes.push_back(Context->getObjCIdType());
2884 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattnera4997152009-02-20 18:43:26 +00002885 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Narofff36987c2007-11-04 22:37:50 +00002886 // Push any user argument types.
Chris Lattnera4997152009-02-20 18:43:26 +00002887 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2888 E = OMD->param_end(); PI != E; ++PI) {
2889 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump11289f42009-09-09 15:08:12 +00002890 ? Context->getObjCIdType()
Chris Lattnera4997152009-02-20 18:43:26 +00002891 : (*PI)->getType();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002892 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00002893 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002894 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002895 t = Context->getPointerType(BPT->getPointeeType());
2896 }
Steve Naroff98eb8d12007-11-05 14:36:37 +00002897 ArgTypes.push_back(t);
2898 }
Chris Lattnera4997152009-02-20 18:43:26 +00002899 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2900 ? Context->getObjCIdType() : OMD->getResultType();
Fariborz Jahanianf89eb2b2010-02-24 01:25:40 +00002901 if (isTopLevelBlockPointerType(returnType)) {
2902 const BlockPointerType *BPT = returnType->getAs<BlockPointerType>();
2903 returnType = Context->getPointerType(BPT->getPointeeType());
2904 }
Steve Narofff36987c2007-11-04 22:37:50 +00002905 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002906 returnType = Context->getObjCIdType();
Steve Narofff36987c2007-11-04 22:37:50 +00002907 }
2908 // Get the type, we will need to reference it in a couple spots.
Steve Naroff7fa2f042007-11-15 10:28:18 +00002909 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002910
Steve Narofff36987c2007-11-04 22:37:50 +00002911 // Create a reference to the objc_msgSend() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002912 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002913 SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002914
Mike Stump11289f42009-09-09 15:08:12 +00002915 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Narofff36987c2007-11-04 22:37:50 +00002916 // If we don't do this cast, we get the following bizarre warning/note:
2917 // xx.m:13: warning: function called through a non-compatible type
2918 // xx.m:13: note: if this code is reached, the program will abort
John McCall97513962010-01-15 18:39:57 +00002919 cast = NoTypeInfoCStyleCastExpr(Context,
2920 Context->getPointerType(Context->VoidTy),
2921 CastExpr::CK_Unknown, DRE);
Mike Stump11289f42009-09-09 15:08:12 +00002922
Steve Narofff36987c2007-11-04 22:37:50 +00002923 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002924 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002925 &ArgTypes[0], ArgTypes.size(),
Steve Naroff327f0f42008-03-18 02:02:04 +00002926 // If we don't have a method decl, force a variadic cast.
Douglas Gregor36c569f2010-02-21 22:15:06 +00002927 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0,
2928 false, false, 0, 0, false,
2929 CC_Default);
Steve Narofff36987c2007-11-04 22:37:50 +00002930 castType = Context->getPointerType(castType);
John McCall97513962010-01-15 18:39:57 +00002931 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
2932 cast);
Steve Narofff36987c2007-11-04 22:37:50 +00002933
2934 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002935 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump11289f42009-09-09 15:08:12 +00002936
John McCall9dd450b2009-09-21 23:43:11 +00002937 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002938 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002939 MsgExprs.size(),
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002940 FT->getResultType(), EndLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002941 Stmt *ReplacingStmt = CE;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002942 if (MsgSendStretFlavor) {
2943 // We have the method which returns a struct/union. Must also generate
2944 // call to objc_msgSend_stret and hang both varieties on a conditional
2945 // expression which dictate which one to envoke depending on size of
2946 // method's return type.
Mike Stump11289f42009-09-09 15:08:12 +00002947
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002948 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002949 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002950 SourceLocation());
2951 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall97513962010-01-15 18:39:57 +00002952 cast = NoTypeInfoCStyleCastExpr(Context,
2953 Context->getPointerType(Context->VoidTy),
2954 CastExpr::CK_Unknown, STDRE);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002955 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002956 castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002957 &ArgTypes[0], ArgTypes.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002958 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0,
2959 false, false, 0, 0, false,
2960 CC_Default);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002961 castType = Context->getPointerType(castType);
John McCall97513962010-01-15 18:39:57 +00002962 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
2963 cast);
Mike Stump11289f42009-09-09 15:08:12 +00002964
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002965 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002966 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002967
John McCall9dd450b2009-09-21 23:43:11 +00002968 FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002969 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002970 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002971 FT->getResultType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002972
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002973 // Build sizeof(returnType)
Mike Stump11289f42009-09-09 15:08:12 +00002974 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCallbcd03502009-12-07 02:54:59 +00002975 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl6f282892008-11-11 17:56:53 +00002976 Context->getSizeType(),
2977 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002978 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2979 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2980 // For X86 it is more complicated and some kind of target specific routine
2981 // is needed to decide what to do.
Mike Stump11289f42009-09-09 15:08:12 +00002982 unsigned IntSize =
Chris Lattner37e05872008-03-05 18:54:05 +00002983 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Mike Stump11289f42009-09-09 15:08:12 +00002984 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002985 Context->IntTy,
2986 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002987 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
2988 BinaryOperator::LE,
2989 Context->IntTy,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002990 SourceLocation());
2991 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump11289f42009-09-09 15:08:12 +00002992 ConditionalOperator *CondExpr =
Douglas Gregor7e112b02009-08-26 14:37:04 +00002993 new (Context) ConditionalOperator(lessThanExpr,
2994 SourceLocation(), CE,
2995 SourceLocation(), STCE, returnType);
Ted Kremenek5a201952009-02-07 01:47:29 +00002996 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002997 }
Mike Stump11289f42009-09-09 15:08:12 +00002998 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002999 return ReplacingStmt;
3000}
3001
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003002Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00003003 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3004 Exp->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003005
Steve Naroff574440f2007-10-24 22:48:43 +00003006 // Now do the actual rewrite.
Chris Lattner2e0d2602008-01-31 19:37:57 +00003007 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00003008
3009 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003010 return ReplacingStmt;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00003011}
3012
Steve Naroffd9803712009-04-29 16:37:50 +00003013// typedef struct objc_object Protocol;
3014QualType RewriteObjC::getProtocolType() {
3015 if (!ProtocolTypeDecl) {
John McCallbcd03502009-12-07 02:54:59 +00003016 TypeSourceInfo *TInfo
3017 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroffd9803712009-04-29 16:37:50 +00003018 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00003019 SourceLocation(),
Steve Naroffd9803712009-04-29 16:37:50 +00003020 &Context->Idents.get("Protocol"),
John McCallbcd03502009-12-07 02:54:59 +00003021 TInfo);
Steve Naroffd9803712009-04-29 16:37:50 +00003022 }
3023 return Context->getTypeDeclType(ProtocolTypeDecl);
3024}
3025
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00003026/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroffd9803712009-04-29 16:37:50 +00003027/// a synthesized/forward data reference (to the protocol's metadata).
3028/// The forward references (and metadata) are generated in
3029/// RewriteObjC::HandleTranslationUnit().
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003030Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroffd9803712009-04-29 16:37:50 +00003031 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3032 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump11289f42009-09-09 15:08:12 +00003033 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregored6c7442009-11-23 11:41:28 +00003034 ID, getProtocolType(), 0, VarDecl::Extern);
Steve Naroffd9803712009-04-29 16:37:50 +00003035 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
3036 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
3037 Context->getPointerType(DRE->getType()),
3038 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00003039 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3040 CastExpr::CK_Unknown,
3041 DerefExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00003042 ReplaceStmt(Exp, castExpr);
3043 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump11289f42009-09-09 15:08:12 +00003044 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00003045 return castExpr;
Mike Stump11289f42009-09-09 15:08:12 +00003046
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00003047}
3048
Mike Stump11289f42009-09-09 15:08:12 +00003049bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003050 const char *endBuf) {
3051 while (startBuf < endBuf) {
3052 if (*startBuf == '#') {
3053 // Skip whitespace.
3054 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3055 ;
3056 if (!strncmp(startBuf, "if", strlen("if")) ||
3057 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3058 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3059 !strncmp(startBuf, "define", strlen("define")) ||
3060 !strncmp(startBuf, "undef", strlen("undef")) ||
3061 !strncmp(startBuf, "else", strlen("else")) ||
3062 !strncmp(startBuf, "elif", strlen("elif")) ||
3063 !strncmp(startBuf, "endif", strlen("endif")) ||
3064 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3065 !strncmp(startBuf, "include", strlen("include")) ||
3066 !strncmp(startBuf, "import", strlen("import")) ||
3067 !strncmp(startBuf, "include_next", strlen("include_next")))
3068 return true;
3069 }
3070 startBuf++;
3071 }
3072 return false;
3073}
3074
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003075/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003076/// an objective-c class with ivars.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003077void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003078 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003079 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Mike Stump11289f42009-09-09 15:08:12 +00003080 assert(CDecl->getNameAsCString() &&
Douglas Gregor77324f32008-11-17 14:58:09 +00003081 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00003082 // Do not synthesize more than once.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003083 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00003084 return;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003085 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003086 int NumIvars = CDecl->ivar_size();
Steve Naroffdde78982007-11-14 19:25:57 +00003087 SourceLocation LocStart = CDecl->getLocStart();
3088 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00003089
Steve Naroffdde78982007-11-14 19:25:57 +00003090 const char *startBuf = SM->getCharacterData(LocStart);
3091 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00003092
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003093 // If no ivars and no root or if its root, directly or indirectly,
3094 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003095 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3096 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner184e65d2009-04-14 23:22:57 +00003097 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003098 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003099 return;
3100 }
Mike Stump11289f42009-09-09 15:08:12 +00003101
3102 // FIXME: This has potential of causing problem. If
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003103 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003104 Result += "\nstruct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003105 Result += CDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00003106 if (LangOpts.Microsoft)
3107 Result += "_IMPL";
Steve Naroffdc5b6b22008-03-12 00:25:36 +00003108
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003109 if (NumIvars > 0) {
Steve Naroffdde78982007-11-14 19:25:57 +00003110 const char *cursor = strchr(startBuf, '{');
Mike Stump11289f42009-09-09 15:08:12 +00003111 assert((cursor && endBuf)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003112 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003113 // If the buffer contains preprocessor directives, we do more fine-grained
3114 // rewrites. This is intended to fix code that looks like (which occurs in
3115 // NSURL.h, for example):
3116 //
3117 // #ifdef XYZ
3118 // @interface Foo : NSObject
3119 // #else
3120 // @interface FooBar : NSObject
3121 // #endif
3122 // {
3123 // int i;
3124 // }
3125 // @end
3126 //
3127 // This clause is segregated to avoid breaking the common case.
3128 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump11289f42009-09-09 15:08:12 +00003129 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003130 CDecl->getClassLoc();
3131 const char *endHeader = SM->getCharacterData(L);
Chris Lattner184e65d2009-04-14 23:22:57 +00003132 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003133
Chris Lattnerf5b77512009-02-20 18:18:36 +00003134 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003135 // advance to the end of the referenced protocols.
3136 while (endHeader < cursor && *endHeader != '>') endHeader++;
3137 endHeader++;
3138 }
3139 // rewrite the original header
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003140 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003141 } else {
3142 // rewrite the original header *without* disturbing the '{'
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003143 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003144 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003145 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroffdde78982007-11-14 19:25:57 +00003146 Result = "\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003147 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003148 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003149 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003150 Result += "_IVARS;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003151
Steve Naroffdde78982007-11-14 19:25:57 +00003152 // insert the super class structure definition.
Chris Lattner1780a852008-01-31 19:42:41 +00003153 SourceLocation OnePastCurly =
3154 LocStart.getFileLocWithOffset(cursor-startBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003155 InsertText(OnePastCurly, Result);
Steve Naroffdde78982007-11-14 19:25:57 +00003156 }
3157 cursor++; // past '{'
Mike Stump11289f42009-09-09 15:08:12 +00003158
Steve Naroffdde78982007-11-14 19:25:57 +00003159 // Now comment out any visibility specifiers.
3160 while (cursor < endBuf) {
3161 if (*cursor == '@') {
3162 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner174a8252007-11-14 22:57:51 +00003163 // Skip whitespace.
3164 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3165 /*scan*/;
3166
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003167 // FIXME: presence of @public, etc. inside comment results in
3168 // this transformation as well, which is still correct c-code.
Steve Naroffdde78982007-11-14 19:25:57 +00003169 if (!strncmp(cursor, "public", strlen("public")) ||
3170 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffaf91b9a2008-04-04 22:34:24 +00003171 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003172 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003173 InsertText(atLoc, "// ");
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003174 }
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003175 // FIXME: If there are cases where '<' is used in ivar declaration part
3176 // of user code, then scan the ivar list and use needToScanForQualifiers
3177 // for type checking.
3178 else if (*cursor == '<') {
3179 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003180 InsertText(atLoc, "/* ");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003181 cursor = strchr(cursor, '>');
3182 cursor++;
3183 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003184 InsertText(atLoc, " */");
Steve Naroff295570a2008-10-30 12:09:33 +00003185 } else if (*cursor == '^') { // rewrite block specifier.
3186 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003187 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003188 }
Steve Naroffdde78982007-11-14 19:25:57 +00003189 cursor++;
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003190 }
Steve Naroffdde78982007-11-14 19:25:57 +00003191 // Don't forget to add a ';'!!
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003192 InsertText(LocEnd.getFileLocWithOffset(1), ";");
Steve Naroffdde78982007-11-14 19:25:57 +00003193 } else { // we don't have any instance variables - insert super struct.
Chris Lattner184e65d2009-04-14 23:22:57 +00003194 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroffdde78982007-11-14 19:25:57 +00003195 Result += " {\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003196 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003197 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003198 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003199 Result += "_IVARS;\n};\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003200 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003201 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003202 // Mark this struct as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003203 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff13e74872008-05-06 18:26:51 +00003204 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003205}
3206
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003207// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003208/// class methods.
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003209template<typename MethodIterator>
3210void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3211 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +00003212 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003213 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +00003214 const char *ClassName,
3215 std::string &Result) {
Chris Lattner31bc07e2007-12-12 07:46:12 +00003216 if (MethodBegin == MethodEnd) return;
Mike Stump11289f42009-09-09 15:08:12 +00003217
Chris Lattner31bc07e2007-12-12 07:46:12 +00003218 if (!objc_impl_method) {
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003219 /* struct _objc_method {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003220 SEL _cmd;
3221 char *method_types;
3222 void *_imp;
3223 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003224 */
Chris Lattner211f8b82007-10-25 17:07:24 +00003225 Result += "\nstruct _objc_method {\n";
3226 Result += "\tSEL _cmd;\n";
3227 Result += "\tchar *method_types;\n";
3228 Result += "\tvoid *_imp;\n";
3229 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003230
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003231 objc_impl_method = true;
Fariborz Jahanian74a1cfa2007-10-19 00:36:46 +00003232 }
Mike Stump11289f42009-09-09 15:08:12 +00003233
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003234 // Build _objc_method_list for class's methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003235
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003236 /* struct {
3237 struct _objc_method_list *next_method;
3238 int method_count;
3239 struct _objc_method method_list[];
3240 }
3241 */
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003242 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003243 Result += "\nstatic struct {\n";
3244 Result += "\tstruct _objc_method_list *next_method;\n";
3245 Result += "\tint method_count;\n";
3246 Result += "\tstruct _objc_method method_list[";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003247 Result += utostr(NumMethods);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003248 Result += "];\n} _OBJC_";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003249 Result += prefix;
3250 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3251 Result += "_METHODS_";
3252 Result += ClassName;
Steve Naroffb327e492008-03-12 17:18:30 +00003253 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003254 Result += IsInstanceMethod ? "inst" : "cls";
3255 Result += "_meth\")))= ";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003256 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003257
Chris Lattner31bc07e2007-12-12 07:46:12 +00003258 Result += "\t,{{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003259 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattner31bc07e2007-12-12 07:46:12 +00003260 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003261 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattner31bc07e2007-12-12 07:46:12 +00003262 Result += "\", \"";
3263 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003264 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003265 Result += MethodInternalNames[*MethodBegin];
3266 Result += "}\n";
3267 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3268 Result += "\t ,{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003269 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003270 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003271 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003272 Result += "\", \"";
3273 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003274 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003275 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanian56338352007-11-13 21:02:00 +00003276 Result += "}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003277 }
Chris Lattner31bc07e2007-12-12 07:46:12 +00003278 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003279}
3280
Steve Naroffd9803712009-04-29 16:37:50 +00003281/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner390d39a2008-07-21 21:32:27 +00003282void RewriteObjC::
Steve Naroffd9803712009-04-29 16:37:50 +00003283RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
3284 const char *ClassName, std::string &Result) {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003285 static bool objc_protocol_methods = false;
Steve Naroffd9803712009-04-29 16:37:50 +00003286
3287 // Output struct protocol_methods holder of method selector and type.
3288 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3289 /* struct protocol_methods {
3290 SEL _cmd;
3291 char *method_types;
3292 }
3293 */
3294 Result += "\nstruct _protocol_methods {\n";
3295 Result += "\tstruct objc_selector *_cmd;\n";
3296 Result += "\tchar *method_types;\n";
3297 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003298
Steve Naroffd9803712009-04-29 16:37:50 +00003299 objc_protocol_methods = true;
3300 }
3301 // Do not synthesize the protocol more than once.
3302 if (ObjCSynthesizedProtocols.count(PDecl))
3303 return;
Mike Stump11289f42009-09-09 15:08:12 +00003304
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003305 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3306 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3307 PDecl->instmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003308 /* struct _objc_protocol_method_list {
3309 int protocol_method_count;
3310 struct protocol_methods protocols[];
3311 }
Steve Naroff251084d2008-03-12 01:06:30 +00003312 */
Steve Naroffd9803712009-04-29 16:37:50 +00003313 Result += "\nstatic struct {\n";
3314 Result += "\tint protocol_method_count;\n";
3315 Result += "\tstruct _protocol_methods protocol_methods[";
3316 Result += utostr(NumMethods);
3317 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3318 Result += PDecl->getNameAsString();
3319 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3320 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003321
Steve Naroffd9803712009-04-29 16:37:50 +00003322 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003323 for (ObjCProtocolDecl::instmeth_iterator
3324 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003325 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003326 if (I == PDecl->instmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003327 Result += "\t ,{{(struct objc_selector *)\"";
3328 else
3329 Result += "\t ,{(struct objc_selector *)\"";
3330 Result += (*I)->getSelector().getAsString().c_str();
3331 std::string MethodTypeString;
3332 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3333 Result += "\", \"";
3334 Result += MethodTypeString;
3335 Result += "\"}\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003336 }
Steve Naroffd9803712009-04-29 16:37:50 +00003337 Result += "\t }\n};\n";
3338 }
Mike Stump11289f42009-09-09 15:08:12 +00003339
Steve Naroffd9803712009-04-29 16:37:50 +00003340 // Output class methods declared in this protocol.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003341 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3342 PDecl->classmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003343 if (NumMethods > 0) {
3344 /* struct _objc_protocol_method_list {
3345 int protocol_method_count;
3346 struct protocol_methods protocols[];
3347 }
3348 */
3349 Result += "\nstatic struct {\n";
3350 Result += "\tint protocol_method_count;\n";
3351 Result += "\tstruct _protocol_methods protocol_methods[";
3352 Result += utostr(NumMethods);
3353 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3354 Result += PDecl->getNameAsString();
3355 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3356 "{\n\t";
3357 Result += utostr(NumMethods);
3358 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003359
Steve Naroffd9803712009-04-29 16:37:50 +00003360 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003361 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003362 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003363 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003364 if (I == PDecl->classmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003365 Result += "\t ,{{(struct objc_selector *)\"";
3366 else
3367 Result += "\t ,{(struct objc_selector *)\"";
3368 Result += (*I)->getSelector().getAsString().c_str();
3369 std::string MethodTypeString;
3370 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3371 Result += "\", \"";
3372 Result += MethodTypeString;
3373 Result += "\"}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003374 }
Steve Naroffd9803712009-04-29 16:37:50 +00003375 Result += "\t }\n};\n";
3376 }
3377
3378 // Output:
3379 /* struct _objc_protocol {
3380 // Objective-C 1.0 extensions
3381 struct _objc_protocol_extension *isa;
3382 char *protocol_name;
3383 struct _objc_protocol **protocol_list;
3384 struct _objc_protocol_method_list *instance_methods;
3385 struct _objc_protocol_method_list *class_methods;
Mike Stump11289f42009-09-09 15:08:12 +00003386 };
Steve Naroffd9803712009-04-29 16:37:50 +00003387 */
3388 static bool objc_protocol = false;
3389 if (!objc_protocol) {
3390 Result += "\nstruct _objc_protocol {\n";
3391 Result += "\tstruct _objc_protocol_extension *isa;\n";
3392 Result += "\tchar *protocol_name;\n";
3393 Result += "\tstruct _objc_protocol **protocol_list;\n";
3394 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3395 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003396 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003397
Steve Naroffd9803712009-04-29 16:37:50 +00003398 objc_protocol = true;
Chris Lattner388f6e92008-07-21 21:33:21 +00003399 }
Mike Stump11289f42009-09-09 15:08:12 +00003400
Steve Naroffd9803712009-04-29 16:37:50 +00003401 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3402 Result += PDecl->getNameAsString();
3403 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3404 "{\n\t0, \"";
3405 Result += PDecl->getNameAsString();
3406 Result += "\", 0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003407 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003408 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3409 Result += PDecl->getNameAsString();
3410 Result += ", ";
3411 }
3412 else
3413 Result += "0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003414 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003415 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3416 Result += PDecl->getNameAsString();
3417 Result += "\n";
3418 }
3419 else
3420 Result += "0\n";
3421 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003422
Steve Naroffd9803712009-04-29 16:37:50 +00003423 // Mark this protocol as having been generated.
3424 if (!ObjCSynthesizedProtocols.insert(PDecl))
3425 assert(false && "protocol already synthesized");
3426
3427}
3428
3429void RewriteObjC::
3430RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3431 const char *prefix, const char *ClassName,
3432 std::string &Result) {
3433 if (Protocols.empty()) return;
Mike Stump11289f42009-09-09 15:08:12 +00003434
Steve Naroffd9803712009-04-29 16:37:50 +00003435 for (unsigned i = 0; i != Protocols.size(); i++)
3436 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3437
Chris Lattner388f6e92008-07-21 21:33:21 +00003438 // Output the top lovel protocol meta-data for the class.
3439 /* struct _objc_protocol_list {
3440 struct _objc_protocol_list *next;
3441 int protocol_count;
3442 struct _objc_protocol *class_protocols[];
3443 }
3444 */
3445 Result += "\nstatic struct {\n";
3446 Result += "\tstruct _objc_protocol_list *next;\n";
3447 Result += "\tint protocol_count;\n";
3448 Result += "\tstruct _objc_protocol *class_protocols[";
3449 Result += utostr(Protocols.size());
3450 Result += "];\n} _OBJC_";
3451 Result += prefix;
3452 Result += "_PROTOCOLS_";
3453 Result += ClassName;
3454 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3455 "{\n\t0, ";
3456 Result += utostr(Protocols.size());
3457 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003458
Chris Lattner388f6e92008-07-21 21:33:21 +00003459 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003460 Result += Protocols[0]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003461 Result += " \n";
Mike Stump11289f42009-09-09 15:08:12 +00003462
Chris Lattner388f6e92008-07-21 21:33:21 +00003463 for (unsigned i = 1; i != Protocols.size(); i++) {
3464 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003465 Result += Protocols[i]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003466 Result += "\n";
3467 }
3468 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003469}
3470
Steve Naroffd9803712009-04-29 16:37:50 +00003471
Mike Stump11289f42009-09-09 15:08:12 +00003472/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003473/// implementation.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003474void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003475 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003476 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003477 // Find category declaration for this implementation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003478 ObjCCategoryDecl *CDecl;
Mike Stump11289f42009-09-09 15:08:12 +00003479 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003480 CDecl = CDecl->getNextClassCategory())
3481 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3482 break;
Mike Stump11289f42009-09-09 15:08:12 +00003483
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003484 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003485 FullCategoryName += '_';
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003486 FullCategoryName += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003487
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003488 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003489 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003490 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003491
3492 // If any of our property implementations have associated getters or
3493 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003494 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3495 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003496 Prop != PropEnd; ++Prop) {
3497 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3498 continue;
3499 if (!(*Prop)->getPropertyIvarDecl())
3500 continue;
3501 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3502 if (!PD)
3503 continue;
3504 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3505 InstanceMethods.push_back(Getter);
3506 if (PD->isReadOnly())
3507 continue;
3508 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3509 InstanceMethods.push_back(Setter);
3510 }
3511 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003512 true, "CATEGORY_", FullCategoryName.c_str(),
3513 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003514
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003515 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003516 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003517 false, "CATEGORY_", FullCategoryName.c_str(),
3518 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003519
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003520 // Protocols referenced in class declaration?
Fariborz Jahanian989e0392007-11-13 22:09:49 +00003521 // Null CDecl is case of a category implementation with no category interface
3522 if (CDecl)
Steve Naroffd9803712009-04-29 16:37:50 +00003523 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3524 FullCategoryName.c_str(), Result);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003525 /* struct _objc_category {
3526 char *category_name;
3527 char *class_name;
3528 struct _objc_method_list *instance_methods;
3529 struct _objc_method_list *class_methods;
3530 struct _objc_protocol_list *protocols;
3531 // Objective-C 1.0 extensions
3532 uint32_t size; // sizeof (struct _objc_category)
Mike Stump11289f42009-09-09 15:08:12 +00003533 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003534 // @property decl.
Mike Stump11289f42009-09-09 15:08:12 +00003535 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003536 */
Mike Stump11289f42009-09-09 15:08:12 +00003537
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003538 static bool objc_category = false;
3539 if (!objc_category) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003540 Result += "\nstruct _objc_category {\n";
3541 Result += "\tchar *category_name;\n";
3542 Result += "\tchar *class_name;\n";
3543 Result += "\tstruct _objc_method_list *instance_methods;\n";
3544 Result += "\tstruct _objc_method_list *class_methods;\n";
3545 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003546 Result += "\tunsigned int size;\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003547 Result += "\tstruct _objc_property_list *instance_properties;\n";
3548 Result += "};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003549 objc_category = true;
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003550 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003551 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3552 Result += FullCategoryName;
Steve Naroffb327e492008-03-12 17:18:30 +00003553 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003554 Result += IDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003555 Result += "\"\n\t, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003556 Result += ClassDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003557 Result += "\"\n";
Mike Stump11289f42009-09-09 15:08:12 +00003558
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003559 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003560 Result += "\t, (struct _objc_method_list *)"
3561 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3562 Result += FullCategoryName;
3563 Result += "\n";
3564 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003565 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003566 Result += "\t, 0\n";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003567 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003568 Result += "\t, (struct _objc_method_list *)"
3569 "&_OBJC_CATEGORY_CLASS_METHODS_";
3570 Result += FullCategoryName;
3571 Result += "\n";
3572 }
3573 else
3574 Result += "\t, 0\n";
Mike Stump11289f42009-09-09 15:08:12 +00003575
Chris Lattnerf5b77512009-02-20 18:18:36 +00003576 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump11289f42009-09-09 15:08:12 +00003577 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003578 Result += FullCategoryName;
3579 Result += "\n";
3580 }
3581 else
3582 Result += "\t, 0\n";
3583 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003584}
3585
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003586/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3587/// ivar offset.
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00003588void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCContainerDecl *IDecl,
Mike Stump11289f42009-09-09 15:08:12 +00003589 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003590 std::string &Result) {
Steve Naroffde7d0f62008-07-16 18:22:22 +00003591 if (ivar->isBitField()) {
3592 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3593 // place all bitfields at offset 0.
3594 Result += "0";
3595 } else {
3596 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003597 Result += IDecl->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003598 if (LangOpts.Microsoft)
3599 Result += "_IMPL";
3600 Result += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003601 Result += ivar->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003602 Result += ")";
3603 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003604}
3605
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003606//===----------------------------------------------------------------------===//
3607// Meta Data Emission
3608//===----------------------------------------------------------------------===//
3609
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003610void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003611 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003612 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00003613
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003614 // Explictly declared @interface's are already synthesized.
Steve Naroffaac654a2009-04-20 20:09:33 +00003615 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump11289f42009-09-09 15:08:12 +00003616 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003617 // produce correct synthesis as yet.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003618 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003619 }
Mike Stump11289f42009-09-09 15:08:12 +00003620
Chris Lattner30d23e82007-12-12 07:56:42 +00003621 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003622 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump11289f42009-09-09 15:08:12 +00003623 ? IDecl->ivar_size()
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003624 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003625 if (NumIvars > 0) {
3626 static bool objc_ivar = false;
3627 if (!objc_ivar) {
3628 /* struct _objc_ivar {
3629 char *ivar_name;
3630 char *ivar_type;
3631 int ivar_offset;
Mike Stump11289f42009-09-09 15:08:12 +00003632 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003633 */
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003634 Result += "\nstruct _objc_ivar {\n";
3635 Result += "\tchar *ivar_name;\n";
3636 Result += "\tchar *ivar_type;\n";
3637 Result += "\tint ivar_offset;\n";
3638 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003639
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003640 objc_ivar = true;
3641 }
3642
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003643 /* struct {
3644 int ivar_count;
3645 struct _objc_ivar ivar_list[nIvars];
Mike Stump11289f42009-09-09 15:08:12 +00003646 };
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003647 */
Mike Stump11289f42009-09-09 15:08:12 +00003648 Result += "\nstatic struct {\n";
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003649 Result += "\tint ivar_count;\n";
3650 Result += "\tstruct _objc_ivar ivar_list[";
3651 Result += utostr(NumIvars);
3652 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003653 Result += IDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003654 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003655 "{\n\t";
3656 Result += utostr(NumIvars);
3657 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003658
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003659 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor5f662052009-04-23 03:23:08 +00003660 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003661 if (!IDecl->ivar_empty()) {
Fariborz Jahanianaef66222010-02-19 00:31:17 +00003662 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003663 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor5f662052009-04-23 03:23:08 +00003664 IV != IVEnd; ++IV)
3665 IVars.push_back(*IV);
Fariborz Jahanianaef66222010-02-19 00:31:17 +00003666 IVI = IDecl->ivar_begin();
3667 IVE = IDecl->ivar_end();
Chris Lattner30d23e82007-12-12 07:56:42 +00003668 } else {
3669 IVI = CDecl->ivar_begin();
3670 IVE = CDecl->ivar_end();
3671 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003672 Result += "\t,{{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003673 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003674 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003675 std::string TmpString, StrEncoding;
3676 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3677 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003678 Result += StrEncoding;
3679 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003680 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003681 Result += "}\n";
Chris Lattner30d23e82007-12-12 07:56:42 +00003682 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003683 Result += "\t ,{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003684 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003685 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003686 std::string TmpString, StrEncoding;
3687 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3688 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003689 Result += StrEncoding;
3690 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003691 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003692 Result += "}\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003693 }
Mike Stump11289f42009-09-09 15:08:12 +00003694
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003695 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003696 }
Mike Stump11289f42009-09-09 15:08:12 +00003697
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003698 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003699 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003700 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003701
3702 // If any of our property implementations have associated getters or
3703 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003704 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3705 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003706 Prop != PropEnd; ++Prop) {
3707 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3708 continue;
3709 if (!(*Prop)->getPropertyIvarDecl())
3710 continue;
3711 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3712 if (!PD)
3713 continue;
3714 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3715 InstanceMethods.push_back(Getter);
3716 if (PD->isReadOnly())
3717 continue;
3718 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3719 InstanceMethods.push_back(Setter);
3720 }
3721 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003722 true, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003723
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003724 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003725 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003726 false, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003727
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003728 // Protocols referenced in class declaration?
Steve Naroffd9803712009-04-29 16:37:50 +00003729 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3730 "CLASS", CDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003731
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003732 // Declaration of class/meta-class metadata
3733 /* struct _objc_class {
3734 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003735 const char *super_class_name;
3736 char *name;
3737 long version;
3738 long info;
3739 long instance_size;
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003740 struct _objc_ivar_list *ivars;
3741 struct _objc_method_list *methods;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003742 struct objc_cache *cache;
3743 struct objc_protocol_list *protocols;
3744 const char *ivar_layout;
3745 struct _objc_class_ext *ext;
Mike Stump11289f42009-09-09 15:08:12 +00003746 };
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003747 */
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003748 static bool objc_class = false;
3749 if (!objc_class) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003750 Result += "\nstruct _objc_class {\n";
3751 Result += "\tstruct _objc_class *isa;\n";
3752 Result += "\tconst char *super_class_name;\n";
3753 Result += "\tchar *name;\n";
3754 Result += "\tlong version;\n";
3755 Result += "\tlong info;\n";
3756 Result += "\tlong instance_size;\n";
3757 Result += "\tstruct _objc_ivar_list *ivars;\n";
3758 Result += "\tstruct _objc_method_list *methods;\n";
3759 Result += "\tstruct objc_cache *cache;\n";
3760 Result += "\tstruct _objc_protocol_list *protocols;\n";
3761 Result += "\tconst char *ivar_layout;\n";
3762 Result += "\tstruct _objc_class_ext *ext;\n";
3763 Result += "};\n";
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003764 objc_class = true;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003765 }
Mike Stump11289f42009-09-09 15:08:12 +00003766
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003767 // Meta-class metadata generation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003768 ObjCInterfaceDecl *RootClass = 0;
3769 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003770 while (SuperClass) {
3771 RootClass = SuperClass;
3772 SuperClass = SuperClass->getSuperClass();
3773 }
3774 SuperClass = CDecl->getSuperClass();
Mike Stump11289f42009-09-09 15:08:12 +00003775
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003776 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003777 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003778 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003779 "{\n\t(struct _objc_class *)\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003780 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003781 Result += "\"";
3782
3783 if (SuperClass) {
3784 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003785 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003786 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003787 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003788 Result += "\"";
3789 }
3790 else {
3791 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003792 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003793 Result += "\"";
3794 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003795 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003796 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003797 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003798 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff0b844f02008-03-11 18:14:26 +00003799 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003800 Result += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003801 Result += "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003802 }
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003803 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003804 Result += ", 0\n";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003805 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003806 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003807 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003808 Result += ",0,0\n";
3809 }
Fariborz Jahanian486f7182007-10-24 20:54:23 +00003810 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003811 Result += "\t,0,0,0,0\n";
3812 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003813
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003814 // class metadata generation.
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003815 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003816 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003817 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003818 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003819 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003820 if (SuperClass) {
3821 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003822 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003823 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003824 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003825 Result += "\"";
3826 }
3827 else {
3828 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003829 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003830 Result += "\"";
3831 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003832 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003833 Result += ", 0,1";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003834 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003835 Result += ",0";
3836 else {
3837 // class has size. Must synthesize its size.
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00003838 Result += ",sizeof(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003839 Result += CDecl->getNameAsString();
Steve Naroff14a07462008-03-10 23:33:22 +00003840 if (LangOpts.Microsoft)
3841 Result += "_IMPL";
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003842 Result += ")";
3843 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003844 if (NumIvars > 0) {
Steve Naroff17978c42008-03-11 17:37:02 +00003845 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003846 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003847 Result += "\n\t";
3848 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003849 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003850 Result += ",0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003851 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003852 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003853 Result += CDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003854 Result += ", 0\n\t";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003855 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003856 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003857 Result += ",0,0";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003858 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003859 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003860 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003861 Result += ", 0,0\n";
3862 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003863 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003864 Result += ",0,0,0\n";
3865 Result += "};\n";
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003866}
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003867
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003868/// RewriteImplementations - This routine rewrites all method implementations
3869/// and emits meta-data.
3870
Steve Narofff8cfd162008-11-13 20:07:04 +00003871void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003872 int ClsDefCount = ClassImplementation.size();
3873 int CatDefCount = CategoryImplementation.size();
Mike Stump11289f42009-09-09 15:08:12 +00003874
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003875 // Rewrite implemented methods
3876 for (int i = 0; i < ClsDefCount; i++)
3877 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003878
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00003879 for (int i = 0; i < CatDefCount; i++)
3880 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofff8cfd162008-11-13 20:07:04 +00003881}
Mike Stump11289f42009-09-09 15:08:12 +00003882
Steve Narofff8cfd162008-11-13 20:07:04 +00003883void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3884 int ClsDefCount = ClassImplementation.size();
3885 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00003886
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003887 // For each implemented class, write out all its meta data.
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003888 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003889 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump11289f42009-09-09 15:08:12 +00003890
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003891 // For each implemented category, write out all its meta data.
3892 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003893 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroffd9803712009-04-29 16:37:50 +00003894
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003895 // Write objc_symtab metadata
3896 /*
3897 struct _objc_symtab
3898 {
3899 long sel_ref_cnt;
3900 SEL *refs;
3901 short cls_def_cnt;
3902 short cat_def_cnt;
3903 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump11289f42009-09-09 15:08:12 +00003904 };
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003905 */
Mike Stump11289f42009-09-09 15:08:12 +00003906
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003907 Result += "\nstruct _objc_symtab {\n";
3908 Result += "\tlong sel_ref_cnt;\n";
3909 Result += "\tSEL *refs;\n";
3910 Result += "\tshort cls_def_cnt;\n";
3911 Result += "\tshort cat_def_cnt;\n";
3912 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3913 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003914
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003915 Result += "static struct _objc_symtab "
Steve Naroffb327e492008-03-12 17:18:30 +00003916 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003917 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003918 + ", " + utostr(CatDefCount) + "\n";
3919 for (int i = 0; i < ClsDefCount; i++) {
3920 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003921 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003922 Result += "\n";
3923 }
Mike Stump11289f42009-09-09 15:08:12 +00003924
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003925 for (int i = 0; i < CatDefCount; i++) {
3926 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003927 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003928 Result += "_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003929 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003930 Result += "\n";
3931 }
Mike Stump11289f42009-09-09 15:08:12 +00003932
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003933 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003934
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003935 // Write objc_module metadata
Mike Stump11289f42009-09-09 15:08:12 +00003936
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003937 /*
3938 struct _objc_module {
3939 long version;
3940 long size;
3941 const char *name;
3942 struct _objc_symtab *symtab;
3943 }
3944 */
Mike Stump11289f42009-09-09 15:08:12 +00003945
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003946 Result += "\nstruct _objc_module {\n";
3947 Result += "\tlong version;\n";
3948 Result += "\tlong size;\n";
3949 Result += "\tconst char *name;\n";
3950 Result += "\tstruct _objc_symtab *symtab;\n";
3951 Result += "};\n\n";
3952 Result += "static struct _objc_module "
Steve Naroffb327e492008-03-12 17:18:30 +00003953 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003954 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003955 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003956 Result += "};\n\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003957
3958 if (LangOpts.Microsoft) {
Steve Naroffd9803712009-04-29 16:37:50 +00003959 if (ProtocolExprDecls.size()) {
3960 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
3961 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump11289f42009-09-09 15:08:12 +00003962 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00003963 E = ProtocolExprDecls.end(); I != E; ++I) {
3964 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
3965 Result += (*I)->getNameAsString();
3966 Result += " = &_OBJC_PROTOCOL_";
3967 Result += (*I)->getNameAsString();
3968 Result += ";\n";
3969 }
3970 Result += "#pragma data_seg(pop)\n\n";
3971 }
Steve Naroff945a3b12008-03-10 20:43:59 +00003972 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffcab93d52008-05-07 00:06:16 +00003973 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003974 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3975 Result += "&_OBJC_MODULES;\n";
3976 Result += "#pragma data_seg(pop)\n\n";
3977 }
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003978}
Chris Lattnera7c19fe2007-10-16 22:36:42 +00003979
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003980void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3981 const std::string &Name,
3982 ValueDecl *VD) {
3983 assert(BlockByRefDeclNo.count(VD) &&
3984 "RewriteByRefString: ByRef decl missing");
3985 ResultStr += "struct __Block_byref_" + Name +
3986 "_" + utostr(BlockByRefDeclNo[VD]) ;
3987}
3988
Steve Naroff677ab3a2008-10-27 17:20:55 +00003989std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3990 const char *funcName,
3991 std::string Tag) {
3992 const FunctionType *AFT = CE->getFunctionType();
3993 QualType RT = AFT->getResultType();
3994 std::string StructRef = "struct " + Tag;
3995 std::string S = "static " + RT.getAsString() + " __" +
3996 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00003997
Steve Naroff677ab3a2008-10-27 17:20:55 +00003998 BlockDecl *BD = CE->getBlockDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003999
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004000 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump11289f42009-09-09 15:08:12 +00004001 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Narofff26a1d42009-02-02 17:19:26 +00004002 // block (to reference imported block decl refs).
4003 S += "(" + StructRef + " *__cself)";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004004 } else if (BD->param_empty()) {
4005 S += "(" + StructRef + " *__cself)";
4006 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004007 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004008 assert(FT && "SynthesizeBlockFunc: No function proto");
4009 S += '(';
4010 // first add the implicit argument.
4011 S += StructRef + " *__cself, ";
4012 std::string ParamStr;
4013 for (BlockDecl::param_iterator AI = BD->param_begin(),
4014 E = BD->param_end(); AI != E; ++AI) {
4015 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004016 ParamStr = (*AI)->getNameAsString();
Douglas Gregor7de59662009-05-29 20:38:28 +00004017 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004018 S += ParamStr;
4019 }
4020 if (FT->isVariadic()) {
4021 if (!BD->param_empty()) S += ", ";
4022 S += "...";
4023 }
4024 S += ')';
4025 }
4026 S += " {\n";
Mike Stump11289f42009-09-09 15:08:12 +00004027
Steve Naroff677ab3a2008-10-27 17:20:55 +00004028 // Create local declarations to avoid rewriting all closure decl ref exprs.
4029 // First, emit a declaration for all "by ref" decls.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004030 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004031 E = BlockByRefDecls.end(); I != E; ++I) {
4032 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004033 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004034 std::string TypeString;
4035 RewriteByRefString(TypeString, Name, (*I));
4036 TypeString += " *";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004037 Name = TypeString + Name;
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004038 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump11289f42009-09-09 15:08:12 +00004039 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004040 // Next, emit a declaration for all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004041 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004042 E = BlockByCopyDecls.end(); I != E; ++I) {
4043 S += " ";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004044 // Handle nested closure invocation. For example:
4045 //
4046 // void (^myImportedClosure)(void);
4047 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004048 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004049 // void (^anotherClosure)(void);
4050 // anotherClosure = ^(void) {
4051 // myImportedClosure(); // import and invoke the closure
4052 // };
4053 //
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00004054 if (isTopLevelBlockPointerType((*I)->getType())) {
4055 RewriteBlockPointerTypeVariable(S, (*I));
4056 S += " = (";
4057 RewriteBlockPointerType(S, (*I)->getType());
4058 S += ")";
4059 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4060 }
4061 else {
Fariborz Jahanianb6a68c02010-02-16 17:26:03 +00004062 std::string Name = (*I)->getNameAsString();
Douglas Gregor7de59662009-05-29 20:38:28 +00004063 (*I)->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00004064 S += Name + " = __cself->" +
4065 (*I)->getNameAsString() + "; // bound by copy\n";
4066 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004067 }
4068 std::string RewrittenStr = RewrittenBlockExprs[CE];
4069 const char *cstr = RewrittenStr.c_str();
4070 while (*cstr++ != '{') ;
4071 S += cstr;
4072 S += "\n";
4073 return S;
4074}
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00004075
Steve Naroff677ab3a2008-10-27 17:20:55 +00004076std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4077 const char *funcName,
4078 std::string Tag) {
4079 std::string StructRef = "struct " + Tag;
4080 std::string S = "static void __";
Mike Stump11289f42009-09-09 15:08:12 +00004081
Steve Naroff677ab3a2008-10-27 17:20:55 +00004082 S += funcName;
4083 S += "_block_copy_" + utostr(i);
4084 S += "(" + StructRef;
4085 S += "*dst, " + StructRef;
4086 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00004087 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004088 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00004089 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004090 S += (*I)->getNameAsString();
Steve Naroff5ac4eac2008-12-11 20:51:38 +00004091 S += ", (void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004092 S += (*I)->getNameAsString();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004093 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004094 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00004095 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004096 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004097 }
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00004098 S += "}\n";
4099
Steve Naroff677ab3a2008-10-27 17:20:55 +00004100 S += "\nstatic void __";
4101 S += funcName;
4102 S += "_block_dispose_" + utostr(i);
4103 S += "(" + StructRef;
4104 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00004105 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004106 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00004107 S += "_Block_object_dispose((void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004108 S += (*I)->getNameAsString();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004109 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004110 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00004111 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004112 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004113 }
Mike Stump11289f42009-09-09 15:08:12 +00004114 S += "}\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004115 return S;
4116}
4117
Steve Naroff30484702009-12-06 21:14:13 +00004118std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4119 std::string Desc) {
Steve Naroff295570a2008-10-30 12:09:33 +00004120 std::string S = "\nstruct " + Tag;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004121 std::string Constructor = " " + Tag;
Mike Stump11289f42009-09-09 15:08:12 +00004122
Steve Naroff677ab3a2008-10-27 17:20:55 +00004123 S += " {\n struct __block_impl impl;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004124 S += " struct " + Desc;
4125 S += "* Desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00004126
Steve Naroff30484702009-12-06 21:14:13 +00004127 Constructor += "(void *fp, "; // Invoke function pointer.
4128 Constructor += "struct " + Desc; // Descriptor pointer.
4129 Constructor += " *desc";
Mike Stump11289f42009-09-09 15:08:12 +00004130
Steve Naroff677ab3a2008-10-27 17:20:55 +00004131 if (BlockDeclRefs.size()) {
4132 // Output all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004133 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004134 E = BlockByCopyDecls.end(); I != E; ++I) {
4135 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004136 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004137 std::string ArgName = "_" + FieldName;
4138 // Handle nested closure invocation. For example:
4139 //
4140 // void (^myImportedBlock)(void);
4141 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004142 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004143 // void (^anotherBlock)(void);
4144 // anotherBlock = ^(void) {
4145 // myImportedBlock(); // import and invoke the closure
4146 // };
4147 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00004148 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004149 S += "struct __block_impl *";
4150 Constructor += ", void *" + ArgName;
4151 } else {
Douglas Gregor7de59662009-05-29 20:38:28 +00004152 (*I)->getType().getAsStringInternal(FieldName, Context->PrintingPolicy);
4153 (*I)->getType().getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004154 Constructor += ", " + ArgName;
4155 }
4156 S += FieldName + ";\n";
4157 }
4158 // Output all "by ref" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004159 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004160 E = BlockByRefDecls.end(); I != E; ++I) {
4161 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004162 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004163 std::string ArgName = "_" + FieldName;
4164 // Handle nested closure invocation. For example:
4165 //
4166 // void (^myImportedBlock)(void);
4167 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004168 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004169 // void (^anotherBlock)(void);
4170 // anotherBlock = ^(void) {
4171 // myImportedBlock(); // import and invoke the closure
4172 // };
4173 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00004174 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004175 S += "struct __block_impl *";
4176 Constructor += ", void *" + ArgName;
4177 } else {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004178 std::string TypeString;
4179 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004180 TypeString += " *";
4181 FieldName = TypeString + FieldName;
4182 ArgName = TypeString + ArgName;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004183 Constructor += ", " + ArgName;
4184 }
4185 S += FieldName + "; // by ref\n";
4186 }
4187 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004188 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00004189 if (GlobalVarDecl)
4190 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4191 else
4192 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004193 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00004194
Steve Naroff30484702009-12-06 21:14:13 +00004195 Constructor += " Desc = desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00004196
Steve Naroff677ab3a2008-10-27 17:20:55 +00004197 // Initialize all "by copy" arguments.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004198 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004199 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004200 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004201 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00004202 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004203 Constructor += Name + " = (struct __block_impl *)_";
4204 else
4205 Constructor += Name + " = _";
4206 Constructor += Name + ";\n";
4207 }
4208 // Initialize all "by ref" arguments.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004209 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004210 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004211 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004212 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00004213 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004214 Constructor += Name + " = (struct __block_impl *)_";
4215 else
4216 Constructor += Name + " = _";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004217 Constructor += Name + "->__forwarding;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004218 }
4219 } else {
4220 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004221 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00004222 if (GlobalVarDecl)
4223 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4224 else
4225 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004226 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4227 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004228 }
4229 Constructor += " ";
4230 Constructor += "}\n";
4231 S += Constructor;
4232 S += "};\n";
4233 return S;
4234}
4235
Steve Naroff30484702009-12-06 21:14:13 +00004236std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4237 std::string ImplTag, int i,
4238 const char *FunName,
4239 unsigned hasCopy) {
4240 std::string S = "\nstatic struct " + DescTag;
4241
4242 S += " {\n unsigned long reserved;\n";
4243 S += " unsigned long Block_size;\n";
4244 if (hasCopy) {
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004245 S += " void (*copy)(struct ";
4246 S += ImplTag; S += "*, struct ";
4247 S += ImplTag; S += "*);\n";
4248
4249 S += " void (*dispose)(struct ";
4250 S += ImplTag; S += "*);\n";
Steve Naroff30484702009-12-06 21:14:13 +00004251 }
4252 S += "} ";
4253
4254 S += DescTag + "_DATA = { 0, sizeof(struct ";
4255 S += ImplTag + ")";
4256 if (hasCopy) {
4257 S += ", __" + std::string(FunName) + "_block_copy_" + utostr(i);
4258 S += ", __" + std::string(FunName) + "_block_dispose_" + utostr(i);
4259 }
4260 S += "};\n";
4261 return S;
4262}
4263
Steve Naroff677ab3a2008-10-27 17:20:55 +00004264void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004265 const char *FunName) {
4266 // Insert declaration for the function in which block literal is used.
Fariborz Jahanian5c26eee2010-01-15 18:14:52 +00004267 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004268 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004269 // Insert closures that were part of the function.
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004270 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4271 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004272 // Need to copy-in the inner copied-in variables not actually used in this
4273 // block.
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004274 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4275 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
4276 ValueDecl *VD = Exp->getDecl();
4277 BlockDeclRefs.push_back(Exp);
4278 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4279 BlockByCopyDeclsPtrSet.insert(VD);
4280 BlockByCopyDecls.push_back(VD);
4281 }
4282 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4283 BlockByRefDeclsPtrSet.insert(VD);
4284 BlockByRefDecls.push_back(VD);
4285 }
4286 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004287
Steve Naroff30484702009-12-06 21:14:13 +00004288 std::string ImplTag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
4289 std::string DescTag = "__" + std::string(FunName) + "_block_desc_" + utostr(i);
Mike Stump11289f42009-09-09 15:08:12 +00004290
Steve Naroff30484702009-12-06 21:14:13 +00004291 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004292
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004293 InsertText(FunLocStart, CI);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004294
Steve Naroff30484702009-12-06 21:14:13 +00004295 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump11289f42009-09-09 15:08:12 +00004296
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004297 InsertText(FunLocStart, CF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004298
4299 if (ImportedBlockDecls.size()) {
Steve Naroff30484702009-12-06 21:14:13 +00004300 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004301 InsertText(FunLocStart, HF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004302 }
Steve Naroff30484702009-12-06 21:14:13 +00004303 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4304 ImportedBlockDecls.size() > 0);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004305 InsertText(FunLocStart, BD);
Mike Stump11289f42009-09-09 15:08:12 +00004306
Steve Naroff677ab3a2008-10-27 17:20:55 +00004307 BlockDeclRefs.clear();
4308 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004309 BlockByRefDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004310 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004311 BlockByCopyDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004312 ImportedBlockDecls.clear();
4313 }
4314 Blocks.clear();
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004315 InnerDeclRefsCount.clear();
4316 InnerDeclRefs.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004317 RewrittenBlockExprs.clear();
4318}
4319
4320void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4321 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner86d7d912008-11-24 03:54:41 +00004322 const char *FuncName = FD->getNameAsCString();
Mike Stump11289f42009-09-09 15:08:12 +00004323
Steve Naroff677ab3a2008-10-27 17:20:55 +00004324 SynthesizeBlockLiterals(FunLocStart, FuncName);
4325}
4326
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004327static void BuildUniqueMethodName(std::string &Name,
4328 ObjCMethodDecl *MD) {
4329 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4330 Name = IFace->getNameAsCString();
4331 Name += "__" + MD->getSelector().getAsString();
4332 // Convert colons to underscores.
4333 std::string::size_type loc = 0;
4334 while ((loc = Name.find(":", loc)) != std::string::npos)
4335 Name.replace(loc, 1, "_");
4336}
4337
Steve Naroff677ab3a2008-10-27 17:20:55 +00004338void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff295570a2008-10-30 12:09:33 +00004339 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4340 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianb5f99c32010-01-29 01:55:49 +00004341 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004342 std::string FuncName;
4343 BuildUniqueMethodName(FuncName, MD);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004344 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
4345}
4346
4347void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4348 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4349 CI != E; ++CI)
4350 if (*CI) {
4351 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4352 GetBlockDeclRefExprs(CBE->getBody());
4353 else
4354 GetBlockDeclRefExprs(*CI);
4355 }
4356 // Handle specific things.
4357 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
4358 // FIXME: Handle enums.
4359 if (!isa<FunctionDecl>(CDRE->getDecl()))
4360 BlockDeclRefs.push_back(CDRE);
4361 return;
4362}
4363
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004364void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4365 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004366 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004367 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4368 CI != E; ++CI)
4369 if (*CI) {
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004370 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4371 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004372 GetInnerBlockDeclRefExprs(CBE->getBody(),
4373 InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004374 InnerContexts);
4375 }
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004376 else
4377 GetInnerBlockDeclRefExprs(*CI,
4378 InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004379 InnerContexts);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004380
4381 }
4382 // Handle specific things.
4383 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
4384 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004385 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004386 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004387
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004388 return;
4389}
4390
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004391Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004392 // Navigate to relevant type information.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004393 const BlockPointerType *CPT = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004394
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004395 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004396 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004397 } else if (const BlockDeclRefExpr *CDRE =
4398 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004399 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004400 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004401 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004402 }
4403 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4404 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4405 }
4406 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4407 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4408 else if (const ConditionalOperator *CEXPR =
4409 dyn_cast<ConditionalOperator>(BlockExp)) {
4410 Expr *LHSExp = CEXPR->getLHS();
4411 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4412 Expr *RHSExp = CEXPR->getRHS();
4413 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4414 Expr *CONDExp = CEXPR->getCond();
4415 ConditionalOperator *CondExpr =
4416 new (Context) ConditionalOperator(CONDExp,
4417 SourceLocation(), cast<Expr>(LHSStmt),
4418 SourceLocation(), cast<Expr>(RHSStmt),
4419 Exp->getType());
4420 return CondExpr;
Fariborz Jahanian6ab7ed42009-12-18 01:15:21 +00004421 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4422 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004423 } else {
4424 assert(1 && "RewriteBlockClass: Bad type");
4425 }
4426 assert(CPT && "RewriteBlockClass: Bad type");
John McCall9dd450b2009-09-21 23:43:11 +00004427 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004428 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004429 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004430 // FTP will be null for closures that don't take arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004431
Steve Naroff350b6652008-10-30 10:07:53 +00004432 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4433 SourceLocation(),
4434 &Context->Idents.get("__block_impl"));
4435 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff677ab3a2008-10-27 17:20:55 +00004436
Steve Naroff350b6652008-10-30 10:07:53 +00004437 // Generate a funky cast.
4438 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00004439
Steve Naroff350b6652008-10-30 10:07:53 +00004440 // Push the block argument type.
4441 ArgTypes.push_back(PtrBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004442 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004443 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff350b6652008-10-30 10:07:53 +00004444 E = FTP->arg_type_end(); I && (I != E); ++I) {
4445 QualType t = *I;
4446 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00004447 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004448 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff350b6652008-10-30 10:07:53 +00004449 t = Context->getPointerType(BPT->getPointeeType());
4450 }
4451 ArgTypes.push_back(t);
4452 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004453 }
Steve Naroff350b6652008-10-30 10:07:53 +00004454 // Now do the pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00004455 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00004456 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0,
4457 false, false, 0, 0,
4458 false, CC_Default);
Mike Stump11289f42009-09-09 15:08:12 +00004459
Steve Naroff350b6652008-10-30 10:07:53 +00004460 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump11289f42009-09-09 15:08:12 +00004461
John McCall97513962010-01-15 18:39:57 +00004462 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4463 CastExpr::CK_Unknown,
4464 const_cast<Expr*>(BlockExp));
Steve Naroff350b6652008-10-30 10:07:53 +00004465 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00004466 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4467 BlkCast);
Steve Naroff350b6652008-10-30 10:07:53 +00004468 //PE->dump();
Mike Stump11289f42009-09-09 15:08:12 +00004469
Douglas Gregor91f84212008-12-11 16:49:14 +00004470 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004471 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004472 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek5a201952009-02-07 01:47:29 +00004473 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4474 FD->getType());
Mike Stump11289f42009-09-09 15:08:12 +00004475
John McCall97513962010-01-15 18:39:57 +00004476 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4477 CastExpr::CK_Unknown, ME);
Ted Kremenek5a201952009-02-07 01:47:29 +00004478 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump11289f42009-09-09 15:08:12 +00004479
Steve Naroff350b6652008-10-30 10:07:53 +00004480 llvm::SmallVector<Expr*, 8> BlkExprs;
4481 // Add the implicit argument.
4482 BlkExprs.push_back(BlkCast);
4483 // Add the user arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004484 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004485 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00004486 BlkExprs.push_back(*I);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004487 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004488 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4489 BlkExprs.size(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004490 Exp->getType(), SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004491 return CE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004492}
4493
4494void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004495 Stmt *BlockCall = SynthesizeBlockCall(Exp, Exp->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00004496 ReplaceStmt(Exp, BlockCall);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004497}
4498
Steve Naroffd9803712009-04-29 16:37:50 +00004499// We need to return the rewritten expression to handle cases where the
4500// BlockDeclRefExpr is embedded in another expression being rewritten.
4501// For example:
4502//
4503// int main() {
4504// __block Foo *f;
4505// __block int i;
Mike Stump11289f42009-09-09 15:08:12 +00004506//
Steve Naroffd9803712009-04-29 16:37:50 +00004507// void (^myblock)() = ^() {
4508// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4509// i = 77;
4510// };
4511//}
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004512Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanian25c07fa2009-12-23 19:26:34 +00004513 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004514 // for each DeclRefExp where BYREFVAR is name of the variable.
4515 ValueDecl *VD;
4516 bool isArrow = true;
4517 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4518 VD = BDRE->getDecl();
4519 else {
4520 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4521 isArrow = false;
4522 }
4523
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004524 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4525 &Context->Idents.get("__forwarding"),
4526 Context->VoidPtrTy, 0,
4527 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004528 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4529 FD, SourceLocation(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004530 FD->getType());
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004531
4532 const char *Name = VD->getNameAsCString();
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004533 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4534 &Context->Idents.get(Name),
4535 Context->VoidPtrTy, 0,
4536 /*BitWidth=*/0, /*Mutable=*/true);
4537 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004538 DeclRefExp->getType());
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004539
4540
4541
Steve Narofff26a1d42009-02-02 17:19:26 +00004542 // Need parens to enforce precedence.
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004543 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4544 ME);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004545 ReplaceStmt(DeclRefExp, PE);
Steve Naroffd9803712009-04-29 16:37:50 +00004546 return PE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004547}
4548
Steve Naroffc989a7b2008-11-03 23:29:32 +00004549void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4550 SourceLocation LocStart = CE->getLParenLoc();
4551 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofff4b992a2008-10-28 20:29:00 +00004552
4553 // Need to avoid trying to rewrite synthesized casts.
4554 if (LocStart.isInvalid())
4555 return;
Steve Naroff3e7ced12008-11-03 11:20:24 +00004556 // Need to avoid trying to rewrite casts contained in macros.
4557 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4558 return;
Mike Stump11289f42009-09-09 15:08:12 +00004559
Steve Naroff677ab3a2008-10-27 17:20:55 +00004560 const char *startBuf = SM->getCharacterData(LocStart);
4561 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004562 QualType QT = CE->getType();
4563 const Type* TypePtr = QT->getAs<Type>();
4564 if (isa<TypeOfExprType>(TypePtr)) {
4565 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4566 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4567 std::string TypeAsString = "(";
Fariborz Jahanianf5067912010-02-18 01:20:22 +00004568 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004569 TypeAsString += ")";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004570 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004571 return;
4572 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004573 // advance the location to startArgList.
4574 const char *argPtr = startBuf;
Mike Stump11289f42009-09-09 15:08:12 +00004575
Steve Naroff677ab3a2008-10-27 17:20:55 +00004576 while (*argPtr++ && (argPtr < endBuf)) {
4577 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004578 case '^':
4579 // Replace the '^' with '*'.
4580 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004581 ReplaceText(LocStart, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00004582 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004583 }
4584 }
4585 return;
4586}
4587
4588void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4589 SourceLocation DeclLoc = FD->getLocation();
4590 unsigned parenCount = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004591
Steve Naroff677ab3a2008-10-27 17:20:55 +00004592 // We have 1 or more arguments that have closure pointers.
4593 const char *startBuf = SM->getCharacterData(DeclLoc);
4594 const char *startArgList = strchr(startBuf, '(');
Mike Stump11289f42009-09-09 15:08:12 +00004595
Steve Naroff677ab3a2008-10-27 17:20:55 +00004596 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004597
Steve Naroff677ab3a2008-10-27 17:20:55 +00004598 parenCount++;
4599 // advance the location to startArgList.
4600 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4601 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump11289f42009-09-09 15:08:12 +00004602
Steve Naroff677ab3a2008-10-27 17:20:55 +00004603 const char *argPtr = startArgList;
Mike Stump11289f42009-09-09 15:08:12 +00004604
Steve Naroff677ab3a2008-10-27 17:20:55 +00004605 while (*argPtr++ && parenCount) {
4606 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004607 case '^':
4608 // Replace the '^' with '*'.
4609 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004610 ReplaceText(DeclLoc, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00004611 break;
4612 case '(':
4613 parenCount++;
4614 break;
4615 case ')':
4616 parenCount--;
4617 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004618 }
4619 }
4620 return;
4621}
4622
4623bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004624 const FunctionProtoType *FTP;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004625 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004626 if (PT) {
John McCall9dd450b2009-09-21 23:43:11 +00004627 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004628 } else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004629 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004630 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall9dd450b2009-09-21 23:43:11 +00004631 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004632 }
4633 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004634 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004635 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +00004636 if (isTopLevelBlockPointerType(*I))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004637 return true;
4638 }
4639 return false;
4640}
4641
Ted Kremenek5a201952009-02-07 01:47:29 +00004642void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4643 const char *&RParen) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004644 const char *argPtr = strchr(Name, '(');
4645 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004646
Steve Naroff677ab3a2008-10-27 17:20:55 +00004647 LParen = argPtr; // output the start.
4648 argPtr++; // skip past the left paren.
4649 unsigned parenCount = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004650
Steve Naroff677ab3a2008-10-27 17:20:55 +00004651 while (*argPtr && parenCount) {
4652 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004653 case '(': parenCount++; break;
4654 case ')': parenCount--; break;
4655 default: break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004656 }
4657 if (parenCount) argPtr++;
4658 }
4659 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4660 RParen = argPtr; // output the end
4661}
4662
4663void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4664 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4665 RewriteBlockPointerFunctionArgs(FD);
4666 return;
Mike Stump11289f42009-09-09 15:08:12 +00004667 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004668 // Handle Variables and Typedefs.
4669 SourceLocation DeclLoc = ND->getLocation();
4670 QualType DeclT;
4671 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4672 DeclT = VD->getType();
4673 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4674 DeclT = TDD->getUnderlyingType();
4675 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4676 DeclT = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004677 else
Steve Naroff677ab3a2008-10-27 17:20:55 +00004678 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump11289f42009-09-09 15:08:12 +00004679
Steve Naroff677ab3a2008-10-27 17:20:55 +00004680 const char *startBuf = SM->getCharacterData(DeclLoc);
4681 const char *endBuf = startBuf;
4682 // scan backward (from the decl location) for the end of the previous decl.
4683 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4684 startBuf--;
Mike Stump11289f42009-09-09 15:08:12 +00004685
Steve Naroff677ab3a2008-10-27 17:20:55 +00004686 // *startBuf != '^' if we are dealing with a pointer to function that
4687 // may take block argument types (which will be handled below).
4688 if (*startBuf == '^') {
4689 // Replace the '^' with '*', computing a negative offset.
4690 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004691 ReplaceText(DeclLoc, 1, "*");
Steve Naroff677ab3a2008-10-27 17:20:55 +00004692 }
4693 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4694 // Replace the '^' with '*' for arguments.
4695 DeclLoc = ND->getLocation();
4696 startBuf = SM->getCharacterData(DeclLoc);
4697 const char *argListBegin, *argListEnd;
4698 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4699 while (argListBegin < argListEnd) {
4700 if (*argListBegin == '^') {
4701 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004702 ReplaceText(CaretLoc, 1, "*");
Steve Naroff677ab3a2008-10-27 17:20:55 +00004703 }
4704 argListBegin++;
4705 }
4706 }
4707 return;
4708}
4709
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004710
4711/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4712/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4713/// struct Block_byref_id_object *src) {
4714/// _Block_object_assign (&_dest->object, _src->object,
4715/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4716/// [|BLOCK_FIELD_IS_WEAK]) // object
4717/// _Block_object_assign(&_dest->object, _src->object,
4718/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4719/// [|BLOCK_FIELD_IS_WEAK]) // block
4720/// }
4721/// And:
4722/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4723/// _Block_object_dispose(_src->object,
4724/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4725/// [|BLOCK_FIELD_IS_WEAK]) // object
4726/// _Block_object_dispose(_src->object,
4727/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4728/// [|BLOCK_FIELD_IS_WEAK]) // block
4729/// }
4730
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004731std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4732 int flag) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004733 std::string S;
Benjamin Kramere056cea2010-01-10 19:57:50 +00004734 if (CopyDestroyCache.count(flag))
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004735 return S;
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004736 CopyDestroyCache.insert(flag);
4737 S = "static void __Block_byref_id_object_copy_";
4738 S += utostr(flag);
4739 S += "(void *dst, void *src) {\n";
4740
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004741 // offset into the object pointer is computed as:
4742 // void * + void* + int + int + void* + void *
4743 unsigned IntSize =
4744 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4745 unsigned VoidPtrSize =
4746 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4747
4748 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
4749 S += " _Block_object_assign((char*)dst + ";
4750 S += utostr(offset);
4751 S += ", *(void * *) ((char*)src + ";
4752 S += utostr(offset);
4753 S += "), ";
4754 S += utostr(flag);
4755 S += ");\n}\n";
4756
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004757 S += "static void __Block_byref_id_object_dispose_";
4758 S += utostr(flag);
4759 S += "(void *src) {\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004760 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4761 S += utostr(offset);
4762 S += "), ";
4763 S += utostr(flag);
4764 S += ");\n}\n";
4765 return S;
4766}
4767
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004768/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4769/// the declaration into:
4770/// struct __Block_byref_ND {
4771/// void *__isa; // NULL for everything except __weak pointers
4772/// struct __Block_byref_ND *__forwarding;
4773/// int32_t __flags;
4774/// int32_t __size;
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004775/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4776/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004777/// typex ND;
4778/// };
4779///
4780/// It then replaces declaration of ND variable with:
4781/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4782/// __size=sizeof(struct __Block_byref_ND),
4783/// ND=initializer-if-any};
4784///
4785///
4786void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004787 // Insert declaration for the function in which block literal is
4788 // used.
4789 if (CurFunctionDeclToDeclareForBlock)
4790 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004791 int flag = 0;
4792 int isa = 0;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004793 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahanian6005bd82010-02-26 22:49:11 +00004794 if (DeclLoc.isInvalid())
4795 // If type location is missing, it is because of missing type (a warning).
4796 // Use variable's location which is good for this case.
4797 DeclLoc = ND->getLocation();
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004798 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian92368a12009-12-30 20:38:08 +00004799 SourceLocation X = ND->getLocEnd();
4800 X = SM->getInstantiationLoc(X);
4801 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004802 std::string Name(ND->getNameAsString());
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004803 std::string ByrefType;
4804 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004805 ByrefType += " {\n";
4806 ByrefType += " void *__isa;\n";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004807 RewriteByRefString(ByrefType, Name, ND);
4808 ByrefType += " *__forwarding;\n";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004809 ByrefType += " int __flags;\n";
4810 ByrefType += " int __size;\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004811 // Add void *__Block_byref_id_object_copy;
4812 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004813 QualType Ty = ND->getType();
4814 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4815 if (HasCopyAndDispose) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004816 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4817 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004818 }
4819
4820 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004821 ByrefType += " " + Name + ";\n";
4822 ByrefType += "};\n";
4823 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004824 SourceLocation FunLocStart;
4825 if (CurFunctionDef)
4826 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4827 else {
4828 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4829 FunLocStart = CurMethodDef->getLocStart();
4830 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004831 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004832 if (Ty.isObjCGCWeak()) {
4833 flag |= BLOCK_FIELD_IS_WEAK;
4834 isa = 1;
4835 }
4836
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004837 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004838 flag = BLOCK_BYREF_CALLER;
4839 QualType Ty = ND->getType();
4840 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4841 if (Ty->isBlockPointerType())
4842 flag |= BLOCK_FIELD_IS_BLOCK;
4843 else
4844 flag |= BLOCK_FIELD_IS_OBJECT;
4845 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004846 if (!HF.empty())
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004847 InsertText(FunLocStart, HF);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004848 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004849
4850 // struct __Block_byref_ND ND =
4851 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4852 // initializer-if-any};
4853 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanianf7945432010-01-05 18:15:57 +00004854 unsigned flags = 0;
4855 if (HasCopyAndDispose)
4856 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004857 Name = ND->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004858 ByrefType.clear();
4859 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004860 std::string ForwardingCastType("(");
4861 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004862 if (!hasInit) {
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004863 ByrefType += " " + Name + " = {(void*)";
4864 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004865 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004866 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004867 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004868 ByrefType += "sizeof(";
4869 RewriteByRefString(ByrefType, Name, ND);
4870 ByrefType += ")";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004871 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004872 ByrefType += ", __Block_byref_id_object_copy_";
4873 ByrefType += utostr(flag);
4874 ByrefType += ", __Block_byref_id_object_dispose_";
4875 ByrefType += utostr(flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004876 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004877 ByrefType += "};\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004878 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(), ByrefType);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004879 }
4880 else {
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004881 SourceLocation startLoc;
4882 Expr *E = ND->getInit();
4883 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4884 startLoc = ECE->getLParenLoc();
4885 else
4886 startLoc = E->getLocStart();
Fariborz Jahanianb8646ed2010-01-05 23:06:29 +00004887 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004888 endBuf = SM->getCharacterData(startLoc);
4889
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004890 ByrefType += " " + Name;
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004891 ByrefType += " = {(void*)";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004892 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004893 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004894 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004895 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004896 ByrefType += "sizeof(";
4897 RewriteByRefString(ByrefType, Name, ND);
4898 ByrefType += "), ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004899 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004900 ByrefType += "__Block_byref_id_object_copy_";
4901 ByrefType += utostr(flag);
4902 ByrefType += ", __Block_byref_id_object_dispose_";
4903 ByrefType += utostr(flag);
4904 ByrefType += ", ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004905 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004906 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroff13468372009-12-23 17:24:33 +00004907
4908 // Complete the newly synthesized compound expression by inserting a right
4909 // curly brace before the end of the declaration.
4910 // FIXME: This approach avoids rewriting the initializer expression. It
4911 // also assumes there is only one declarator. For example, the following
4912 // isn't currently supported by this routine (in general):
4913 //
4914 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4915 //
4916 const char *startBuf = SM->getCharacterData(startLoc);
4917 const char *semiBuf = strchr(startBuf, ';');
4918 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4919 SourceLocation semiLoc =
4920 startLoc.getFileLocWithOffset(semiBuf-startBuf);
4921
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004922 InsertText(semiLoc, "}");
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004923 }
Fariborz Jahanian81203462009-12-22 00:48:54 +00004924 return;
4925}
4926
Mike Stump11289f42009-09-09 15:08:12 +00004927void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004928 // Add initializers for any closure decl refs.
4929 GetBlockDeclRefExprs(Exp->getBody());
4930 if (BlockDeclRefs.size()) {
4931 // Unique all "by copy" declarations.
4932 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004933 if (!BlockDeclRefs[i]->isByRef()) {
4934 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4935 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4936 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4937 }
4938 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004939 // Unique all "by ref" declarations.
4940 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4941 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004942 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4943 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4944 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4945 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004946 }
4947 // Find any imported blocks...they will need special attention.
4948 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004949 if (BlockDeclRefs[i]->isByRef() ||
4950 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian9bbc1482010-02-26 21:46:27 +00004951 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff677ab3a2008-10-27 17:20:55 +00004952 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff677ab3a2008-10-27 17:20:55 +00004953 }
4954}
4955
Steve Narofff4b992a2008-10-28 20:29:00 +00004956FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4957 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004958 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump11289f42009-09-09 15:08:12 +00004959 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004960 ID, FType, 0, FunctionDecl::Extern, false,
Douglas Gregor739ef0c2009-02-25 16:33:18 +00004961 false);
Steve Narofff4b992a2008-10-28 20:29:00 +00004962}
4963
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004964Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
4965 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004966 Blocks.push_back(Exp);
4967
4968 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004969
4970 // Add inner imported variables now used in current block.
4971 int countOfInnerDecls = 0;
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004972 if (!InnerBlockDeclRefs.empty()) {
4973 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
4974 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
4975 ValueDecl *VD = Exp->getDecl();
4976 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004977 // We need to save the copied-in variables in nested
4978 // blocks because it is needed at the end for some of the API generations.
4979 // See SynthesizeBlockLiterals routine.
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004980 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4981 BlockDeclRefs.push_back(Exp);
4982 BlockByCopyDeclsPtrSet.insert(VD);
4983 BlockByCopyDecls.push_back(VD);
4984 }
4985 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4986 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4987 BlockDeclRefs.push_back(Exp);
4988 BlockByRefDeclsPtrSet.insert(VD);
4989 BlockByRefDecls.push_back(VD);
4990 }
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004991 }
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004992 // Find any imported blocks...they will need special attention.
4993 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
4994 if (InnerBlockDeclRefs[i]->isByRef() ||
4995 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4996 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4997 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004998 }
4999 InnerDeclRefsCount.push_back(countOfInnerDecls);
5000
Steve Narofff4b992a2008-10-28 20:29:00 +00005001 std::string FuncName;
Mike Stump11289f42009-09-09 15:08:12 +00005002
Steve Narofff4b992a2008-10-28 20:29:00 +00005003 if (CurFunctionDef)
Chris Lattnere4b95692008-11-24 03:33:13 +00005004 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00005005 else if (CurMethodDef)
5006 BuildUniqueMethodName(FuncName, CurMethodDef);
5007 else if (GlobalVarDecl)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005008 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +00005009
Steve Narofff4b992a2008-10-28 20:29:00 +00005010 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump11289f42009-09-09 15:08:12 +00005011
Steve Narofff4b992a2008-10-28 20:29:00 +00005012 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
5013 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump11289f42009-09-09 15:08:12 +00005014
Steve Narofff4b992a2008-10-28 20:29:00 +00005015 // Get a pointer to the function type so we can cast appropriately.
5016 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
5017
5018 FunctionDecl *FD;
5019 Expr *NewRep;
Mike Stump11289f42009-09-09 15:08:12 +00005020
Steve Narofff4b992a2008-10-28 20:29:00 +00005021 // Simulate a contructor call...
5022 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00005023 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00005024
Steve Narofff4b992a2008-10-28 20:29:00 +00005025 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00005026
Steve Naroffe2514232008-10-29 21:23:59 +00005027 // Initialize the block function.
Steve Narofff4b992a2008-10-28 20:29:00 +00005028 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00005029 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
5030 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00005031 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5032 CastExpr::CK_Unknown, Arg);
Mike Stump11289f42009-09-09 15:08:12 +00005033 InitExprs.push_back(castExpr);
5034
Steve Naroff30484702009-12-06 21:14:13 +00005035 // Initialize the block descriptor.
5036 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump11289f42009-09-09 15:08:12 +00005037
Steve Naroff30484702009-12-06 21:14:13 +00005038 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
5039 &Context->Idents.get(DescData.c_str()),
5040 Context->VoidPtrTy, 0,
5041 VarDecl::Static);
5042 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
5043 new (Context) DeclRefExpr(NewVD,
5044 Context->VoidPtrTy, SourceLocation()),
5045 UnaryOperator::AddrOf,
5046 Context->getPointerType(Context->VoidPtrTy),
5047 SourceLocation());
5048 InitExprs.push_back(DescRefExpr);
5049
Steve Narofff4b992a2008-10-28 20:29:00 +00005050 // Add initializers for any closure decl refs.
5051 if (BlockDeclRefs.size()) {
Steve Naroffe2514232008-10-29 21:23:59 +00005052 Expr *Exp;
Steve Narofff4b992a2008-10-28 20:29:00 +00005053 // Output all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005054 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00005055 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005056 if (isObjCType((*I)->getType())) {
Steve Naroffe2514232008-10-29 21:23:59 +00005057 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner86d7d912008-11-24 03:54:41 +00005058 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00005059 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroffa5c0db82008-12-11 21:05:33 +00005060 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner86d7d912008-11-24 03:54:41 +00005061 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00005062 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
John McCall97513962010-01-15 18:39:57 +00005063 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5064 CastExpr::CK_Unknown, Arg);
Steve Narofff4b992a2008-10-28 20:29:00 +00005065 } else {
Chris Lattner86d7d912008-11-24 03:54:41 +00005066 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00005067 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00005068 }
Mike Stump11289f42009-09-09 15:08:12 +00005069 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00005070 }
5071 // Output all "by ref" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005072 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00005073 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005074 ValueDecl *ND = (*I);
5075 std::string Name(ND->getNameAsString());
5076 std::string RecName;
5077 RewriteByRefString(RecName, Name, ND);
5078 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5079 + sizeof("struct"));
5080 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
5081 SourceLocation(), II);
5082 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5083 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5084
Chris Lattner86d7d912008-11-24 03:54:41 +00005085 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00005086 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
5087 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00005088 Context->getPointerType(Exp->getType()),
Steve Naroffe2514232008-10-29 21:23:59 +00005089 SourceLocation());
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005090 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CastExpr::CK_Unknown, Exp);
Mike Stump11289f42009-09-09 15:08:12 +00005091 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00005092 }
5093 }
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00005094 if (ImportedBlockDecls.size()) {
5095 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5096 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff30484702009-12-06 21:14:13 +00005097 unsigned IntSize =
5098 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00005099 Expr *FlagExp = new (Context) IntegerLiteral(llvm::APInt(IntSize, flag),
5100 Context->IntTy, SourceLocation());
5101 InitExprs.push_back(FlagExp);
Steve Naroff30484702009-12-06 21:14:13 +00005102 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00005103 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
5104 FType, SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00005105 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00005106 Context->getPointerType(NewRep->getType()),
Steve Narofff4b992a2008-10-28 20:29:00 +00005107 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00005108 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CastExpr::CK_Unknown,
5109 NewRep);
Steve Narofff4b992a2008-10-28 20:29:00 +00005110 BlockDeclRefs.clear();
5111 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005112 BlockByRefDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00005113 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005114 BlockByCopyDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00005115 ImportedBlockDecls.clear();
5116 return NewRep;
5117}
5118
5119//===----------------------------------------------------------------------===//
5120// Function Body / Expression rewriting
5121//===----------------------------------------------------------------------===//
5122
Steve Naroff4588d0f2008-12-04 16:24:46 +00005123// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
5124// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
5125// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
5126// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
5127// Since the rewriter isn't capable of rewriting rewritten code, it's important
5128// we get this right.
5129void RewriteObjC::CollectPropertySetters(Stmt *S) {
5130 // Perform a bottom up traversal of all children.
5131 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5132 CI != E; ++CI)
5133 if (*CI)
5134 CollectPropertySetters(*CI);
5135
5136 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
5137 if (BinOp->isAssignmentOp()) {
5138 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
5139 PropSetters[PRE] = BinOp;
5140 }
5141 }
5142}
5143
Steve Narofff4b992a2008-10-28 20:29:00 +00005144Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump11289f42009-09-09 15:08:12 +00005145 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00005146 isa<DoStmt>(S) || isa<ForStmt>(S))
5147 Stmts.push_back(S);
5148 else if (isa<ObjCForCollectionStmt>(S)) {
5149 Stmts.push_back(S);
Chris Lattnerb71980f2010-01-09 21:45:57 +00005150 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofff4b992a2008-10-28 20:29:00 +00005151 }
Mike Stump11289f42009-09-09 15:08:12 +00005152
Steve Narofff4b992a2008-10-28 20:29:00 +00005153 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005154
Steve Narofff4b992a2008-10-28 20:29:00 +00005155 // Perform a bottom up rewrite of all children.
5156 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5157 CI != E; ++CI)
5158 if (*CI) {
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00005159 Stmt *newStmt;
5160 Stmt *S = (*CI);
5161 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5162 Expr *OldBase = IvarRefExpr->getBase();
5163 bool replaced = false;
5164 newStmt = RewriteObjCNestedIvarRefExpr(S, replaced);
5165 if (replaced) {
5166 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
5167 ReplaceStmt(OldBase, IRE->getBase());
5168 else
5169 ReplaceStmt(S, newStmt);
5170 }
5171 }
5172 else
5173 newStmt = RewriteFunctionBodyOrGlobalInitializer(S);
Mike Stump11289f42009-09-09 15:08:12 +00005174 if (newStmt)
Steve Narofff4b992a2008-10-28 20:29:00 +00005175 *CI = newStmt;
5176 }
Mike Stump11289f42009-09-09 15:08:12 +00005177
Steve Narofff4b992a2008-10-28 20:29:00 +00005178 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005179 llvm::SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00005180 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5181 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005182 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00005183 InnerBlockDeclRefs, InnerContexts);
Steve Narofff4b992a2008-10-28 20:29:00 +00005184 // Rewrite the block body in place.
5185 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Mike Stump11289f42009-09-09 15:08:12 +00005186
Steve Narofff4b992a2008-10-28 20:29:00 +00005187 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenekdb2ef372010-01-07 18:00:35 +00005188 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroffd8907b72008-10-29 18:15:37 +00005189 RewrittenBlockExprs[BE] = Str;
Mike Stump11289f42009-09-09 15:08:12 +00005190
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005191 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5192
Steve Narofff4b992a2008-10-28 20:29:00 +00005193 //blockTranscribed->dump();
Steve Naroffd8907b72008-10-29 18:15:37 +00005194 ReplaceStmt(S, blockTranscribed);
Steve Narofff4b992a2008-10-28 20:29:00 +00005195 return blockTranscribed;
5196 }
5197 // Handle specific things.
5198 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5199 return RewriteAtEncode(AtEncode);
Mike Stump11289f42009-09-09 15:08:12 +00005200
Steve Naroff4588d0f2008-12-04 16:24:46 +00005201 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
5202 BinaryOperator *BinOp = PropSetters[PropRefExpr];
5203 if (BinOp) {
5204 // Because the rewriter doesn't allow us to rewrite rewritten code,
5205 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroff08628db2008-12-09 12:56:34 +00005206 DisableReplaceStmt = true;
5207 // Save the source range. Even if we disable the replacement, the
5208 // rewritten node will have been inserted into the tree. If the synthesized
5209 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump11289f42009-09-09 15:08:12 +00005210 // self.errorHandler = handler ? handler :
Steve Naroff08628db2008-12-09 12:56:34 +00005211 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5212 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroff4588d0f2008-12-04 16:24:46 +00005213 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroff08628db2008-12-09 12:56:34 +00005214 DisableReplaceStmt = false;
Steve Naroff22216db2008-12-04 23:50:32 +00005215 //
5216 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
5217 // we changed the RHS of BinOp, the rewriter would fail (since it needs
5218 // to see the original expression). Consider this example:
5219 //
5220 // Foo *obj1, *obj2;
5221 //
5222 // obj1.i = [obj2 rrrr];
5223 //
5224 // 'BinOp' for the previous expression looks like:
5225 //
5226 // (BinaryOperator 0x231ccf0 'int' '='
5227 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5228 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5229 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5230 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5231 //
5232 // 'newStmt' represents the rewritten message expression. For example:
5233 //
5234 // (CallExpr 0x231d300 'id':'struct objc_object *'
5235 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5236 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5237 // (CStyleCastExpr 0x231d220 'void *'
5238 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5239 //
5240 // Note that 'newStmt' is passed to RewritePropertySetter so that it
5241 // can be used as the setter argument. ReplaceStmt() will still 'see'
5242 // the original RHS (since we haven't altered BinOp).
5243 //
Mike Stump11289f42009-09-09 15:08:12 +00005244 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff22216db2008-12-04 23:50:32 +00005245 // node. As a result, we now leak the original AST nodes.
5246 //
Steve Naroff08628db2008-12-09 12:56:34 +00005247 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroff4588d0f2008-12-04 16:24:46 +00005248 } else {
5249 return RewritePropertyGetter(PropRefExpr);
Steve Narofff326f402008-12-03 00:56:33 +00005250 }
5251 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005252 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5253 return RewriteAtSelector(AtSelector);
Mike Stump11289f42009-09-09 15:08:12 +00005254
Steve Narofff4b992a2008-10-28 20:29:00 +00005255 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5256 return RewriteObjCStringLiteral(AtString);
Mike Stump11289f42009-09-09 15:08:12 +00005257
Steve Narofff4b992a2008-10-28 20:29:00 +00005258 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00005259#if 0
Steve Narofff4b992a2008-10-28 20:29:00 +00005260 // Before we rewrite it, put the original message expression in a comment.
5261 SourceLocation startLoc = MessExpr->getLocStart();
5262 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00005263
Steve Narofff4b992a2008-10-28 20:29:00 +00005264 const char *startBuf = SM->getCharacterData(startLoc);
5265 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump11289f42009-09-09 15:08:12 +00005266
Steve Narofff4b992a2008-10-28 20:29:00 +00005267 std::string messString;
5268 messString += "// ";
5269 messString.append(startBuf, endBuf-startBuf+1);
5270 messString += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00005271
5272 // FIXME: Missing definition of
Steve Narofff4b992a2008-10-28 20:29:00 +00005273 // InsertText(clang::SourceLocation, char const*, unsigned int).
5274 // InsertText(startLoc, messString.c_str(), messString.size());
5275 // Tried this, but it didn't work either...
5276 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff4588d0f2008-12-04 16:24:46 +00005277#endif
Steve Narofff4b992a2008-10-28 20:29:00 +00005278 return RewriteMessageExpr(MessExpr);
5279 }
Mike Stump11289f42009-09-09 15:08:12 +00005280
Steve Narofff4b992a2008-10-28 20:29:00 +00005281 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5282 return RewriteObjCTryStmt(StmtTry);
5283
5284 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5285 return RewriteObjCSynchronizedStmt(StmtTry);
5286
5287 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5288 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump11289f42009-09-09 15:08:12 +00005289
Steve Narofff4b992a2008-10-28 20:29:00 +00005290 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5291 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump11289f42009-09-09 15:08:12 +00005292
5293 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofff4b992a2008-10-28 20:29:00 +00005294 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump11289f42009-09-09 15:08:12 +00005295 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofff4b992a2008-10-28 20:29:00 +00005296 OrigStmtRange.getEnd());
5297 if (BreakStmt *StmtBreakStmt =
5298 dyn_cast<BreakStmt>(S))
5299 return RewriteBreakStmt(StmtBreakStmt);
5300 if (ContinueStmt *StmtContinueStmt =
5301 dyn_cast<ContinueStmt>(S))
5302 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump11289f42009-09-09 15:08:12 +00005303
5304 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofff4b992a2008-10-28 20:29:00 +00005305 // and cast exprs.
5306 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5307 // FIXME: What we're doing here is modifying the type-specifier that
5308 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump11289f42009-09-09 15:08:12 +00005309 // a separate type-specifier that we can rewrite.
Steve Naroffe70a52a2009-12-05 15:55:59 +00005310 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5311 // the context of an ObjCForCollectionStmt. For example:
5312 // NSArray *someArray;
5313 // for (id <FooProtocol> index in someArray) ;
5314 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5315 // and it depends on the original text locations/positions.
Benjamin Krameracc5fa12009-12-05 22:16:51 +00005316 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroffe70a52a2009-12-05 15:55:59 +00005317 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump11289f42009-09-09 15:08:12 +00005318
Steve Narofff4b992a2008-10-28 20:29:00 +00005319 // Blocks rewrite rules.
5320 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5321 DI != DE; ++DI) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +00005322 Decl *SD = *DI;
Steve Narofff4b992a2008-10-28 20:29:00 +00005323 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005324 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005325 RewriteBlockPointerDecl(ND);
Mike Stump11289f42009-09-09 15:08:12 +00005326 else if (ND->getType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005327 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00005328 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005329 if (VD->hasAttr<BlocksAttr>()) {
5330 static unsigned uniqueByrefDeclCount = 0;
5331 assert(!BlockByRefDeclNo.count(ND) &&
5332 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5333 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005334 RewriteByRefVar(VD);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005335 }
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00005336 else
5337 RewriteTypeOfDecl(VD);
5338 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005339 }
5340 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005341 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005342 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005343 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005344 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5345 }
5346 }
5347 }
Mike Stump11289f42009-09-09 15:08:12 +00005348
Steve Narofff4b992a2008-10-28 20:29:00 +00005349 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5350 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump11289f42009-09-09 15:08:12 +00005351
5352 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00005353 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5354 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump11289f42009-09-09 15:08:12 +00005355 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5356 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005357 && "Statement stack mismatch");
5358 Stmts.pop_back();
5359 }
5360 // Handle blocks rewriting.
5361 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5362 if (BDRE->isByRef())
Steve Naroffd9803712009-04-29 16:37:50 +00005363 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofff4b992a2008-10-28 20:29:00 +00005364 }
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005365 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5366 ValueDecl *VD = DRE->getDecl();
5367 if (VD->hasAttr<BlocksAttr>())
5368 return RewriteBlockDeclRefExpr(DRE);
5369 }
5370
Steve Narofff4b992a2008-10-28 20:29:00 +00005371 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff350b6652008-10-30 10:07:53 +00005372 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00005373 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00005374 ReplaceStmt(S, BlockCall);
5375 return BlockCall;
5376 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005377 }
Steve Naroffc989a7b2008-11-03 23:29:32 +00005378 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005379 RewriteCastExpr(CE);
5380 }
5381#if 0
5382 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek5a201952009-02-07 01:47:29 +00005383 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00005384 // Get the new text.
5385 std::string SStr;
5386 llvm::raw_string_ostream Buf(SStr);
Eli Friedman0905f142009-05-30 05:19:26 +00005387 Replacement->printPretty(Buf, *Context);
Steve Narofff4b992a2008-10-28 20:29:00 +00005388 const std::string &Str = Buf.str();
5389
5390 printf("CAST = %s\n", &Str[0]);
5391 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5392 delete S;
5393 return Replacement;
5394 }
5395#endif
5396 // Return this stmt unmodified.
5397 return S;
5398}
5399
Steve Naroffe70a52a2009-12-05 15:55:59 +00005400void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5401 for (RecordDecl::field_iterator i = RD->field_begin(),
5402 e = RD->field_end(); i != e; ++i) {
5403 FieldDecl *FD = *i;
5404 if (isTopLevelBlockPointerType(FD->getType()))
5405 RewriteBlockPointerDecl(FD);
5406 if (FD->getType()->isObjCQualifiedIdType() ||
5407 FD->getType()->isObjCQualifiedInterfaceType())
5408 RewriteObjCQualifiedInterfaceTypes(FD);
5409 }
5410}
5411
Steve Narofff4b992a2008-10-28 20:29:00 +00005412/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5413/// main file of the input.
5414void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5415 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffb1368882008-12-17 00:20:22 +00005416 if (FD->isOverloadedOperator())
5417 return;
Mike Stump11289f42009-09-09 15:08:12 +00005418
Steve Narofff4b992a2008-10-28 20:29:00 +00005419 // Since function prototypes don't have ParmDecl's, we check the function
5420 // prototype. This enables us to rewrite function declarations and
5421 // definitions using the same code.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005422 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005423
Sebastian Redla7b98a72009-04-26 20:35:05 +00005424 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005425 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005426 CurFunctionDef = FD;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005427 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005428 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005429 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005430 Body =
5431 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5432 FD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005433 CurrentBody = 0;
5434 if (PropParentMap) {
5435 delete PropParentMap;
5436 PropParentMap = 0;
5437 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005438 // This synthesizes and inserts the block "impl" struct, invoke function,
5439 // and any copy/dispose helper functions.
5440 InsertBlockLiteralsWithinFunction(FD);
5441 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005442 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005443 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005444 return;
5445 }
5446 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005447 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005448 CurMethodDef = MD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005449 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005450 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005451 Body =
5452 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5453 MD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005454 CurrentBody = 0;
5455 if (PropParentMap) {
5456 delete PropParentMap;
5457 PropParentMap = 0;
5458 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005459 InsertBlockLiteralsWithinMethod(MD);
5460 CurMethodDef = 0;
5461 }
5462 }
5463 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5464 ClassImplementation.push_back(CI);
5465 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5466 CategoryImplementation.push_back(CI);
5467 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5468 RewriteForwardClassDecl(CD);
5469 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5470 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroffa5c0db82008-12-11 21:05:33 +00005471 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005472 RewriteBlockPointerDecl(VD);
Steve Naroffd8907b72008-10-29 18:15:37 +00005473 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005474 CheckFunctionPointerDecl(VD->getType(), VD);
5475 if (VD->getInit()) {
Steve Naroffc989a7b2008-11-03 23:29:32 +00005476 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005477 RewriteCastExpr(CE);
5478 }
5479 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00005480 } else if (VD->getType()->isRecordType()) {
5481 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5482 if (RD->isDefinition())
5483 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005484 }
Steve Naroffd8907b72008-10-29 18:15:37 +00005485 if (VD->getInit()) {
5486 GlobalVarDecl = VD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005487 CollectPropertySetters(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005488 CurrentBody = VD->getInit();
Steve Naroffd8907b72008-10-29 18:15:37 +00005489 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005490 CurrentBody = 0;
5491 if (PropParentMap) {
5492 delete PropParentMap;
5493 PropParentMap = 0;
5494 }
Mike Stump11289f42009-09-09 15:08:12 +00005495 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner86d7d912008-11-24 03:54:41 +00005496 VD->getNameAsCString());
Steve Naroffd8907b72008-10-29 18:15:37 +00005497 GlobalVarDecl = 0;
5498
5499 // This is needed for blocks.
Steve Naroffc989a7b2008-11-03 23:29:32 +00005500 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroffd8907b72008-10-29 18:15:37 +00005501 RewriteCastExpr(CE);
5502 }
5503 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005504 return;
5505 }
5506 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005507 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005508 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005509 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005510 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5511 return;
5512 }
5513 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroffe70a52a2009-12-05 15:55:59 +00005514 if (RD->isDefinition())
5515 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005516 return;
5517 }
5518 // Nothing yet.
5519}
5520
Chris Lattnercf169832009-03-28 04:11:33 +00005521void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005522 if (Diags.hasErrorOccurred())
5523 return;
Mike Stump11289f42009-09-09 15:08:12 +00005524
Steve Narofff4b992a2008-10-28 20:29:00 +00005525 RewriteInclude();
Mike Stump11289f42009-09-09 15:08:12 +00005526
Steve Naroffd9803712009-04-29 16:37:50 +00005527 // Here's a great place to add any extra declarations that may be needed.
5528 // Write out meta data for each @protocol(<expr>).
Mike Stump11289f42009-09-09 15:08:12 +00005529 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00005530 E = ProtocolExprDecls.end(); I != E; ++I)
5531 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5532
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005533 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005534 if (ClassImplementation.size() || CategoryImplementation.size())
5535 RewriteImplementations();
Steve Naroffd9803712009-04-29 16:37:50 +00005536
Steve Narofff4b992a2008-10-28 20:29:00 +00005537 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5538 // we are done.
Mike Stump11289f42009-09-09 15:08:12 +00005539 if (const RewriteBuffer *RewriteBuf =
Steve Narofff4b992a2008-10-28 20:29:00 +00005540 Rewrite.getRewriteBufferFor(MainFileID)) {
5541 //printf("Changed:\n");
5542 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5543 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005544 llvm::errs() << "No changes\n";
Steve Narofff4b992a2008-10-28 20:29:00 +00005545 }
Steve Narofff8cfd162008-11-13 20:07:04 +00005546
Steve Naroffd9803712009-04-29 16:37:50 +00005547 if (ClassImplementation.size() || CategoryImplementation.size() ||
5548 ProtocolExprDecls.size()) {
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005549 // Rewrite Objective-c meta data*
5550 std::string ResultStr;
5551 SynthesizeMetaDataIntoBuffer(ResultStr);
5552 // Emit metadata.
5553 *OutFile << ResultStr;
5554 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005555 OutFile->flush();
5556}
5557