blob: 386d9b0812bbe6ed44f135b606b117ea77285541 [file] [log] [blame]
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattnere99c8322007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnere99c8322007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Eli Friedman9f30fc32009-05-18 22:50:54 +000014#include "clang/Frontend/ASTConsumers.h"
Chris Lattner16a0de42007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattnere99c8322007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Steve Naroff1042ff32008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Chris Lattner16a0de42007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner4431a1b2007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattnerf3a59a12007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000023#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
Chris Lattner211f8b82007-10-25 17:07:24 +000025#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian99e96b02007-10-26 19:46:17 +000026#include "llvm/ADT/SmallPtrSet.h"
Ted Kremenek2d470fc2008-09-13 05:16:45 +000027#include "llvm/ADT/OwningPtr.h"
Fariborz Jahaniane3891582010-01-05 18:04:40 +000028#include "llvm/ADT/DenseSet.h"
Chris Lattnere99c8322007-10-11 00:43:27 +000029using namespace clang;
Chris Lattner211f8b82007-10-25 17:07:24 +000030using llvm::utostr;
Chris Lattnere99c8322007-10-11 00:43:27 +000031
Chris Lattnere99c8322007-10-11 00:43:27 +000032namespace {
Steve Naroff1dc53ef2008-04-14 22:03:09 +000033 class RewriteObjC : public ASTConsumer {
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000034 enum {
35 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
36 block, ... */
37 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
38 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
39 __block variable */
40 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
41 helpers */
42 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
43 support routines */
44 BLOCK_BYREF_CURRENT_MAX = 256
45 };
46
47 enum {
48 BLOCK_NEEDS_FREE = (1 << 24),
49 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
50 BLOCK_HAS_CXX_OBJ = (1 << 26),
51 BLOCK_IS_GC = (1 << 27),
52 BLOCK_IS_GLOBAL = (1 << 28),
53 BLOCK_HAS_DESCRIPTOR = (1 << 29)
54 };
55
Chris Lattner0bd1c972007-10-16 21:07:07 +000056 Rewriter Rewrite;
Chris Lattnere9c810c2007-11-30 22:25:36 +000057 Diagnostic &Diags;
Steve Naroff945a3b12008-03-10 20:43:59 +000058 const LangOptions &LangOpts;
Steve Naroff7b3579b2008-01-30 19:17:43 +000059 unsigned RewriteFailedDiag;
Steve Naroff6d6da252008-12-05 17:03:39 +000060 unsigned TryFinallyContainsReturnDiag;
Mike Stump11289f42009-09-09 15:08:12 +000061
Chris Lattnerc6d91c02007-10-17 22:35:30 +000062 ASTContext *Context;
Chris Lattnere99c8322007-10-11 00:43:27 +000063 SourceManager *SM;
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +000064 TranslationUnitDecl *TUDecl;
Chris Lattnerd32480d2009-01-17 06:22:33 +000065 FileID MainFileID;
Chris Lattnerf3a59a12007-12-02 01:13:47 +000066 const char *MainFileStart, *MainFileEnd;
Chris Lattner0bd1c972007-10-16 21:07:07 +000067 SourceLocation LastIncLoc;
Mike Stump11289f42009-09-09 15:08:12 +000068
Ted Kremenek1b0ea822008-01-07 19:49:32 +000069 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
70 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
71 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Naroff13e74872008-05-06 18:26:51 +000072 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremenek1b0ea822008-01-07 19:49:32 +000073 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
74 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +000075 llvm::SmallVector<Stmt *, 32> Stmts;
76 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffd9803712009-04-29 16:37:50 +000077 // Remember all the @protocol(<expr>) expressions.
78 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahaniane3891582010-01-05 18:04:40 +000079
80 llvm::DenseSet<uint64_t> CopyDestroyCache;
81
Steve Naroffce8e8862008-03-15 00:55:56 +000082 unsigned NumObjCStringLiterals;
Mike Stump11289f42009-09-09 15:08:12 +000083
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000084 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +000085 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +000086 FunctionDecl *MsgSendStretFunctionDecl;
87 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian4f76f222007-12-03 21:26:48 +000088 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000089 FunctionDecl *GetClassFunctionDecl;
Steve Naroffb2f8ff12007-12-07 03:50:46 +000090 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff574440f2007-10-24 22:48:43 +000091 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff265a6b92007-11-08 14:30:50 +000092 FunctionDecl *CFStringFunctionDecl;
Steve Naroff17978c42008-03-11 17:37:02 +000093 FunctionDecl *SuperContructorFunctionDecl;
Mike Stump11289f42009-09-09 15:08:12 +000094
Steve Naroffa397efd2007-11-03 11:27:19 +000095 // ObjC string constant support.
Steve Naroff08899ff2008-04-15 22:42:06 +000096 VarDecl *ConstantStringClassReference;
Steve Naroffa397efd2007-11-03 11:27:19 +000097 RecordDecl *NSStringRecord;
Mike Stump11289f42009-09-09 15:08:12 +000098
Fariborz Jahanian19d42bf2008-01-16 00:09:11 +000099 // ObjC foreach break/continue generation support.
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000100 int BcLabelCount;
Mike Stump11289f42009-09-09 15:08:12 +0000101
Steve Naroff7fa2f042007-11-15 10:28:18 +0000102 // Needed for super.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000103 ObjCMethodDecl *CurMethodDef;
Steve Naroff7fa2f042007-11-15 10:28:18 +0000104 RecordDecl *SuperStructDecl;
Steve Naroffce8e8862008-03-15 00:55:56 +0000105 RecordDecl *ConstantStringDecl;
Mike Stump11289f42009-09-09 15:08:12 +0000106
Steve Naroffd9803712009-04-29 16:37:50 +0000107 TypeDecl *ProtocolTypeDecl;
108 QualType getProtocolType();
Mike Stump11289f42009-09-09 15:08:12 +0000109
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000110 // Needed for header files being rewritten
111 bool IsHeader;
Mike Stump11289f42009-09-09 15:08:12 +0000112
Steve Narofff9e7c902008-03-28 22:26:09 +0000113 std::string InFileName;
Eli Friedman94cf21e2009-05-18 22:20:00 +0000114 llvm::raw_ostream* OutFile;
Eli Friedmanf22439a2009-05-18 22:39:16 +0000115
116 bool SilenceRewriteMacroWarning;
Fariborz Jahanianbc6811c2010-01-07 22:51:18 +0000117 bool objc_impl_method;
Eli Friedmanf22439a2009-05-18 22:39:16 +0000118
Steve Naroff00a31762008-03-27 22:29:16 +0000119 std::string Preamble;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000120
121 // Block expressions.
122 llvm::SmallVector<BlockExpr *, 32> Blocks;
123 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
124 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Mike Stump11289f42009-09-09 15:08:12 +0000125
Steve Naroff677ab3a2008-10-27 17:20:55 +0000126 // Block related declarations.
127 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
128 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +0000129 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000130 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
131
132 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
133
Steve Naroff4588d0f2008-12-04 16:24:46 +0000134 // This maps a property to it's assignment statement.
135 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Naroff1042ff32008-12-08 16:43:47 +0000136 // This maps a property to it's synthesied message expression.
137 // This allows us to rewrite chained getters (e.g. o.a.b.c).
138 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
Mike Stump11289f42009-09-09 15:08:12 +0000139
Steve Naroff22216db2008-12-04 23:50:32 +0000140 // This maps an original source AST to it's rewritten form. This allows
141 // us to avoid rewriting the same node twice (which is very uncommon).
142 // This is needed to support some of the exotic property rewriting.
143 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Narofff326f402008-12-03 00:56:33 +0000144
Steve Naroff677ab3a2008-10-27 17:20:55 +0000145 FunctionDecl *CurFunctionDef;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000146 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Steve Naroffd8907b72008-10-29 18:15:37 +0000147 VarDecl *GlobalVarDecl;
Mike Stump11289f42009-09-09 15:08:12 +0000148
Steve Naroff08628db2008-12-09 12:56:34 +0000149 bool DisableReplaceStmt;
Mike Stump11289f42009-09-09 15:08:12 +0000150
Fariborz Jahanian93191af2007-10-18 19:23:00 +0000151 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnere99c8322007-10-11 00:43:27 +0000152 public:
Ted Kremenek380df932008-05-31 20:11:04 +0000153 virtual void Initialize(ASTContext &context);
154
Chris Lattner3c799d72007-10-24 17:06:59 +0000155 // Top Level Driver code.
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000156 virtual void HandleTopLevelDecl(DeclGroupRef D) {
157 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
158 HandleTopLevelSingleDecl(*I);
159 }
160 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000161 void HandleDeclInMainFile(Decl *D);
Eli Friedman94cf21e2009-05-18 22:20:00 +0000162 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000163 Diagnostic &D, const LangOptions &LOpts,
164 bool silenceMacroWarn);
Ted Kremenek6231e7e2008-08-08 04:15:52 +0000165
166 ~RewriteObjC() {}
Mike Stump11289f42009-09-09 15:08:12 +0000167
Chris Lattnercf169832009-03-28 04:11:33 +0000168 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump11289f42009-09-09 15:08:12 +0000169
Chris Lattner2e0d2602008-01-31 19:37:57 +0000170 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff22216db2008-12-04 23:50:32 +0000171 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump11289f42009-09-09 15:08:12 +0000172
Steve Naroff22216db2008-12-04 23:50:32 +0000173 if (ReplacingStmt)
174 return; // We can't rewrite the same node twice.
Chris Lattner2e0d2602008-01-31 19:37:57 +0000175
Steve Naroff08628db2008-12-09 12:56:34 +0000176 if (DisableReplaceStmt)
177 return; // Used when rewriting the assignment of a property setter.
178
Steve Naroff22216db2008-12-04 23:50:32 +0000179 // If replacement succeeded or warning disabled return with no warning.
180 if (!Rewrite.ReplaceStmt(Old, New)) {
181 ReplacedNodes[Old] = New;
182 return;
183 }
184 if (SilenceRewriteMacroWarning)
185 return;
Chris Lattner8488c822008-11-18 07:04:44 +0000186 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
187 << Old->getSourceRange();
Chris Lattner2e0d2602008-01-31 19:37:57 +0000188 }
Steve Naroff08628db2008-12-09 12:56:34 +0000189
190 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
191 // Measaure the old text.
192 int Size = Rewrite.getRangeSize(SrcRange);
193 if (Size == -1) {
194 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
195 << Old->getSourceRange();
196 return;
197 }
198 // Get the new text.
199 std::string SStr;
200 llvm::raw_string_ostream S(SStr);
Chris Lattnerc61089a2009-06-30 01:26:17 +0000201 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroff08628db2008-12-09 12:56:34 +0000202 const std::string &Str = S.str();
203
204 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000205 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroff08628db2008-12-09 12:56:34 +0000206 ReplacedNodes[Old] = New;
207 return;
208 }
209 if (SilenceRewriteMacroWarning)
210 return;
211 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
212 << Old->getSourceRange();
213 }
214
Steve Naroff00a31762008-03-27 22:29:16 +0000215 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
216 bool InsertAfter = true) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000217 // If insertion succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000218 if (!Rewrite.InsertText(Loc, llvm::StringRef(StrData, StrLen),
219 InsertAfter) ||
Chris Lattner1780a852008-01-31 19:42:41 +0000220 SilenceRewriteMacroWarning)
221 return;
Mike Stump11289f42009-09-09 15:08:12 +0000222
Chris Lattner1780a852008-01-31 19:42:41 +0000223 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
224 }
Mike Stump11289f42009-09-09 15:08:12 +0000225
Chris Lattner9cc55f52008-01-31 19:51:04 +0000226 void RemoveText(SourceLocation Loc, unsigned StrLen) {
227 // If removal succeeded or warning disabled return with no warning.
228 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
229 return;
Mike Stump11289f42009-09-09 15:08:12 +0000230
Chris Lattner9cc55f52008-01-31 19:51:04 +0000231 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
232 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000233
Chris Lattner9cc55f52008-01-31 19:51:04 +0000234 void ReplaceText(SourceLocation Start, unsigned OrigLength,
235 const char *NewStr, unsigned NewLength) {
236 // If removal succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000237 if (!Rewrite.ReplaceText(Start, OrigLength,
238 llvm::StringRef(NewStr, NewLength)) ||
Chris Lattner9cc55f52008-01-31 19:51:04 +0000239 SilenceRewriteMacroWarning)
240 return;
Mike Stump11289f42009-09-09 15:08:12 +0000241
Chris Lattner9cc55f52008-01-31 19:51:04 +0000242 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
243 }
Mike Stump11289f42009-09-09 15:08:12 +0000244
Chris Lattner3c799d72007-10-24 17:06:59 +0000245 // Syntactic Rewriting.
Steve Narofff36987c2007-11-04 22:37:50 +0000246 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000247 void RewriteInclude();
Chris Lattner3c799d72007-10-24 17:06:59 +0000248 void RewriteTabs();
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000249 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffc038b3a2008-12-02 17:36:43 +0000250 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
251 ObjCImplementationDecl *IMD,
252 ObjCCategoryImplDecl *CID);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000253 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000254 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000255 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +0000256 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
257 ValueDecl *VD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000258 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
259 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
260 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
261 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000262 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000263 void RewriteFunctionDecl(FunctionDecl *FD);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000264 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000265 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff873bd842008-07-29 18:15:38 +0000266 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroff50d42052007-11-01 13:24:47 +0000267 bool needToScanForQualifiers(QualType T);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000268 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff7fa2f042007-11-15 10:28:18 +0000269 QualType getSuperStructType();
Steve Naroffce8e8862008-03-15 00:55:56 +0000270 QualType getConstantStringStructType();
Steve Naroffcd92aeb2008-05-31 14:15:04 +0000271 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump11289f42009-09-09 15:08:12 +0000272
Chris Lattner3c799d72007-10-24 17:06:59 +0000273 // Expression Rewriting.
Steve Naroff20113382007-11-09 15:20:18 +0000274 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroff4588d0f2008-12-04 16:24:46 +0000275 void CollectPropertySetters(Stmt *S);
Mike Stump11289f42009-09-09 15:08:12 +0000276
Steve Naroff1042ff32008-12-08 16:43:47 +0000277 Stmt *CurrentBody;
278 ParentMap *PropParentMap; // created lazily.
Mike Stump11289f42009-09-09 15:08:12 +0000279
Chris Lattner69534692007-10-24 16:57:36 +0000280 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner37f5b7d2008-05-23 20:40:52 +0000281 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroff4588d0f2008-12-04 16:24:46 +0000282 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Mike Stump11289f42009-09-09 15:08:12 +0000283 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroff08628db2008-12-09 12:56:34 +0000284 SourceRange SrcRange);
Steve Naroffe4f9b232007-11-05 14:50:49 +0000285 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner69534692007-10-24 16:57:36 +0000286 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffa397efd2007-11-03 11:27:19 +0000287 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian33c0e812007-12-07 18:47:10 +0000288 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffec60b432009-12-05 21:43:12 +0000289 void WarnAboutReturnGotoStmts(Stmt *S);
290 void HasReturnStmts(Stmt *S, bool &hasReturns);
291 void RewriteTryReturnStmts(Stmt *S);
292 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000293 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian284011b2008-01-29 22:59:37 +0000294 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000295 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
296 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
297 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattnera779d692008-01-31 05:10:40 +0000298 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
299 SourceLocation OrigEnd);
Mike Stump11289f42009-09-09 15:08:12 +0000300 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Steve Naroff574440f2007-10-24 22:48:43 +0000301 Expr **args, unsigned nargs);
Fariborz Jahanian965a8962008-01-08 22:06:28 +0000302 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000303 Stmt *RewriteBreakStmt(BreakStmt *S);
304 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian965a8962008-01-08 22:06:28 +0000305 void SynthCountByEnumWithState(std::string &buf);
Mike Stump11289f42009-09-09 15:08:12 +0000306
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000307 void SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +0000308 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000309 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +0000310 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000311 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000312 void SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +0000313 void SynthGetMetaClassFunctionDecl();
Fariborz Jahanian31e18502007-12-04 21:47:40 +0000314 void SynthSelGetUidFunctionDecl();
Steve Naroff17978c42008-03-11 17:37:02 +0000315 void SynthSuperContructorFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000316
Chris Lattner3c799d72007-10-24 17:06:59 +0000317 // Metadata emission.
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000318 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000319 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000320
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000321 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000322 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000323
Douglas Gregor29bd76f2009-04-23 01:02:12 +0000324 template<typename MethodIterator>
325 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
326 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +0000327 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +0000328 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +0000329 const char *ClassName,
330 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000331
Steve Naroffd9803712009-04-29 16:37:50 +0000332 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
333 const char *prefix,
334 const char *ClassName,
335 std::string &Result);
336 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Mike Stump11289f42009-09-09 15:08:12 +0000337 const char *prefix,
Steve Naroffd9803712009-04-29 16:37:50 +0000338 const char *ClassName,
339 std::string &Result);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000340 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000341 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000342 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
343 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000344 std::string &Result);
Steve Narofff8cfd162008-11-13 20:07:04 +0000345 void RewriteImplementations();
346 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000347
Steve Naroff677ab3a2008-10-27 17:20:55 +0000348 // Block rewriting.
Mike Stump11289f42009-09-09 15:08:12 +0000349 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000350 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump11289f42009-09-09 15:08:12 +0000351
Steve Naroff677ab3a2008-10-27 17:20:55 +0000352 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
353 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump11289f42009-09-09 15:08:12 +0000354
355 // Block specific rewrite rules.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000356 void RewriteBlockCall(CallExpr *Exp);
357 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000358 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahaniane3891582010-01-05 18:04:40 +0000359 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +0000360 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000361 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump11289f42009-09-09 15:08:12 +0000362
363 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000364 const char *funcName, std::string Tag);
Mike Stump11289f42009-09-09 15:08:12 +0000365 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000366 const char *funcName, std::string Tag);
Steve Naroff30484702009-12-06 21:14:13 +0000367 std::string SynthesizeBlockImpl(BlockExpr *CE,
368 std::string Tag, std::string Desc);
369 std::string SynthesizeBlockDescriptor(std::string DescTag,
370 std::string ImplTag,
371 int i, const char *funcName,
372 unsigned hasCopy);
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +0000373 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000374 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000375 const char *FunName);
Steve Naroffe70a52a2009-12-05 15:55:59 +0000376 void RewriteRecordBody(RecordDecl *RD);
Mike Stump11289f42009-09-09 15:08:12 +0000377
Steve Naroff677ab3a2008-10-27 17:20:55 +0000378 void CollectBlockDeclRefInfo(BlockExpr *Exp);
379 void GetBlockCallExprs(Stmt *S);
380 void GetBlockDeclRefExprs(Stmt *S);
Mike Stump11289f42009-09-09 15:08:12 +0000381
Steve Naroff677ab3a2008-10-27 17:20:55 +0000382 // We avoid calling Type::isBlockPointerType(), since it operates on the
383 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek5a201952009-02-07 01:47:29 +0000384 bool isTopLevelBlockPointerType(QualType T) {
385 return isa<BlockPointerType>(T);
386 }
Mike Stump11289f42009-09-09 15:08:12 +0000387
Steve Naroff677ab3a2008-10-27 17:20:55 +0000388 // FIXME: This predicate seems like it would be useful to add to ASTContext.
389 bool isObjCType(QualType T) {
390 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
391 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000392
Steve Naroff677ab3a2008-10-27 17:20:55 +0000393 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000394
Steve Naroff677ab3a2008-10-27 17:20:55 +0000395 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
396 OCT == Context->getCanonicalType(Context->getObjCClassType()))
397 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000398
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000399 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +0000400 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Narofffb4330f2009-06-17 22:40:22 +0000401 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff677ab3a2008-10-27 17:20:55 +0000402 return true;
403 }
404 return false;
405 }
406 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek5a201952009-02-07 01:47:29 +0000407 void GetExtentOfArgList(const char *Name, const char *&LParen,
408 const char *&RParen);
Steve Naroffc989a7b2008-11-03 23:29:32 +0000409 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump11289f42009-09-09 15:08:12 +0000410
Steve Narofff4b992a2008-10-28 20:29:00 +0000411 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroffd8907b72008-10-29 18:15:37 +0000412 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Mike Stump11289f42009-09-09 15:08:12 +0000413
Steve Naroffd9803712009-04-29 16:37:50 +0000414 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump11289f42009-09-09 15:08:12 +0000415 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroffd9803712009-04-29 16:37:50 +0000416 if (From[i] == '"')
417 To += "\\\"";
418 else
419 To += From[i];
420 }
421 }
Chris Lattnere99c8322007-10-11 00:43:27 +0000422 };
423}
424
Mike Stump11289f42009-09-09 15:08:12 +0000425void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
426 NamedDecl *D) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000427 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000428 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +0000429 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +0000430 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +0000431 // All the args are checked/rewritten. Don't call twice!
432 RewriteBlockPointerDecl(D);
433 break;
434 }
435 }
436}
437
438void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000439 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +0000440 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000441 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000442}
443
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000444static bool IsHeaderFile(const std::string &Filename) {
445 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump11289f42009-09-09 15:08:12 +0000446
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000447 if (DotPos == std::string::npos) {
448 // no file extension
Mike Stump11289f42009-09-09 15:08:12 +0000449 return false;
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000450 }
Mike Stump11289f42009-09-09 15:08:12 +0000451
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000452 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
453 // C header: .h
454 // C++ header: .hh or .H;
455 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump11289f42009-09-09 15:08:12 +0000456}
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000457
Eli Friedman94cf21e2009-05-18 22:20:00 +0000458RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000459 Diagnostic &D, const LangOptions &LOpts,
460 bool silenceMacroWarn)
461 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
462 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Narofff9e7c902008-03-28 22:26:09 +0000463 IsHeader = IsHeaderFile(inFile);
Mike Stump11289f42009-09-09 15:08:12 +0000464 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Narofff9e7c902008-03-28 22:26:09 +0000465 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump11289f42009-09-09 15:08:12 +0000466 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek5a201952009-02-07 01:47:29 +0000467 "rewriter doesn't support user-specified control flow semantics "
468 "for @try/@finally (code may not execute properly)");
Steve Narofff9e7c902008-03-28 22:26:09 +0000469}
470
Eli Friedmana63ab2d2009-05-18 22:29:17 +0000471ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
472 llvm::raw_ostream* OS,
Mike Stump11289f42009-09-09 15:08:12 +0000473 Diagnostic &Diags,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000474 const LangOptions &LOpts,
475 bool SilenceRewriteMacroWarning) {
476 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere9c810c2007-11-30 22:25:36 +0000477}
Chris Lattnere99c8322007-10-11 00:43:27 +0000478
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000479void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner187f6262008-01-31 19:38:44 +0000480 Context = &context;
481 SM = &Context->getSourceManager();
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +0000482 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner187f6262008-01-31 19:38:44 +0000483 MsgSendFunctionDecl = 0;
484 MsgSendSuperFunctionDecl = 0;
485 MsgSendStretFunctionDecl = 0;
486 MsgSendSuperStretFunctionDecl = 0;
487 MsgSendFpretFunctionDecl = 0;
488 GetClassFunctionDecl = 0;
489 GetMetaClassFunctionDecl = 0;
490 SelGetUidFunctionDecl = 0;
491 CFStringFunctionDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000492 ConstantStringClassReference = 0;
493 NSStringRecord = 0;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000494 CurMethodDef = 0;
495 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000496 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000497 GlobalVarDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000498 SuperStructDecl = 0;
Steve Naroffd9803712009-04-29 16:37:50 +0000499 ProtocolTypeDecl = 0;
Steve Naroff60a9ef62008-03-27 22:59:54 +0000500 ConstantStringDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000501 BcLabelCount = 0;
Steve Naroff17978c42008-03-11 17:37:02 +0000502 SuperContructorFunctionDecl = 0;
Steve Naroffce8e8862008-03-15 00:55:56 +0000503 NumObjCStringLiterals = 0;
Steve Narofff1ab6002008-12-08 20:01:41 +0000504 PropParentMap = 0;
505 CurrentBody = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000506 DisableReplaceStmt = false;
Fariborz Jahanianbc6811c2010-01-07 22:51:18 +0000507 objc_impl_method = false;
Mike Stump11289f42009-09-09 15:08:12 +0000508
Chris Lattner187f6262008-01-31 19:38:44 +0000509 // Get the ID and start/end of the main file.
510 MainFileID = SM->getMainFileID();
511 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
512 MainFileStart = MainBuf->getBufferStart();
513 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000514
Chris Lattner184e65d2009-04-14 23:22:57 +0000515 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump11289f42009-09-09 15:08:12 +0000516
Chris Lattner187f6262008-01-31 19:38:44 +0000517 // declaring objc_selector outside the parameter list removes a silly
518 // scope related warning...
Steve Naroff00a31762008-03-27 22:29:16 +0000519 if (IsHeader)
Steve Narofffcc6fd52009-02-03 20:39:18 +0000520 Preamble = "#pragma once\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000521 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff6ab6dc72008-12-23 20:11:22 +0000522 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroff00a31762008-03-27 22:29:16 +0000523 Preamble += "struct objc_object *superClass; ";
Steve Naroff17978c42008-03-11 17:37:02 +0000524 if (LangOpts.Microsoft) {
525 // Add a constructor for creating temporary objects.
Ted Kremenek5a201952009-02-07 01:47:29 +0000526 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
527 ": ";
Steve Naroff00a31762008-03-27 22:29:16 +0000528 Preamble += "object(o), superClass(s) {} ";
Steve Naroff17978c42008-03-11 17:37:02 +0000529 }
Steve Naroff00a31762008-03-27 22:29:16 +0000530 Preamble += "};\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000531 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
532 Preamble += "typedef struct objc_object Protocol;\n";
533 Preamble += "#define _REWRITER_typedef_Protocol\n";
534 Preamble += "#endif\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000535 if (LangOpts.Microsoft) {
536 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
537 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
538 } else
539 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
540 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroff00a31762008-03-27 22:29:16 +0000541 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000542 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroff00a31762008-03-27 22:29:16 +0000543 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000544 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000545 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000546 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000547 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000548 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroff00a31762008-03-27 22:29:16 +0000549 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000550 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000551 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000552 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000553 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000554 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
555 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
556 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
557 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
558 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroffd30f8c52008-05-09 21:17:56 +0000559 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff8dd15252008-07-16 18:58:11 +0000560 // @synchronized hooks.
Steve Narofff122ff02008-12-08 17:30:33 +0000561 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
562 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
563 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000564 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
565 Preamble += "struct __objcFastEnumerationState {\n\t";
566 Preamble += "unsigned long state;\n\t";
Steve Naroff4dbab8a2008-04-04 22:58:22 +0000567 Preamble += "void **itemsPtr;\n\t";
Steve Naroff00a31762008-03-27 22:29:16 +0000568 Preamble += "unsigned long *mutationsPtr;\n\t";
569 Preamble += "unsigned long extra[5];\n};\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000570 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000571 Preamble += "#define __FASTENUMERATIONSTATE\n";
572 Preamble += "#endif\n";
573 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
574 Preamble += "struct __NSConstantStringImpl {\n";
575 Preamble += " int *isa;\n";
576 Preamble += " int flags;\n";
577 Preamble += " char *str;\n";
578 Preamble += " long length;\n";
579 Preamble += "};\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000580 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
581 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
582 Preamble += "#else\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000583 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000584 Preamble += "#endif\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000585 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
586 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000587 // Blocks preamble.
588 Preamble += "#ifndef BLOCK_IMPL\n";
589 Preamble += "#define BLOCK_IMPL\n";
590 Preamble += "struct __block_impl {\n";
591 Preamble += " void *isa;\n";
592 Preamble += " int Flags;\n";
Steve Naroff30484702009-12-06 21:14:13 +0000593 Preamble += " int Reserved;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000594 Preamble += " void *FuncPtr;\n";
595 Preamble += "};\n";
Steve Naroff61d879e2008-12-16 15:50:30 +0000596 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroff287a2bf2009-12-06 01:52:22 +0000597 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000598 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_assign(void *, const void *, const int);\n";
599 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
600 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
601 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
602 Preamble += "#else\n";
Steve Naroff7bf01ea2010-01-05 18:09:31 +0000603 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
604 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000605 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
606 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
607 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000608 Preamble += "#endif\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000609 if (LangOpts.Microsoft) {
Steve Narofff122ff02008-12-08 17:30:33 +0000610 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
611 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000612 Preamble += "#define __attribute__(X)\n";
613 }
Fariborz Jahanian7fac6552010-01-05 19:21:35 +0000614 else {
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000615 Preamble += "#define __block\n";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +0000616 Preamble += "#define __weak\n";
617 }
Chris Lattner187f6262008-01-31 19:38:44 +0000618}
619
620
Chris Lattner3c799d72007-10-24 17:06:59 +0000621//===----------------------------------------------------------------------===//
622// Top Level Driver Code
623//===----------------------------------------------------------------------===//
624
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000625void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Chris Lattner0bd1c972007-10-16 21:07:07 +0000626 // Two cases: either the decl could be in the main file, or it could be in a
627 // #included file. If the former, rewrite it now. If the later, check to see
628 // if we rewrote the #include/#import.
629 SourceLocation Loc = D->getLocation();
Chris Lattner8a425862009-01-16 07:36:28 +0000630 Loc = SM->getInstantiationLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000631
Chris Lattner0bd1c972007-10-16 21:07:07 +0000632 // If this is for a builtin, ignore it.
633 if (Loc.isInvalid()) return;
634
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000635 // Look for built-in declarations that we need to refer during the rewrite.
636 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000637 RewriteFunctionDecl(FD);
Steve Naroff08899ff2008-04-15 22:42:06 +0000638 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000639 // declared in <Foundation/NSString.h>
Chris Lattner86d7d912008-11-24 03:54:41 +0000640 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000641 ConstantStringClassReference = FVD;
642 return;
643 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000644 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff161a92b2007-10-26 20:53:56 +0000645 RewriteInterfaceDecl(MD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000646 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000647 RewriteCategoryDecl(CD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000648 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff921385f2007-10-30 16:42:30 +0000649 RewriteProtocolDecl(PD);
Mike Stump11289f42009-09-09 15:08:12 +0000650 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000651 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000652 RewriteForwardProtocolDecl(FP);
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000653 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
654 // Recurse into linkage specifications
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000655 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
656 DIEnd = LSD->decls_end();
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000657 DI != DIEnd; ++DI)
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000658 HandleTopLevelSingleDecl(*DI);
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000659 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000660 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekd61ed3b2008-04-14 21:24:13 +0000661 if (SM->isFromMainFile(Loc))
Chris Lattner0bd1c972007-10-16 21:07:07 +0000662 return HandleDeclInMainFile(D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000663}
664
Chris Lattner3c799d72007-10-24 17:06:59 +0000665//===----------------------------------------------------------------------===//
666// Syntactic (non-AST) Rewriting Code
667//===----------------------------------------------------------------------===//
668
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000669void RewriteObjC::RewriteInclude() {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000670 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000671 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
672 const char *MainBufStart = MainBuf.first;
673 const char *MainBufEnd = MainBuf.second;
674 size_t ImportLen = strlen("import");
675 size_t IncludeLen = strlen("include");
Mike Stump11289f42009-09-09 15:08:12 +0000676
Fariborz Jahanian137d6932008-01-19 01:03:17 +0000677 // Loop over the whole file, looking for includes.
Fariborz Jahanian80258362008-01-19 00:30:35 +0000678 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
679 if (*BufPtr == '#') {
680 if (++BufPtr == MainBufEnd)
681 return;
682 while (*BufPtr == ' ' || *BufPtr == '\t')
683 if (++BufPtr == MainBufEnd)
684 return;
685 if (!strncmp(BufPtr, "import", ImportLen)) {
686 // replace import with include
Mike Stump11289f42009-09-09 15:08:12 +0000687 SourceLocation ImportLoc =
Fariborz Jahanian80258362008-01-19 00:30:35 +0000688 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000689 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000690 BufPtr += ImportLen;
691 }
692 }
693 }
Chris Lattner0bd1c972007-10-16 21:07:07 +0000694}
695
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000696void RewriteObjC::RewriteTabs() {
Chris Lattner3c799d72007-10-24 17:06:59 +0000697 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
698 const char *MainBufStart = MainBuf.first;
699 const char *MainBufEnd = MainBuf.second;
Mike Stump11289f42009-09-09 15:08:12 +0000700
Chris Lattner3c799d72007-10-24 17:06:59 +0000701 // Loop over the whole file, looking for tabs.
702 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
703 if (*BufPtr != '\t')
704 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000705
Chris Lattner3c799d72007-10-24 17:06:59 +0000706 // Okay, we found a tab. This tab will turn into at least one character,
707 // but it depends on which 'virtual column' it is in. Compute that now.
708 unsigned VCol = 0;
709 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
710 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
711 ++VCol;
Mike Stump11289f42009-09-09 15:08:12 +0000712
Chris Lattner3c799d72007-10-24 17:06:59 +0000713 // Okay, now that we know the virtual column, we know how many spaces to
714 // insert. We assume 8-character tab-stops.
715 unsigned Spaces = 8-(VCol & 7);
Mike Stump11289f42009-09-09 15:08:12 +0000716
Chris Lattner3c799d72007-10-24 17:06:59 +0000717 // Get the location of the tab.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000718 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
719 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Mike Stump11289f42009-09-09 15:08:12 +0000720
Chris Lattner3c799d72007-10-24 17:06:59 +0000721 // Rewrite the single tab character into a sequence of spaces.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000722 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattner3c799d72007-10-24 17:06:59 +0000723 }
Chris Lattner16a0de42007-10-11 18:38:32 +0000724}
725
Steve Naroff9af94912008-12-02 15:48:25 +0000726static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
727 ObjCIvarDecl *OID) {
728 std::string S;
729 S = "((struct ";
730 S += ClassDecl->getIdentifier()->getName();
731 S += "_IMPL *)self)->";
Daniel Dunbar70e7ead2009-10-18 20:26:27 +0000732 S += OID->getName();
Steve Naroff9af94912008-12-02 15:48:25 +0000733 return S;
734}
735
Steve Naroffc038b3a2008-12-02 17:36:43 +0000736void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
737 ObjCImplementationDecl *IMD,
738 ObjCCategoryImplDecl *CID) {
Steve Naroffe1908e32008-12-01 20:33:01 +0000739 SourceLocation startLoc = PID->getLocStart();
740 InsertText(startLoc, "// ", 3);
Steve Naroff9af94912008-12-02 15:48:25 +0000741 const char *startBuf = SM->getCharacterData(startLoc);
742 assert((*startBuf == '@') && "bogus @synthesize location");
743 const char *semiBuf = strchr(startBuf, ';');
744 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek5a201952009-02-07 01:47:29 +0000745 SourceLocation onePastSemiLoc =
746 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroff9af94912008-12-02 15:48:25 +0000747
748 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
749 return; // FIXME: is this correct?
Mike Stump11289f42009-09-09 15:08:12 +0000750
Steve Naroff9af94912008-12-02 15:48:25 +0000751 // Generate the 'getter' function.
Steve Naroff9af94912008-12-02 15:48:25 +0000752 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroff9af94912008-12-02 15:48:25 +0000753 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroff9af94912008-12-02 15:48:25 +0000754 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000755
Steve Naroff003d00e2008-12-02 16:05:55 +0000756 if (!OID)
757 return;
Mike Stump11289f42009-09-09 15:08:12 +0000758
Steve Naroff003d00e2008-12-02 16:05:55 +0000759 std::string Getr;
760 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
761 Getr += "{ ";
762 // Synthesize an explicit cast to gain access to the ivar.
Mike Stump11289f42009-09-09 15:08:12 +0000763 // FIXME: deal with code generation implications for various property
764 // attributes (copy, retain, nonatomic).
Steve Naroff06297042008-12-02 17:54:50 +0000765 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroff003d00e2008-12-02 16:05:55 +0000766 Getr += "return " + getIvarAccessString(ClassDecl, OID);
767 Getr += "; }";
Steve Naroff9af94912008-12-02 15:48:25 +0000768 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroff9af94912008-12-02 15:48:25 +0000769 if (PD->isReadOnly())
770 return;
Mike Stump11289f42009-09-09 15:08:12 +0000771
Steve Naroff9af94912008-12-02 15:48:25 +0000772 // Generate the 'setter' function.
773 std::string Setr;
774 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroff9af94912008-12-02 15:48:25 +0000775 Setr += "{ ";
Steve Naroff003d00e2008-12-02 16:05:55 +0000776 // Synthesize an explicit cast to initialize the ivar.
Mike Stump11289f42009-09-09 15:08:12 +0000777 // FIXME: deal with code generation implications for various property
778 // attributes (copy, retain, nonatomic).
Steve Narofff326f402008-12-03 00:56:33 +0000779 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroff003d00e2008-12-02 16:05:55 +0000780 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000781 Setr += PD->getNameAsCString();
Steve Naroff003d00e2008-12-02 16:05:55 +0000782 Setr += "; }";
Steve Naroff9af94912008-12-02 15:48:25 +0000783 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffe1908e32008-12-01 20:33:01 +0000784}
Chris Lattner16a0de42007-10-11 18:38:32 +0000785
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000786void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattner3c799d72007-10-24 17:06:59 +0000787 // Get the start location and compute the semi location.
788 SourceLocation startLoc = ClassDecl->getLocation();
789 const char *startBuf = SM->getCharacterData(startLoc);
790 const char *semiPtr = strchr(startBuf, ';');
Mike Stump11289f42009-09-09 15:08:12 +0000791
Chris Lattner3c799d72007-10-24 17:06:59 +0000792 // Translate to typedef's that forward reference structs with the same name
793 // as the class. As a convenience, we include the original declaration
794 // as a comment.
795 std::string typedefString;
Fariborz Jahanian1c2cb6d2010-01-11 22:48:40 +0000796 typedefString += "// @class ";
797 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
798 I != E; ++I) {
799 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
800 typedefString += ForwardDecl->getNameAsString();
801 if (I+1 != E)
802 typedefString += ", ";
803 else
804 typedefString += ";\n";
805 }
806
Chris Lattner9ee23b72009-02-20 18:04:31 +0000807 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
808 I != E; ++I) {
Ted Kremenek9b124e12009-11-18 00:28:11 +0000809 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff1b232132007-11-09 12:50:28 +0000810 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000811 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000812 typedefString += "\n";
813 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000814 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000815 typedefString += "\n";
Steve Naroff98eb8d12007-11-05 14:36:37 +0000816 typedefString += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000817 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000818 typedefString += ";\n#endif\n";
Steve Naroff574440f2007-10-24 22:48:43 +0000819 }
Mike Stump11289f42009-09-09 15:08:12 +0000820
Steve Naroff574440f2007-10-24 22:48:43 +0000821 // Replace the @class with typedefs corresponding to the classes.
Mike Stump11289f42009-09-09 15:08:12 +0000822 ReplaceText(startLoc, semiPtr-startBuf+1,
Chris Lattner9cc55f52008-01-31 19:51:04 +0000823 typedefString.c_str(), typedefString.size());
Chris Lattner3c799d72007-10-24 17:06:59 +0000824}
825
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000826void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff3ce37a62007-12-14 23:37:57 +0000827 SourceLocation LocStart = Method->getLocStart();
828 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000829
Chris Lattner88ea93e2009-02-04 01:06:56 +0000830 if (SM->getInstantiationLineNumber(LocEnd) >
831 SM->getInstantiationLineNumber(LocStart)) {
Steve Naroffe020fa12008-10-21 13:37:27 +0000832 InsertText(LocStart, "#if 0\n", 6);
833 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff3ce37a62007-12-14 23:37:57 +0000834 } else {
Chris Lattner1780a852008-01-31 19:42:41 +0000835 InsertText(LocStart, "// ", 3);
Steve Naroff5448cf62007-10-30 13:30:57 +0000836 }
837}
838
Mike Stump11289f42009-09-09 15:08:12 +0000839void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000840 SourceLocation Loc = prop->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000841
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000842 ReplaceText(Loc, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000843
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000844 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahaniane8a30162007-11-07 00:09:37 +0000845}
846
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000847void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000848 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000849
Steve Naroff5448cf62007-10-30 13:30:57 +0000850 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000851 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000852
853 for (ObjCCategoryDecl::instmeth_iterator
854 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000855 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000856 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +0000857 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000858 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000859 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000860 RewriteMethodDeclaration(*I);
861
Steve Naroff5448cf62007-10-30 13:30:57 +0000862 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +0000863 ReplaceText(CatDecl->getAtEndRange().getBegin(), 0, "// ", 3);
Steve Naroff5448cf62007-10-30 13:30:57 +0000864}
865
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000866void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000867 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Mike Stump11289f42009-09-09 15:08:12 +0000868
Steve Narofff921385f2007-10-30 16:42:30 +0000869 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000870
Steve Narofff921385f2007-10-30 16:42:30 +0000871 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000872 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000873
874 for (ObjCProtocolDecl::instmeth_iterator
875 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000876 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000877 RewriteMethodDeclaration(*I);
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000878 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000879 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000880 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000881 RewriteMethodDeclaration(*I);
882
Steve Narofff921385f2007-10-30 16:42:30 +0000883 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +0000884 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Chris Lattner9cc55f52008-01-31 19:51:04 +0000885 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroffa509f042007-11-14 15:03:57 +0000886
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000887 // Must comment out @optional/@required
888 const char *startBuf = SM->getCharacterData(LocStart);
889 const char *endBuf = SM->getCharacterData(LocEnd);
890 for (const char *p = startBuf; p < endBuf; p++) {
891 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
892 std::string CommentedOptional = "/* @optional */";
Steve Naroffa509f042007-11-14 15:03:57 +0000893 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000894 ReplaceText(OptionalLoc, strlen("@optional"),
895 CommentedOptional.c_str(), CommentedOptional.size());
Mike Stump11289f42009-09-09 15:08:12 +0000896
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000897 }
898 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
899 std::string CommentedRequired = "/* @required */";
Steve Naroffa509f042007-11-14 15:03:57 +0000900 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000901 ReplaceText(OptionalLoc, strlen("@required"),
902 CommentedRequired.c_str(), CommentedRequired.size());
Mike Stump11289f42009-09-09 15:08:12 +0000903
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000904 }
905 }
Steve Narofff921385f2007-10-30 16:42:30 +0000906}
907
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000908void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000909 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffc17b0562007-11-14 03:37:28 +0000910 if (LocStart.isInvalid())
911 assert(false && "Invalid SourceLocation");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000912 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000913 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000914}
915
Mike Stump11289f42009-09-09 15:08:12 +0000916void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000917 std::string &ResultStr) {
Steve Naroff295570a2008-10-30 12:09:33 +0000918 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroffb067bbd2008-07-16 14:40:40 +0000919 const FunctionType *FPRetType = 0;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000920 ResultStr += "\nstatic ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000921 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +0000922 ResultStr += "id";
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000923 else if (OMD->getResultType()->isFunctionPointerType() ||
924 OMD->getResultType()->isBlockPointerType()) {
Steve Naroffb067bbd2008-07-16 14:40:40 +0000925 // needs special handling, since pointer-to-functions have special
926 // syntax (where a decaration models use).
927 QualType retType = OMD->getResultType();
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000928 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000929 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000930 PointeeTy = PT->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000931 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000932 PointeeTy = BPT->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +0000933 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000934 ResultStr += FPRetType->getResultType().getAsString();
935 ResultStr += "(*";
Steve Naroffb067bbd2008-07-16 14:40:40 +0000936 }
937 } else
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +0000938 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7262fca2008-01-10 01:39:52 +0000939 ResultStr += " ";
Mike Stump11289f42009-09-09 15:08:12 +0000940
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000941 // Unique method name
Fariborz Jahanian56338352007-11-13 21:02:00 +0000942 std::string NameStr;
Mike Stump11289f42009-09-09 15:08:12 +0000943
Douglas Gregorffca3a22009-01-09 17:18:27 +0000944 if (OMD->isInstanceMethod())
Fariborz Jahanian56338352007-11-13 21:02:00 +0000945 NameStr += "_I_";
946 else
947 NameStr += "_C_";
Mike Stump11289f42009-09-09 15:08:12 +0000948
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000949 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +0000950 NameStr += "_";
Mike Stump11289f42009-09-09 15:08:12 +0000951
952 if (ObjCCategoryImplDecl *CID =
Steve Naroff11b387f2009-01-08 19:41:02 +0000953 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000954 NameStr += CID->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +0000955 NameStr += "_";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000956 }
Mike Stump11289f42009-09-09 15:08:12 +0000957 // Append selector names, replacing ':' with '_'
Chris Lattnere4b95692008-11-24 03:33:13 +0000958 {
959 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000960 int len = selString.size();
961 for (int i = 0; i < len; i++)
962 if (selString[i] == ':')
963 selString[i] = '_';
Fariborz Jahanian56338352007-11-13 21:02:00 +0000964 NameStr += selString;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000965 }
Fariborz Jahanian56338352007-11-13 21:02:00 +0000966 // Remember this name for metadata emission
967 MethodInternalNames[OMD] = NameStr;
968 ResultStr += NameStr;
Mike Stump11289f42009-09-09 15:08:12 +0000969
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000970 // Rewrite arguments
971 ResultStr += "(";
Mike Stump11289f42009-09-09 15:08:12 +0000972
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000973 // invisible arguments
Douglas Gregorffca3a22009-01-09 17:18:27 +0000974 if (OMD->isInstanceMethod()) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000975 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000976 selfTy = Context->getPointerType(selfTy);
Steve Naroffdc5b6b22008-03-12 00:25:36 +0000977 if (!LangOpts.Microsoft) {
978 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
979 ResultStr += "struct ";
980 }
981 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000982 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +0000983 ResultStr += " *";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000984 }
985 else
Steve Naroffd9803712009-04-29 16:37:50 +0000986 ResultStr += Context->getObjCClassType().getAsString();
Mike Stump11289f42009-09-09 15:08:12 +0000987
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000988 ResultStr += " self, ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000989 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000990 ResultStr += " _cmd";
Mike Stump11289f42009-09-09 15:08:12 +0000991
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000992 // Method arguments.
Chris Lattnera4997152009-02-20 18:43:26 +0000993 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
994 E = OMD->param_end(); PI != E; ++PI) {
995 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000996 ResultStr += ", ";
Steve Naroffdcdcdcd2008-04-18 21:13:19 +0000997 if (PDecl->getType()->isObjCQualifiedIdType()) {
998 ResultStr += "id ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000999 ResultStr += PDecl->getNameAsString();
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001000 } else {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001001 std::string Name = PDecl->getNameAsString();
Steve Naroffa5c0db82008-12-11 21:05:33 +00001002 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroff44df6a22008-10-30 14:45:29 +00001003 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001004 const BlockPointerType *BPT = PDecl->getType()->getAs<BlockPointerType>();
Douglas Gregor7de59662009-05-29 20:38:28 +00001005 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name,
1006 Context->PrintingPolicy);
Steve Naroff44df6a22008-10-30 14:45:29 +00001007 } else
Douglas Gregor7de59662009-05-29 20:38:28 +00001008 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001009 ResultStr += Name;
1010 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001011 }
Fariborz Jahanianeab81cd2008-01-21 20:14:23 +00001012 if (OMD->isVariadic())
1013 ResultStr += ", ...";
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001014 ResultStr += ") ";
Mike Stump11289f42009-09-09 15:08:12 +00001015
Steve Naroffb067bbd2008-07-16 14:40:40 +00001016 if (FPRetType) {
1017 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump11289f42009-09-09 15:08:12 +00001018
Steve Naroffb067bbd2008-07-16 14:40:40 +00001019 // Now, emit the argument types (if any).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001020 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001021 ResultStr += "(";
1022 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1023 if (i) ResultStr += ", ";
1024 std::string ParamStr = FT->getArgType(i).getAsString();
1025 ResultStr += ParamStr;
1026 }
1027 if (FT->isVariadic()) {
1028 if (FT->getNumArgs()) ResultStr += ", ";
1029 ResultStr += "...";
1030 }
1031 ResultStr += ")";
1032 } else {
1033 ResultStr += "()";
1034 }
1035 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001036}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001037void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001038 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1039 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump11289f42009-09-09 15:08:12 +00001040
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001041 if (IMD)
Chris Lattner1780a852008-01-31 19:42:41 +00001042 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001043 else
Chris Lattner1780a852008-01-31 19:42:41 +00001044 InsertText(CID->getLocStart(), "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +00001045
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001046 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001047 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1048 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001049 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001050 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001051 ObjCMethodDecl *OMD = *I;
1052 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001053 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001054 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redla7b98a72009-04-26 20:35:05 +00001055
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001056 const char *startBuf = SM->getCharacterData(LocStart);
1057 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattner9cc55f52008-01-31 19:51:04 +00001058 ReplaceText(LocStart, endBuf-startBuf,
1059 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001060 }
Mike Stump11289f42009-09-09 15:08:12 +00001061
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001062 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001063 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1064 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001065 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001066 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001067 ObjCMethodDecl *OMD = *I;
1068 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001069 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001070 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +00001071
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001072 const char *startBuf = SM->getCharacterData(LocStart);
1073 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattner9cc55f52008-01-31 19:51:04 +00001074 ReplaceText(LocStart, endBuf-startBuf,
Mike Stump11289f42009-09-09 15:08:12 +00001075 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001076 }
Steve Naroffe1908e32008-12-01 20:33:01 +00001077 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001078 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001079 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001080 I != E; ++I) {
Steve Naroffc038b3a2008-12-02 17:36:43 +00001081 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffe1908e32008-12-01 20:33:01 +00001082 }
1083
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001084 if (IMD)
Chris Lattner1780a852008-01-31 19:42:41 +00001085 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001086 else
Mike Stump11289f42009-09-09 15:08:12 +00001087 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001088}
1089
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001090void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffc5484042007-10-30 02:23:23 +00001091 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001092 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff2f55b982007-11-01 03:35:41 +00001093 // we haven't seen a forward decl - generate a typedef.
Steve Naroff03f27672007-11-14 23:02:56 +00001094 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001095 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001096 ResultStr += "\n";
1097 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001098 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001099 ResultStr += "\n";
Steve Naroffa1e115e2008-03-10 23:16:54 +00001100 ResultStr += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001101 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001102 ResultStr += ";\n#endif\n";
Steve Naroff2f55b982007-11-01 03:35:41 +00001103 // Mark this typedef as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001104 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff2f55b982007-11-01 03:35:41 +00001105 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001106 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump11289f42009-09-09 15:08:12 +00001107
1108 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001109 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff0c0f5ba2009-01-11 01:06:09 +00001110 RewriteProperty(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001111 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001112 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001113 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001114 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001115 for (ObjCInterfaceDecl::classmeth_iterator
1116 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001117 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001118 RewriteMethodDeclaration(*I);
1119
Steve Naroff4cd61ac2007-10-30 03:43:13 +00001120 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +00001121 ReplaceText(ClassDecl->getAtEndRange().getBegin(), 0, "// ", 3);
Steve Naroff161a92b2007-10-26 20:53:56 +00001122}
1123
Steve Naroff08628db2008-12-09 12:56:34 +00001124Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1125 SourceRange SrcRange) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00001126 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1127 // This allows us to reuse all the fun and games in SynthMessageExpr().
1128 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1129 ObjCMessageExpr *MsgExpr;
1130 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1131 llvm::SmallVector<Expr *, 1> ExprVec;
1132 ExprVec.push_back(newStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001133
Steve Naroff1042ff32008-12-08 16:43:47 +00001134 Stmt *Receiver = PropRefExpr->getBase();
1135 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1136 if (PRE && PropGetters[PRE]) {
1137 // This allows us to handle chain/nested property getters.
1138 Receiver = PropGetters[PRE];
1139 }
Mike Stump11289f42009-09-09 15:08:12 +00001140 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1141 PDecl->getSetterName(), PDecl->getType(),
1142 PDecl->getSetterMethodDecl(),
1143 SourceLocation(), SourceLocation(),
Steve Naroff4588d0f2008-12-04 16:24:46 +00001144 &ExprVec[0], 1);
1145 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001146
Steve Naroff4588d0f2008-12-04 16:24:46 +00001147 // Now do the actual rewrite.
Steve Naroff08628db2008-12-09 12:56:34 +00001148 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffdf705772008-12-10 14:53:27 +00001149 //delete BinOp;
Ted Kremenek5a201952009-02-07 01:47:29 +00001150 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1151 // to things that stay around.
1152 Context->Deallocate(MsgExpr);
Steve Naroff4588d0f2008-12-04 16:24:46 +00001153 return ReplacingStmt;
Steve Narofff326f402008-12-03 00:56:33 +00001154}
1155
Steve Naroff4588d0f2008-12-04 16:24:46 +00001156Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Narofff326f402008-12-03 00:56:33 +00001157 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1158 // This allows us to reuse all the fun and games in SynthMessageExpr().
1159 ObjCMessageExpr *MsgExpr;
1160 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
Mike Stump11289f42009-09-09 15:08:12 +00001161
Steve Naroff1042ff32008-12-08 16:43:47 +00001162 Stmt *Receiver = PropRefExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00001163
Steve Naroff1042ff32008-12-08 16:43:47 +00001164 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1165 if (PRE && PropGetters[PRE]) {
1166 // This allows us to handle chain/nested property getters.
1167 Receiver = PropGetters[PRE];
1168 }
Mike Stump11289f42009-09-09 15:08:12 +00001169 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1170 PDecl->getGetterName(), PDecl->getType(),
1171 PDecl->getGetterMethodDecl(),
1172 SourceLocation(), SourceLocation(),
Steve Narofff326f402008-12-03 00:56:33 +00001173 0, 0);
1174
Steve Naroff22216db2008-12-04 23:50:32 +00001175 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001176
1177 if (!PropParentMap)
1178 PropParentMap = new ParentMap(CurrentBody);
1179
1180 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1181 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1182 // We stash away the ReplacingStmt since actually doing the
1183 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1184 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek5a201952009-02-07 01:47:29 +00001185 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1186 // to things that stay around.
1187 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001188 return PropRefExpr; // return the original...
1189 } else {
1190 ReplaceStmt(PropRefExpr, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001191 // delete PropRefExpr; elsewhere...
Ted Kremenek5a201952009-02-07 01:47:29 +00001192 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1193 // to things that stay around.
1194 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001195 return ReplacingStmt;
1196 }
Steve Narofff326f402008-12-03 00:56:33 +00001197}
1198
Mike Stump11289f42009-09-09 15:08:12 +00001199Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001200 SourceLocation OrigStart) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001201 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001202 const Expr *BaseExpr = IV->getBase();
Steve Naroff677ab3a2008-10-27 17:20:55 +00001203 if (CurMethodDef) {
Fariborz Jahanian12e2e862010-01-12 17:31:23 +00001204 if (BaseExpr->getType()->isObjCObjectPointerType() &&
1205 isa<DeclRefExpr>(BaseExpr)) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001206 ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001207 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroffb1c02372008-05-08 17:52:16 +00001208 // lookup which class implements the instance variable.
1209 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001210 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001211 clsDeclared);
Steve Naroffb1c02372008-05-08 17:52:16 +00001212 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001213
Steve Naroffb1c02372008-05-08 17:52:16 +00001214 // Synthesize an explicit cast to gain access to the ivar.
1215 std::string RecName = clsDeclared->getIdentifier()->getName();
1216 RecName += "_IMPL";
1217 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001218 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001219 SourceLocation(), II);
Steve Naroffb1c02372008-05-08 17:52:16 +00001220 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1221 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Mike Stump11289f42009-09-09 15:08:12 +00001222 CastExpr *castExpr = new (Context) CStyleCastExpr(castT,
Anders Carlssona2615922009-07-31 00:48:10 +00001223 CastExpr::CK_Unknown,
1224 IV->getBase(),
1225 castT,SourceLocation(),
1226 SourceLocation());
Steve Naroffb1c02372008-05-08 17:52:16 +00001227 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001228 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1229 IV->getBase()->getLocEnd(),
1230 castExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001231 if (IV->isFreeIvar() &&
Steve Naroff677ab3a2008-10-27 17:20:55 +00001232 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001233 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1234 IV->getLocation(),
1235 D->getType());
Steve Naroffb1c02372008-05-08 17:52:16 +00001236 ReplaceStmt(IV, ME);
Steve Naroff22216db2008-12-04 23:50:32 +00001237 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb1c02372008-05-08 17:52:16 +00001238 return ME;
Steve Naroff05caa482007-11-15 11:33:00 +00001239 }
Mike Stump11289f42009-09-09 15:08:12 +00001240
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001241 ReplaceStmt(IV->getBase(), PE);
1242 // Cannot delete IV->getBase(), since PE points to it.
1243 // Replace the old base with the cast. This is important when doing
1244 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001245 IV->setBase(PE);
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001246 return IV;
Steve Naroff05caa482007-11-15 11:33:00 +00001247 }
Steve Naroff24840f62008-04-18 21:55:08 +00001248 } else { // we are outside a method.
Steve Naroff29ce4e52008-05-06 23:20:07 +00001249 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump11289f42009-09-09 15:08:12 +00001250
Steve Naroff29ce4e52008-05-06 23:20:07 +00001251 // Explicit ivar refs need to have a cast inserted.
1252 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian12e2e862010-01-12 17:31:23 +00001253 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Fariborz Jahanian9146e442010-01-11 17:50:35 +00001254 ObjCInterfaceType *iFaceDecl =
1255 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001256 // lookup which class implements the instance variable.
1257 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001258 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001259 clsDeclared);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001260 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001261
Steve Naroff29ce4e52008-05-06 23:20:07 +00001262 // Synthesize an explicit cast to gain access to the ivar.
1263 std::string RecName = clsDeclared->getIdentifier()->getName();
1264 RecName += "_IMPL";
1265 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001266 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001267 SourceLocation(), II);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001268 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1269 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Mike Stump11289f42009-09-09 15:08:12 +00001270 CastExpr *castExpr = new (Context) CStyleCastExpr(castT,
Anders Carlssona2615922009-07-31 00:48:10 +00001271 CastExpr::CK_Unknown,
1272 IV->getBase(),
Ted Kremenek5a201952009-02-07 01:47:29 +00001273 castT, SourceLocation(),
1274 SourceLocation());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001275 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001276 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner34873d22008-05-28 16:38:23 +00001277 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001278 ReplaceStmt(IV->getBase(), PE);
1279 // Cannot delete IV->getBase(), since PE points to it.
1280 // Replace the old base with the cast. This is important when doing
1281 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001282 IV->setBase(PE);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001283 return IV;
1284 }
Steve Naroff05caa482007-11-15 11:33:00 +00001285 }
Steve Naroff24840f62008-04-18 21:55:08 +00001286 return IV;
Steve Narofff60782b2007-11-15 02:58:25 +00001287}
1288
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001289/// SynthCountByEnumWithState - To print:
1290/// ((unsigned int (*)
1291/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001292/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001293/// sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001294/// "countByEnumeratingWithState:objects:count:"),
1295/// &enumState,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001296/// (id *)items, (unsigned int)16)
1297///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001298void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001299 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1300 "id *, unsigned int))(void *)objc_msgSend)";
1301 buf += "\n\t\t";
1302 buf += "((id)l_collection,\n\t\t";
1303 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1304 buf += "\n\t\t";
1305 buf += "&enumState, "
1306 "(id *)items, (unsigned int)16)";
1307}
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001308
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001309/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1310/// statement to exit to its outer synthesized loop.
1311///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001312Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001313 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1314 return S;
1315 // replace break with goto __break_label
1316 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001317
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001318 SourceLocation startLoc = S->getLocStart();
1319 buf = "goto __break_label_";
1320 buf += utostr(ObjCBcLabelNo.back());
Chris Lattner9cc55f52008-01-31 19:51:04 +00001321 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001322
1323 return 0;
1324}
1325
1326/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1327/// statement to continue with its inner synthesized loop.
1328///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001329Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001330 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1331 return S;
1332 // replace continue with goto __continue_label
1333 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001334
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001335 SourceLocation startLoc = S->getLocStart();
1336 buf = "goto __continue_label_";
1337 buf += utostr(ObjCBcLabelNo.back());
Chris Lattner9cc55f52008-01-31 19:51:04 +00001338 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001339
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001340 return 0;
1341}
1342
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001343/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001344/// It rewrites:
1345/// for ( type elem in collection) { stmts; }
Mike Stump11289f42009-09-09 15:08:12 +00001346
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001347/// Into:
1348/// {
Mike Stump11289f42009-09-09 15:08:12 +00001349/// type elem;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001350/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001351/// id items[16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001352/// id l_collection = (id)collection;
Mike Stump11289f42009-09-09 15:08:12 +00001353/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001354/// objects:items count:16];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001355/// if (limit) {
1356/// unsigned long startMutations = *enumState.mutationsPtr;
1357/// do {
1358/// unsigned long counter = 0;
1359/// do {
Mike Stump11289f42009-09-09 15:08:12 +00001360/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001361/// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001362/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001363/// stmts;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001364/// __continue_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001365/// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001366/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001367/// objects:items count:16]);
1368/// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001369/// __break_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001370/// }
1371/// else
1372/// elem = nil;
1373/// }
1374///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001375Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattnera779d692008-01-31 05:10:40 +00001376 SourceLocation OrigEnd) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001377 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001378 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001379 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump11289f42009-09-09 15:08:12 +00001380 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001381 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001382
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001383 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001384 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001385 const char *elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001386 std::string elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001387 std::string buf;
1388 buf = "\n{\n\t";
1389 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1390 // type elem;
Chris Lattner529efc72009-03-28 06:33:19 +00001391 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek292b3842008-10-06 22:16:13 +00001392 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001393 if (ElementType->isObjCQualifiedIdType() ||
1394 ElementType->isObjCQualifiedInterfaceType())
1395 // Simply use 'id' for all qualified types.
1396 elementTypeAsString = "id";
1397 else
1398 elementTypeAsString = ElementType.getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001399 buf += elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001400 buf += " ";
Chris Lattner86d7d912008-11-24 03:54:41 +00001401 elementName = D->getNameAsCString();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001402 buf += elementName;
1403 buf += ";\n\t";
1404 }
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001405 else {
1406 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner86d7d912008-11-24 03:54:41 +00001407 elementName = DR->getDecl()->getNameAsCString();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001408 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1409 if (VD->getType()->isObjCQualifiedIdType() ||
1410 VD->getType()->isObjCQualifiedInterfaceType())
1411 // Simply use 'id' for all qualified types.
1412 elementTypeAsString = "id";
1413 else
1414 elementTypeAsString = VD->getType().getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001415 }
Mike Stump11289f42009-09-09 15:08:12 +00001416
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001417 // struct __objcFastEnumerationState enumState = { 0 };
1418 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1419 // id items[16];
1420 buf += "id items[16];\n\t";
1421 // id l_collection = (id)
1422 buf += "id l_collection = (id)";
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001423 // Find start location of 'collection' the hard way!
1424 const char *startCollectionBuf = startBuf;
1425 startCollectionBuf += 3; // skip 'for'
1426 startCollectionBuf = strchr(startCollectionBuf, '(');
1427 startCollectionBuf++; // skip '('
1428 // find 'in' and skip it.
1429 while (*startCollectionBuf != ' ' ||
1430 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1431 (*(startCollectionBuf+3) != ' ' &&
1432 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1433 startCollectionBuf++;
1434 startCollectionBuf += 3;
Mike Stump11289f42009-09-09 15:08:12 +00001435
1436 // Replace: "for (type element in" with string constructed thus far.
Chris Lattner9cc55f52008-01-31 19:51:04 +00001437 ReplaceText(startLoc, startCollectionBuf - startBuf,
1438 buf.c_str(), buf.size());
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001439 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001440 SourceLocation rightParenLoc = S->getRParenLoc();
1441 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1442 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001443 buf = ";\n\t";
Mike Stump11289f42009-09-09 15:08:12 +00001444
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001445 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1446 // objects:items count:16];
1447 // which is synthesized into:
Mike Stump11289f42009-09-09 15:08:12 +00001448 // unsigned int limit =
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001449 // ((unsigned int (*)
1450 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001451 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001452 // sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001453 // "countByEnumeratingWithState:objects:count:"),
1454 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001455 // (id *)items, (unsigned int)16);
1456 buf += "unsigned long limit =\n\t\t";
1457 SynthCountByEnumWithState(buf);
1458 buf += ";\n\t";
1459 /// if (limit) {
1460 /// unsigned long startMutations = *enumState.mutationsPtr;
1461 /// do {
1462 /// unsigned long counter = 0;
1463 /// do {
Mike Stump11289f42009-09-09 15:08:12 +00001464 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001465 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001466 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001467 buf += "if (limit) {\n\t";
1468 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1469 buf += "do {\n\t\t";
1470 buf += "unsigned long counter = 0;\n\t\t";
1471 buf += "do {\n\t\t\t";
1472 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1473 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1474 buf += elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001475 buf += " = (";
1476 buf += elementTypeAsString;
1477 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001478 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattner9cc55f52008-01-31 19:51:04 +00001479 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001480
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001481 /// __continue_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001482 /// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001483 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001484 /// objects:items count:16]);
1485 /// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001486 /// __break_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001487 /// }
1488 /// else
1489 /// elem = nil;
1490 /// }
Mike Stump11289f42009-09-09 15:08:12 +00001491 ///
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001492 buf = ";\n\t";
1493 buf += "__continue_label_";
1494 buf += utostr(ObjCBcLabelNo.back());
1495 buf += ": ;";
1496 buf += "\n\t\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001497 buf += "} while (counter < limit);\n\t";
1498 buf += "} while (limit = ";
1499 SynthCountByEnumWithState(buf);
1500 buf += ");\n\t";
1501 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001502 buf += " = ((";
1503 buf += elementTypeAsString;
1504 buf += ")0);\n\t";
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001505 buf += "__break_label_";
1506 buf += utostr(ObjCBcLabelNo.back());
1507 buf += ": ;\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001508 buf += "}\n\t";
1509 buf += "else\n\t\t";
1510 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001511 buf += " = ((";
1512 buf += elementTypeAsString;
1513 buf += ")0);\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001514 buf += "}\n";
Mike Stump11289f42009-09-09 15:08:12 +00001515
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001516 // Insert all these *after* the statement body.
Sebastian Redla7b98a72009-04-26 20:35:05 +00001517 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Narofff0ff8792008-07-21 18:26:02 +00001518 if (isa<CompoundStmt>(S->getBody())) {
1519 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1520 InsertText(endBodyLoc, buf.c_str(), buf.size());
1521 } else {
1522 /* Need to treat single statements specially. For example:
1523 *
1524 * for (A *a in b) if (stuff()) break;
1525 * for (A *a in b) xxxyy;
1526 *
1527 * The following code simply scans ahead to the semi to find the actual end.
1528 */
1529 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1530 const char *semiBuf = strchr(stmtBuf, ';');
1531 assert(semiBuf && "Can't find ';'");
1532 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1533 InsertText(endBodyLoc, buf.c_str(), buf.size());
1534 }
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001535 Stmts.pop_back();
1536 ObjCBcLabelNo.pop_back();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001537 return 0;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001538}
1539
Mike Stump11289f42009-09-09 15:08:12 +00001540/// RewriteObjCSynchronizedStmt -
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001541/// This routine rewrites @synchronized(expr) stmt;
1542/// into:
1543/// objc_sync_enter(expr);
1544/// @try stmt @finally { objc_sync_exit(expr); }
1545///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001546Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001547 // Get the start location and compute the semi location.
1548 SourceLocation startLoc = S->getLocStart();
1549 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001550
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001551 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump11289f42009-09-09 15:08:12 +00001552
1553 std::string buf;
Steve Naroffb2fc0522008-08-21 13:03:03 +00001554 buf = "objc_sync_enter((id)";
1555 const char *lparenBuf = startBuf;
1556 while (*lparenBuf != '(') lparenBuf++;
1557 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001558 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1559 // the sync expression is typically a message expression that's already
Steve Naroffad7013b2008-08-19 13:04:19 +00001560 // been rewritten! (which implies the SourceLocation's are invalid).
1561 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001562 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffad7013b2008-08-19 13:04:19 +00001563 while (*endBuf != ')') endBuf--;
1564 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001565 buf = ");\n";
1566 // declare a new scope with two variables, _stack and _rethrow.
1567 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1568 buf += "int buf[18/*32-bit i386*/];\n";
1569 buf += "char *pointers[4];} _stack;\n";
1570 buf += "id volatile _rethrow = 0;\n";
1571 buf += "objc_exception_try_enter(&_stack);\n";
1572 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001573 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001574 startLoc = S->getSynchBody()->getLocEnd();
1575 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001576
Steve Naroffad7013b2008-08-19 13:04:19 +00001577 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001578 SourceLocation lastCurlyLoc = startLoc;
1579 buf = "}\nelse {\n";
1580 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroffd9803712009-04-29 16:37:50 +00001581 buf += "}\n";
1582 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001583 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffec60b432009-12-05 21:43:12 +00001584
1585 std::string syncBuf;
1586 syncBuf += " objc_sync_exit(";
Mike Stump11289f42009-09-09 15:08:12 +00001587 Expr *syncExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00001588 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00001589 S->getSynchExpr(),
Ted Kremenek5a201952009-02-07 01:47:29 +00001590 Context->getObjCIdType(),
1591 SourceLocation(),
1592 SourceLocation());
Ted Kremenek2d470fc2008-09-13 05:16:45 +00001593 std::string syncExprBufS;
1594 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00001595 syncExpr->printPretty(syncExprBuf, *Context, 0,
1596 PrintingPolicy(LangOpts));
Steve Naroffec60b432009-12-05 21:43:12 +00001597 syncBuf += syncExprBuf.str();
1598 syncBuf += ");";
1599
1600 buf += syncBuf;
1601 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001602 buf += "}\n";
1603 buf += "}";
Mike Stump11289f42009-09-09 15:08:12 +00001604
Chris Lattner9cc55f52008-01-31 19:51:04 +00001605 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffec60b432009-12-05 21:43:12 +00001606
1607 bool hasReturns = false;
1608 HasReturnStmts(S->getSynchBody(), hasReturns);
1609 if (hasReturns)
1610 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1611
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001612 return 0;
1613}
1614
Steve Naroffec60b432009-12-05 21:43:12 +00001615void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1616{
Steve Naroff6d6da252008-12-05 17:03:39 +00001617 // Perform a bottom up traversal of all children.
1618 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1619 CI != E; ++CI)
1620 if (*CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001621 WarnAboutReturnGotoStmts(*CI);
Steve Naroff6d6da252008-12-05 17:03:39 +00001622
Steve Naroffec60b432009-12-05 21:43:12 +00001623 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump11289f42009-09-09 15:08:12 +00001624 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff6d6da252008-12-05 17:03:39 +00001625 TryFinallyContainsReturnDiag);
1626 }
1627 return;
1628}
1629
Steve Naroffec60b432009-12-05 21:43:12 +00001630void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1631{
1632 // Perform a bottom up traversal of all children.
1633 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1634 CI != E; ++CI)
1635 if (*CI)
1636 HasReturnStmts(*CI, hasReturns);
1637
1638 if (isa<ReturnStmt>(S))
1639 hasReturns = true;
1640 return;
1641}
1642
1643void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1644 // Perform a bottom up traversal of all children.
1645 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1646 CI != E; ++CI)
1647 if (*CI) {
1648 RewriteTryReturnStmts(*CI);
1649 }
1650 if (isa<ReturnStmt>(S)) {
1651 SourceLocation startLoc = S->getLocStart();
1652 const char *startBuf = SM->getCharacterData(startLoc);
1653
1654 const char *semiBuf = strchr(startBuf, ';');
1655 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1656 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1657
1658 std::string buf;
1659 buf = "{ objc_exception_try_exit(&_stack); return";
1660
1661 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1662 InsertText(onePastSemiLoc, "}", 1);
1663 }
1664 return;
1665}
1666
1667void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1668 // Perform a bottom up traversal of all children.
1669 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1670 CI != E; ++CI)
1671 if (*CI) {
1672 RewriteSyncReturnStmts(*CI, syncExitBuf);
1673 }
1674 if (isa<ReturnStmt>(S)) {
1675 SourceLocation startLoc = S->getLocStart();
1676 const char *startBuf = SM->getCharacterData(startLoc);
1677
1678 const char *semiBuf = strchr(startBuf, ';');
1679 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1680 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1681
1682 std::string buf;
1683 buf = "{ objc_exception_try_exit(&_stack);";
1684 buf += syncExitBuf;
1685 buf += " return";
1686
1687 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1688 InsertText(onePastSemiLoc, "}", 1);
1689 }
1690 return;
1691}
1692
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001693Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001694 // Get the start location and compute the semi location.
1695 SourceLocation startLoc = S->getLocStart();
1696 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001697
Steve Naroffbf478ec2007-11-07 04:08:17 +00001698 assert((*startBuf == '@') && "bogus @try location");
1699
1700 std::string buf;
1701 // declare a new scope with two variables, _stack and _rethrow.
1702 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1703 buf += "int buf[18/*32-bit i386*/];\n";
1704 buf += "char *pointers[4];} _stack;\n";
1705 buf += "id volatile _rethrow = 0;\n";
1706 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff16018582007-11-07 18:43:40 +00001707 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffbf478ec2007-11-07 04:08:17 +00001708
Chris Lattner9cc55f52008-01-31 19:51:04 +00001709 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001710
Steve Naroffbf478ec2007-11-07 04:08:17 +00001711 startLoc = S->getTryBody()->getLocEnd();
1712 startBuf = SM->getCharacterData(startLoc);
1713
1714 assert((*startBuf == '}') && "bogus @try block");
Mike Stump11289f42009-09-09 15:08:12 +00001715
Steve Naroffbf478ec2007-11-07 04:08:17 +00001716 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffce2dca12008-07-16 15:31:30 +00001717 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1718 if (catchList) {
1719 startLoc = startLoc.getFileLocWithOffset(1);
1720 buf = " /* @catch begin */ else {\n";
1721 buf += " id _caught = objc_exception_extract(&_stack);\n";
1722 buf += " objc_exception_try_enter (&_stack);\n";
1723 buf += " if (_setjmp(_stack.buf))\n";
1724 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1725 buf += " else { /* @catch continue */";
Mike Stump11289f42009-09-09 15:08:12 +00001726
Steve Naroffce2dca12008-07-16 15:31:30 +00001727 InsertText(startLoc, buf.c_str(), buf.size());
Steve Narofffac18fe2008-09-09 19:59:12 +00001728 } else { /* no catch list */
1729 buf = "}\nelse {\n";
1730 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1731 buf += "}";
1732 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffce2dca12008-07-16 15:31:30 +00001733 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001734 bool sawIdTypedCatch = false;
1735 Stmt *lastCatchBody = 0;
Steve Naroffbf478ec2007-11-07 04:08:17 +00001736 while (catchList) {
Steve Naroff371b8fb2009-03-03 19:52:17 +00001737 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001738
Mike Stump11289f42009-09-09 15:08:12 +00001739 if (catchList == S->getCatchStmts())
Steve Naroffbf478ec2007-11-07 04:08:17 +00001740 buf = "if ("; // we are generating code for the first catch clause
1741 else
1742 buf = "else if (";
1743 startLoc = catchList->getLocStart();
1744 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001745
Steve Naroffbf478ec2007-11-07 04:08:17 +00001746 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump11289f42009-09-09 15:08:12 +00001747
Steve Naroffbf478ec2007-11-07 04:08:17 +00001748 const char *lParenLoc = strchr(startBuf, '(');
1749
Steve Naroffe6b7ffd2008-02-01 22:08:12 +00001750 if (catchList->hasEllipsis()) {
Steve Naroffedb5bc62008-02-01 20:02:07 +00001751 // Now rewrite the body...
1752 lastCatchBody = catchList->getCatchBody();
Steve Naroffedb5bc62008-02-01 20:02:07 +00001753 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1754 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001755 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1756 "bogus @catch paren location");
Steve Naroffedb5bc62008-02-01 20:02:07 +00001757 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001758
Steve Naroffedb5bc62008-02-01 20:02:07 +00001759 buf += "1) { id _tmp = _caught;";
Daniel Dunbardec484a2009-08-19 19:10:30 +00001760 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff371b8fb2009-03-03 19:52:17 +00001761 } else if (catchDecl) {
1762 QualType t = catchDecl->getType();
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001763 if (t == Context->getObjCIdType()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001764 buf += "1) { ";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001765 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001766 sawIdTypedCatch = true;
Fariborz Jahanian59516092010-01-12 01:22:23 +00001767 } else if (t->isObjCObjectPointerType()) {
1768 QualType InterfaceTy = t->getPointeeType();
1769 const ObjCInterfaceType *cls = // Should be a pointer to a class.
1770 InterfaceTy->getAs<ObjCInterfaceType>();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001771 if (cls) {
Steve Naroff16018582007-11-07 18:43:40 +00001772 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001773 buf += cls->getDecl()->getNameAsString();
Steve Naroff16018582007-11-07 18:43:40 +00001774 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001775 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001776 }
1777 }
1778 // Now rewrite the body...
1779 lastCatchBody = catchList->getCatchBody();
1780 SourceLocation rParenLoc = catchList->getRParenLoc();
1781 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1782 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1783 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1784 assert((*rParenBuf == ')') && "bogus @catch paren location");
1785 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001786
Steve Naroffbf478ec2007-11-07 04:08:17 +00001787 buf = " = _caught;";
Mike Stump11289f42009-09-09 15:08:12 +00001788 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroffbf478ec2007-11-07 04:08:17 +00001789 // declares the @catch parameter).
Chris Lattner9cc55f52008-01-31 19:51:04 +00001790 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff371b8fb2009-03-03 19:52:17 +00001791 } else {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001792 assert(false && "@catch rewrite bug");
Steve Naroffa733c7f2007-11-07 15:32:26 +00001793 }
Steve Naroffedb5bc62008-02-01 20:02:07 +00001794 // make sure all the catch bodies get rewritten!
Steve Naroffbf478ec2007-11-07 04:08:17 +00001795 catchList = catchList->getNextCatchStmt();
1796 }
1797 // Complete the catch list...
1798 if (lastCatchBody) {
1799 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001800 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1801 "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001802
Steve Naroff4adbe312008-09-11 15:29:03 +00001803 // Insert the last (implicit) else clause *before* the right curly brace.
1804 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1805 buf = "} /* last catch end */\n";
1806 buf += "else {\n";
1807 buf += " _rethrow = _caught;\n";
1808 buf += " objc_exception_try_exit(&_stack);\n";
1809 buf += "} } /* @catch end */\n";
1810 if (!S->getFinallyStmt())
1811 buf += "}\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001812 InsertText(bodyLoc, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001813
Steve Naroffbf478ec2007-11-07 04:08:17 +00001814 // Set lastCurlyLoc
1815 lastCurlyLoc = lastCatchBody->getLocEnd();
1816 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001817 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001818 startLoc = finalStmt->getLocStart();
1819 startBuf = SM->getCharacterData(startLoc);
1820 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump11289f42009-09-09 15:08:12 +00001821
Steve Naroffbf478ec2007-11-07 04:08:17 +00001822 buf = "/* @finally */";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001823 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001824
Steve Naroffbf478ec2007-11-07 04:08:17 +00001825 Stmt *body = finalStmt->getFinallyBody();
1826 SourceLocation startLoc = body->getLocStart();
1827 SourceLocation endLoc = body->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001828 assert(*SM->getCharacterData(startLoc) == '{' &&
1829 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001830 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001831 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001832
Steve Naroffbf478ec2007-11-07 04:08:17 +00001833 startLoc = startLoc.getFileLocWithOffset(1);
1834 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001835 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001836 endLoc = endLoc.getFileLocWithOffset(-1);
1837 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001838 InsertText(endLoc, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001839
Steve Naroffbf478ec2007-11-07 04:08:17 +00001840 // Set lastCurlyLoc
1841 lastCurlyLoc = body->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00001842
Steve Naroff6d6da252008-12-05 17:03:39 +00001843 // Now check for any return/continue/go statements within the @try.
Steve Naroffec60b432009-12-05 21:43:12 +00001844 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff4adbe312008-09-11 15:29:03 +00001845 } else { /* no finally clause - make sure we synthesize an implicit one */
1846 buf = "{ /* implicit finally clause */\n";
1847 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1848 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1849 buf += "}";
1850 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffec60b432009-12-05 21:43:12 +00001851
1852 // Now check for any return/continue/go statements within the @try.
1853 // The implicit finally clause won't called if the @try contains any
1854 // jump statements.
1855 bool hasReturns = false;
1856 HasReturnStmts(S->getTryBody(), hasReturns);
1857 if (hasReturns)
1858 RewriteTryReturnStmts(S->getTryBody());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001859 }
1860 // Now emit the final closing curly brace...
1861 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1862 buf = " } /* @try scope end */\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001863 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001864 return 0;
1865}
1866
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001867Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001868 return 0;
1869}
1870
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001871Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001872 return 0;
1873}
1874
Mike Stump11289f42009-09-09 15:08:12 +00001875// This can't be done with ReplaceStmt(S, ThrowExpr), since
1876// the throw expression is typically a message expression that's already
Steve Naroffa733c7f2007-11-07 15:32:26 +00001877// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001878Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroffa733c7f2007-11-07 15:32:26 +00001879 // Get the start location and compute the semi location.
1880 SourceLocation startLoc = S->getLocStart();
1881 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001882
Steve Naroffa733c7f2007-11-07 15:32:26 +00001883 assert((*startBuf == '@') && "bogus @throw location");
1884
1885 std::string buf;
1886 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffc7d2df22008-01-19 00:42:38 +00001887 if (S->getThrowExpr())
1888 buf = "objc_exception_throw(";
1889 else // add an implicit argument
1890 buf = "objc_exception_throw(_caught";
Mike Stump11289f42009-09-09 15:08:12 +00001891
Steve Naroff29788342008-07-25 15:41:30 +00001892 // handle "@ throw" correctly.
1893 const char *wBuf = strchr(startBuf, 'w');
1894 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1895 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001896
Steve Naroffa733c7f2007-11-07 15:32:26 +00001897 const char *semiBuf = strchr(startBuf, ';');
1898 assert((*semiBuf == ';') && "@throw: can't find ';'");
1899 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1900 buf = ");";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001901 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroffa733c7f2007-11-07 15:32:26 +00001902 return 0;
1903}
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001904
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001905Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerc6d91c02007-10-17 22:35:30 +00001906 // Create a new string expression.
1907 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlssond8499822007-10-29 05:01:08 +00001908 std::string StrEncoding;
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00001909 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00001910 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1911 StrEncoding.length(), false,StrType,
1912 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00001913 ReplaceStmt(Exp, Replacement);
Mike Stump11289f42009-09-09 15:08:12 +00001914
Chris Lattner4431a1b2007-11-30 22:53:43 +00001915 // Replace this subexpr in the parent.
Steve Naroff22216db2008-12-04 23:50:32 +00001916 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattner69534692007-10-24 16:57:36 +00001917 return Replacement;
Chris Lattnera7c19fe2007-10-16 22:36:42 +00001918}
1919
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001920Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff2654e182008-12-22 22:16:07 +00001921 if (!SelGetUidFunctionDecl)
1922 SynthSelGetUidFunctionDecl();
Steve Naroffe4f9b232007-11-05 14:50:49 +00001923 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1924 // Create a call to sel_registerName("selName").
1925 llvm::SmallVector<Expr*, 8> SelExprs;
1926 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00001927 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00001928 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00001929 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00001930 false, argType, SourceLocation()));
Steve Naroffe4f9b232007-11-05 14:50:49 +00001931 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1932 &SelExprs[0], SelExprs.size());
Chris Lattner2e0d2602008-01-31 19:37:57 +00001933 ReplaceStmt(Exp, SelExp);
Steve Naroff22216db2008-12-04 23:50:32 +00001934 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffe4f9b232007-11-05 14:50:49 +00001935 return SelExp;
1936}
1937
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001938CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff574440f2007-10-24 22:48:43 +00001939 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001940 // Get the type, we will need to reference it in a couple spots.
Steve Naroff574440f2007-10-24 22:48:43 +00001941 QualType msgSendType = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001942
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001943 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek5a201952009-02-07 01:47:29 +00001944 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001945
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001946 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattner3c799d72007-10-24 17:06:59 +00001947 QualType pToFunc = Context->getPointerType(msgSendType);
Mike Stump11289f42009-09-09 15:08:12 +00001948 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc,
Anders Carlssona2615922009-07-31 00:48:10 +00001949 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00001950 DRE,
Douglas Gregora11693b2008-11-12 17:17:38 +00001951 /*isLvalue=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001952
John McCall9dd450b2009-09-21 23:43:11 +00001953 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00001954
Ted Kremenekd7b4f402009-02-09 20:51:47 +00001955 return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1956 SourceLocation());
Steve Naroff574440f2007-10-24 22:48:43 +00001957}
1958
Steve Naroff50d42052007-11-01 13:24:47 +00001959static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1960 const char *&startRef, const char *&endRef) {
1961 while (startBuf < endBuf) {
1962 if (*startBuf == '<')
1963 startRef = startBuf; // mark the start.
1964 if (*startBuf == '>') {
Steve Naroff1b232132007-11-09 12:50:28 +00001965 if (startRef && *startRef == '<') {
1966 endRef = startBuf; // mark the end.
1967 return true;
1968 }
1969 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00001970 }
1971 startBuf++;
1972 }
1973 return false;
1974}
1975
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001976static void scanToNextArgument(const char *&argRef) {
1977 int angle = 0;
1978 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1979 if (*argRef == '<')
1980 angle++;
1981 else if (*argRef == '>')
1982 angle--;
1983 argRef++;
1984 }
1985 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1986}
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00001987
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001988bool RewriteObjC::needToScanForQualifiers(QualType T) {
Steve Naroffc277ad12009-07-18 15:33:26 +00001989 return T->isObjCQualifiedIdType() || T->isObjCQualifiedInterfaceType();
Steve Naroff50d42052007-11-01 13:24:47 +00001990}
1991
Steve Naroff873bd842008-07-29 18:15:38 +00001992void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1993 QualType Type = E->getType();
1994 if (needToScanForQualifiers(Type)) {
Steve Naroffdbfc6932008-11-19 21:15:47 +00001995 SourceLocation Loc, EndLoc;
Mike Stump11289f42009-09-09 15:08:12 +00001996
Steve Naroffdbfc6932008-11-19 21:15:47 +00001997 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1998 Loc = ECE->getLParenLoc();
1999 EndLoc = ECE->getRParenLoc();
2000 } else {
2001 Loc = E->getLocStart();
2002 EndLoc = E->getLocEnd();
2003 }
2004 // This will defend against trying to rewrite synthesized expressions.
2005 if (Loc.isInvalid() || EndLoc.isInvalid())
2006 return;
2007
Steve Naroff873bd842008-07-29 18:15:38 +00002008 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffdbfc6932008-11-19 21:15:47 +00002009 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff873bd842008-07-29 18:15:38 +00002010 const char *startRef = 0, *endRef = 0;
2011 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2012 // Get the locations of the startRef, endRef.
2013 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2014 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2015 // Comment out the protocol references.
2016 InsertText(LessLoc, "/*", 2);
2017 InsertText(GreaterLoc, "*/", 2);
2018 }
2019 }
2020}
2021
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002022void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002023 SourceLocation Loc;
2024 QualType Type;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002025 const FunctionProtoType *proto = 0;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002026 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2027 Loc = VD->getLocation();
2028 Type = VD->getType();
2029 }
2030 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2031 Loc = FD->getLocation();
2032 // Check for ObjC 'id' and class types that have been adorned with protocol
2033 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall9dd450b2009-09-21 23:43:11 +00002034 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002035 assert(funcType && "missing function type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002036 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002037 if (!proto)
2038 return;
2039 Type = proto->getResultType();
2040 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00002041 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2042 Loc = FD->getLocation();
2043 Type = FD->getType();
2044 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002045 else
2046 return;
Mike Stump11289f42009-09-09 15:08:12 +00002047
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002048 if (needToScanForQualifiers(Type)) {
Steve Naroff50d42052007-11-01 13:24:47 +00002049 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002050
Steve Naroff50d42052007-11-01 13:24:47 +00002051 const char *endBuf = SM->getCharacterData(Loc);
2052 const char *startBuf = endBuf;
Steve Naroff930e0992008-05-31 05:02:17 +00002053 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroff50d42052007-11-01 13:24:47 +00002054 startBuf--; // scan backward (from the decl location) for return type.
2055 const char *startRef = 0, *endRef = 0;
2056 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2057 // Get the locations of the startRef, endRef.
2058 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2059 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2060 // Comment out the protocol references.
Chris Lattner1780a852008-01-31 19:42:41 +00002061 InsertText(LessLoc, "/*", 2);
2062 InsertText(GreaterLoc, "*/", 2);
Steve Naroff37e011c2007-10-31 04:38:33 +00002063 }
2064 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002065 if (!proto)
2066 return; // most likely, was a variable
Steve Naroff50d42052007-11-01 13:24:47 +00002067 // Now check arguments.
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002068 const char *startBuf = SM->getCharacterData(Loc);
2069 const char *startFuncBuf = startBuf;
Steve Naroff50d42052007-11-01 13:24:47 +00002070 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2071 if (needToScanForQualifiers(proto->getArgType(i))) {
2072 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002073
Steve Naroff50d42052007-11-01 13:24:47 +00002074 const char *endBuf = startBuf;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002075 // scan forward (from the decl location) for argument types.
2076 scanToNextArgument(endBuf);
Steve Naroff50d42052007-11-01 13:24:47 +00002077 const char *startRef = 0, *endRef = 0;
2078 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2079 // Get the locations of the startRef, endRef.
Mike Stump11289f42009-09-09 15:08:12 +00002080 SourceLocation LessLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002081 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump11289f42009-09-09 15:08:12 +00002082 SourceLocation GreaterLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002083 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002084 // Comment out the protocol references.
Chris Lattner1780a852008-01-31 19:42:41 +00002085 InsertText(LessLoc, "/*", 2);
2086 InsertText(GreaterLoc, "*/", 2);
Steve Naroff50d42052007-11-01 13:24:47 +00002087 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002088 startBuf = ++endBuf;
2089 }
2090 else {
Steve Naroffc884aa82008-08-06 15:58:23 +00002091 // If the function name is derived from a macro expansion, then the
2092 // argument buffer will not follow the name. Need to speak with Chris.
2093 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002094 startBuf++; // scan forward (from the decl location) for argument types.
2095 startBuf++;
2096 }
Steve Naroff50d42052007-11-01 13:24:47 +00002097 }
Steve Naroff37e011c2007-10-31 04:38:33 +00002098}
2099
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002100// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002101void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002102 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2103 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002104 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002105 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002106 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002107 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002108 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002109 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002110 SelGetUidIdent, getFuncType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002111 FunctionDecl::Extern, false);
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002112}
2113
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002114void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002115 // declared in <objc/objc.h>
Douglas Gregor1e21c192009-01-09 01:47:02 +00002116 if (FD->getIdentifier() &&
2117 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002118 SelGetUidFunctionDecl = FD;
Steve Naroff37e011c2007-10-31 04:38:33 +00002119 return;
2120 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002121 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002122}
2123
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002124void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2125 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2126 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2127 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2128 if (!proto)
2129 return;
2130 QualType Type = proto->getResultType();
2131 std::string FdStr = Type.getAsString();
2132 FdStr += " ";
2133 FdStr += FD->getNameAsCString();
2134 FdStr += "(";
2135 unsigned numArgs = proto->getNumArgs();
2136 for (unsigned i = 0; i < numArgs; i++) {
2137 QualType ArgType = proto->getArgType(i);
2138 FdStr += ArgType.getAsString();
2139
2140 if (i+1 < numArgs)
2141 FdStr += ", ";
2142 }
2143 FdStr += ");\n";
2144 InsertText(FunLocStart, FdStr.c_str(), FdStr.size());
2145 CurFunctionDeclToDeclareForBlock = 0;
2146}
2147
Steve Naroff17978c42008-03-11 17:37:02 +00002148// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002149void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroff17978c42008-03-11 17:37:02 +00002150 if (SuperContructorFunctionDecl)
2151 return;
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002152 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroff17978c42008-03-11 17:37:02 +00002153 llvm::SmallVector<QualType, 16> ArgTys;
2154 QualType argT = Context->getObjCIdType();
2155 assert(!argT.isNull() && "Can't find 'id' type");
2156 ArgTys.push_back(argT);
2157 ArgTys.push_back(argT);
2158 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2159 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002160 false, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002161 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002162 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002163 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002164 FunctionDecl::Extern, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002165}
2166
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002167// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002168void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002169 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2170 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002171 QualType argT = Context->getObjCIdType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002172 assert(!argT.isNull() && "Can't find 'id' type");
2173 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002174 argT = Context->getObjCSelType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002175 assert(!argT.isNull() && "Can't find 'SEL' type");
2176 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002177 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002178 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002179 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002180 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002181 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002182 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002183 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002184}
2185
Steve Naroff7fa2f042007-11-15 10:28:18 +00002186// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002187void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002188 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2189 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002190 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002191 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002192 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002193 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2194 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2195 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002196 argT = Context->getObjCSelType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002197 assert(!argT.isNull() && "Can't find 'SEL' type");
2198 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002199 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff7fa2f042007-11-15 10:28:18 +00002200 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002201 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002202 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002203 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002204 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002205 FunctionDecl::Extern, false);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002206}
2207
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002208// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002209void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002210 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2211 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002212 QualType argT = Context->getObjCIdType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002213 assert(!argT.isNull() && "Can't find 'id' type");
2214 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002215 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002216 assert(!argT.isNull() && "Can't find 'SEL' type");
2217 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002218 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002219 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002220 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002221 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002222 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002223 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002224 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002225}
2226
Mike Stump11289f42009-09-09 15:08:12 +00002227// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002228// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002229void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump11289f42009-09-09 15:08:12 +00002230 IdentifierInfo *msgSendIdent =
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002231 &Context->Idents.get("objc_msgSendSuper_stret");
2232 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002233 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002234 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002235 &Context->Idents.get("objc_super"));
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002236 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2237 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2238 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002239 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002240 assert(!argT.isNull() && "Can't find 'SEL' type");
2241 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002242 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002243 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002244 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002245 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002246 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002247 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002248 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002249}
2250
Steve Naroff2e4e3852008-05-08 22:02:18 +00002251// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002252void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002253 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2254 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002255 QualType argT = Context->getObjCIdType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002256 assert(!argT.isNull() && "Can't find 'id' type");
2257 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002258 argT = Context->getObjCSelType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002259 assert(!argT.isNull() && "Can't find 'SEL' type");
2260 ArgTys.push_back(argT);
Steve Naroff2e4e3852008-05-08 22:02:18 +00002261 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002262 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002263 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002264 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002265 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002266 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002267 FunctionDecl::Extern, false);
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002268}
2269
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002270// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002271void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002272 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2273 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002274 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002275 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002276 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002277 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002278 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002279 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002280 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002281 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002282}
2283
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002284// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002285void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002286 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2287 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002288 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002289 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002290 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002291 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002292 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002293 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002294 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002295 FunctionDecl::Extern, false);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002296}
2297
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002298Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffce8e8862008-03-15 00:55:56 +00002299 QualType strType = getConstantStringStructType();
2300
2301 std::string S = "__NSConstantStringImpl_";
Steve Naroffa6141f02008-05-31 03:35:42 +00002302
2303 std::string tmpName = InFileName;
2304 unsigned i;
2305 for (i=0; i < tmpName.length(); i++) {
2306 char c = tmpName.at(i);
2307 // replace any non alphanumeric characters with '_'.
2308 if (!isalpha(c) && (c < '0' || c > '9'))
2309 tmpName[i] = '_';
2310 }
2311 S += tmpName;
2312 S += "_";
Steve Naroffce8e8862008-03-15 00:55:56 +00002313 S += utostr(NumObjCStringLiterals++);
2314
Steve Naroff00a31762008-03-27 22:29:16 +00002315 Preamble += "static __NSConstantStringImpl " + S;
2316 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2317 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffce8e8862008-03-15 00:55:56 +00002318 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek2d470fc2008-09-13 05:16:45 +00002319 std::string prettyBufS;
2320 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00002321 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2322 PrintingPolicy(LangOpts));
Steve Naroff00a31762008-03-27 22:29:16 +00002323 Preamble += prettyBuf.str();
2324 Preamble += ",";
Steve Naroff94ed6dc2009-12-06 01:48:44 +00002325 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002326
2327 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2328 &Context->Idents.get(S.c_str()), strType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002329 VarDecl::Static);
Ted Kremenek5a201952009-02-07 01:47:29 +00002330 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2331 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002332 Context->getPointerType(DRE->getType()),
Steve Naroffce8e8862008-03-15 00:55:56 +00002333 SourceLocation());
Steve Naroff265a6b92007-11-08 14:30:50 +00002334 // cast to NSConstantString *
Mike Stump11289f42009-09-09 15:08:12 +00002335 CastExpr *cast = new (Context) CStyleCastExpr(Exp->getType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002336 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002337 Unop, Exp->getType(),
2338 SourceLocation(),
Anders Carlssona2615922009-07-31 00:48:10 +00002339 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002340 ReplaceStmt(Exp, cast);
Steve Naroff22216db2008-12-04 23:50:32 +00002341 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff265a6b92007-11-08 14:30:50 +00002342 return cast;
Steve Naroffa397efd2007-11-03 11:27:19 +00002343}
2344
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002345ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002346 // check if we are sending a message to 'super'
Douglas Gregorffca3a22009-01-09 17:18:27 +00002347 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002348
Douglas Gregor8ea1f532008-11-04 14:56:14 +00002349 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
Mike Stump11289f42009-09-09 15:08:12 +00002350 const ObjCObjectPointerType *OPT =
John McCall9dd450b2009-09-21 23:43:11 +00002351 Super->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00002352 assert(OPT);
2353 const ObjCInterfaceType *IT = OPT->getInterfaceType();
Chris Lattnera9b3cae2008-06-21 18:04:54 +00002354 return IT->getDecl();
2355 }
2356 return 0;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002357}
2358
2359// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002360QualType RewriteObjC::getSuperStructType() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002361 if (!SuperStructDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002362 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002363 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002364 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002365 QualType FieldTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002366
Steve Naroff7fa2f042007-11-15 10:28:18 +00002367 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002368 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002369 // struct objc_class *super;
Mike Stump11289f42009-09-09 15:08:12 +00002370 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor91f84212008-12-11 16:49:14 +00002371
Steve Naroff7fa2f042007-11-15 10:28:18 +00002372 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002373 for (unsigned i = 0; i < 2; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002374 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2375 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002376 FieldTypes[i], 0,
2377 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002378 /*Mutable=*/false));
Douglas Gregor91f84212008-12-11 16:49:14 +00002379 }
Mike Stump11289f42009-09-09 15:08:12 +00002380
Douglas Gregor91f84212008-12-11 16:49:14 +00002381 SuperStructDecl->completeDefinition(*Context);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002382 }
2383 return Context->getTagDeclType(SuperStructDecl);
2384}
2385
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002386QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffce8e8862008-03-15 00:55:56 +00002387 if (!ConstantStringDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002388 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002389 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002390 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffce8e8862008-03-15 00:55:56 +00002391 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002392
Steve Naroffce8e8862008-03-15 00:55:56 +00002393 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002394 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffce8e8862008-03-15 00:55:56 +00002395 // int flags;
Mike Stump11289f42009-09-09 15:08:12 +00002396 FieldTypes[1] = Context->IntTy;
Steve Naroffce8e8862008-03-15 00:55:56 +00002397 // char *str;
Mike Stump11289f42009-09-09 15:08:12 +00002398 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffce8e8862008-03-15 00:55:56 +00002399 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002400 FieldTypes[3] = Context->LongTy;
Douglas Gregor91f84212008-12-11 16:49:14 +00002401
Steve Naroffce8e8862008-03-15 00:55:56 +00002402 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002403 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002404 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2405 ConstantStringDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002406 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002407 FieldTypes[i], 0,
Douglas Gregor91f84212008-12-11 16:49:14 +00002408 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002409 /*Mutable=*/true));
Douglas Gregor91f84212008-12-11 16:49:14 +00002410 }
2411
2412 ConstantStringDecl->completeDefinition(*Context);
Steve Naroffce8e8862008-03-15 00:55:56 +00002413 }
2414 return Context->getTagDeclType(ConstantStringDecl);
2415}
2416
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002417Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002418 if (!SelGetUidFunctionDecl)
2419 SynthSelGetUidFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002420 if (!MsgSendFunctionDecl)
2421 SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002422 if (!MsgSendSuperFunctionDecl)
2423 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002424 if (!MsgSendStretFunctionDecl)
2425 SynthMsgSendStretFunctionDecl();
2426 if (!MsgSendSuperStretFunctionDecl)
2427 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002428 if (!MsgSendFpretFunctionDecl)
2429 SynthMsgSendFpretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002430 if (!GetClassFunctionDecl)
2431 SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002432 if (!GetMetaClassFunctionDecl)
2433 SynthGetMetaClassFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002434
Steve Naroff7fa2f042007-11-15 10:28:18 +00002435 // default to objc_msgSend().
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002436 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2437 // May need to use objc_msgSend_stret() as well.
2438 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroffd9803712009-04-29 16:37:50 +00002439 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2440 QualType resultType = mDecl->getResultType();
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002441 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002442 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002443 else if (resultType->isRealFloatingType())
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002444 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002445 }
Mike Stump11289f42009-09-09 15:08:12 +00002446
Steve Naroff574440f2007-10-24 22:48:43 +00002447 // Synthesize a call to objc_msgSend().
2448 llvm::SmallVector<Expr*, 8> MsgExprs;
2449 IdentifierInfo *clsName = Exp->getClassName();
Mike Stump11289f42009-09-09 15:08:12 +00002450
Steve Naroff574440f2007-10-24 22:48:43 +00002451 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2452 if (clsName) { // class message.
Steve Naroff6c79f972008-07-24 19:44:33 +00002453 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2454 // the 'super' idiom within a class method.
Daniel Dunbar07d07852009-10-18 21:17:35 +00002455 if (clsName->getName() == "super") {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002456 MsgSendFlavor = MsgSendSuperFunctionDecl;
2457 if (MsgSendStretFlavor)
2458 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2459 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002460
2461 ObjCInterfaceDecl *SuperDecl =
Steve Naroff677ab3a2008-10-27 17:20:55 +00002462 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002463
2464 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002465
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002466 // set the receiver to self, the first argument to all methods.
Steve Naroffd9803712009-04-29 16:37:50 +00002467 InitExprs.push_back(
Mike Stump11289f42009-09-09 15:08:12 +00002468 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002469 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002470 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroffd9803712009-04-29 16:37:50 +00002471 Context->getObjCIdType(),
2472 SourceLocation()),
2473 Context->getObjCIdType(),
2474 SourceLocation(), SourceLocation())); // set the 'receiver'.
2475
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002476 llvm::SmallVector<Expr*, 8> ClsExprs;
2477 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002478 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002479 SuperDecl->getIdentifier()->getNameStart(),
2480 SuperDecl->getIdentifier()->getLength(),
2481 false, argType, SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002482 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002483 &ClsExprs[0],
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002484 ClsExprs.size());
2485 // To turn off a warning, type-cast to 'id'
Douglas Gregore200adc2008-10-27 19:41:14 +00002486 InitExprs.push_back( // set 'super class', using objc_getClass().
Mike Stump11289f42009-09-09 15:08:12 +00002487 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002488 CastExpr::CK_Unknown,
Douglas Gregore200adc2008-10-27 19:41:14 +00002489 Cls, Context->getObjCIdType(),
Mike Stump11289f42009-09-09 15:08:12 +00002490 SourceLocation(), SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002491 // struct objc_super
2492 QualType superType = getSuperStructType();
Steve Naroff0b844f02008-03-11 18:14:26 +00002493 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002494
Steve Naroff0b844f02008-03-11 18:14:26 +00002495 if (LangOpts.Microsoft) {
2496 SynthSuperContructorFunctionDecl();
2497 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002498 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff0b844f02008-03-11 18:14:26 +00002499 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002500 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002501 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002502 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002503 // The code for super is a little tricky to prevent collision with
2504 // the structure definition in the header. The rewriter has it's own
2505 // internal definition (__rw_objc_super) that is uses. This is why
2506 // we need the cast below. For example:
2507 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2508 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002509 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002510 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002511 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002512 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
2513 CastExpr::CK_Unknown, SuperRep,
Anders Carlssona2615922009-07-31 00:48:10 +00002514 Context->getPointerType(superType),
Mike Stump11289f42009-09-09 15:08:12 +00002515 SourceLocation(), SourceLocation());
2516 } else {
Steve Naroff0b844f02008-03-11 18:14:26 +00002517 // (struct objc_super) { <exprs from above> }
Mike Stump11289f42009-09-09 15:08:12 +00002518 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2519 &InitExprs[0], InitExprs.size(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002520 SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00002521 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE,
Chris Lattner07d754a2008-10-26 23:43:26 +00002522 false);
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002523 // struct objc_super *
Ted Kremenek5a201952009-02-07 01:47:29 +00002524 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002525 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002526 SourceLocation());
Steve Naroff0b844f02008-03-11 18:14:26 +00002527 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002528 MsgExprs.push_back(SuperRep);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002529 } else {
2530 llvm::SmallVector<Expr*, 8> ClsExprs;
2531 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002532 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002533 clsName->getNameStart(),
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002534 clsName->getLength(),
2535 false, argType,
2536 SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002537 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002538 &ClsExprs[0],
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002539 ClsExprs.size());
2540 MsgExprs.push_back(Cls);
2541 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002542 } else { // instance message.
2543 Expr *recExpr = Exp->getReceiver();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002544
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002545 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002546 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002547 if (MsgSendStretFlavor)
2548 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002549 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002550
Steve Naroff7fa2f042007-11-15 10:28:18 +00002551 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002552
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002553 InitExprs.push_back(
Mike Stump11289f42009-09-09 15:08:12 +00002554 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002555 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002556 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff97adf602008-07-16 22:35:27 +00002557 Context->getObjCIdType(),
Douglas Gregore200adc2008-10-27 19:41:14 +00002558 SourceLocation()),
2559 Context->getObjCIdType(),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002560 SourceLocation(), SourceLocation())); // set the 'receiver'.
Mike Stump11289f42009-09-09 15:08:12 +00002561
Steve Naroff7fa2f042007-11-15 10:28:18 +00002562 llvm::SmallVector<Expr*, 8> ClsExprs;
2563 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002564 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002565 SuperDecl->getIdentifier()->getNameStart(),
2566 SuperDecl->getIdentifier()->getLength(),
2567 false, argType, SourceLocation()));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002568 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002569 &ClsExprs[0],
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002570 ClsExprs.size());
Fariborz Jahaniand5db92b2007-12-05 17:29:46 +00002571 // To turn off a warning, type-cast to 'id'
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002572 InitExprs.push_back(
Douglas Gregore200adc2008-10-27 19:41:14 +00002573 // set 'super class', using objc_getClass().
Mike Stump11289f42009-09-09 15:08:12 +00002574 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002575 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002576 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002577 // struct objc_super
2578 QualType superType = getSuperStructType();
Steve Naroff17978c42008-03-11 17:37:02 +00002579 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002580
Steve Naroff17978c42008-03-11 17:37:02 +00002581 if (LangOpts.Microsoft) {
2582 SynthSuperContructorFunctionDecl();
2583 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002584 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff17978c42008-03-11 17:37:02 +00002585 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002586 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002587 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002588 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002589 // The code for super is a little tricky to prevent collision with
2590 // the structure definition in the header. The rewriter has it's own
2591 // internal definition (__rw_objc_super) that is uses. This is why
2592 // we need the cast below. For example:
2593 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2594 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002595 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002596 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002597 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002598 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Anders Carlssona2615922009-07-31 00:48:10 +00002599 CastExpr::CK_Unknown,
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002600 SuperRep, Context->getPointerType(superType),
Mike Stump11289f42009-09-09 15:08:12 +00002601 SourceLocation(), SourceLocation());
Steve Naroff17978c42008-03-11 17:37:02 +00002602 } else {
2603 // (struct objc_super) { <exprs from above> }
Mike Stump11289f42009-09-09 15:08:12 +00002604 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2605 &InitExprs[0], InitExprs.size(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002606 SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00002607 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002608 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002609 MsgExprs.push_back(SuperRep);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002610 } else {
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002611 // Remove all type-casts because it may contain objc-style types; e.g.
2612 // Foo<Proto> *.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002613 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002614 recExpr = CE->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002615 recExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002616 CastExpr::CK_Unknown, recExpr,
Mike Stump11289f42009-09-09 15:08:12 +00002617 Context->getObjCIdType(),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002618 SourceLocation(), SourceLocation());
Steve Naroff7fa2f042007-11-15 10:28:18 +00002619 MsgExprs.push_back(recExpr);
2620 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002621 }
Steve Naroffa397efd2007-11-03 11:27:19 +00002622 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff574440f2007-10-24 22:48:43 +00002623 llvm::SmallVector<Expr*, 8> SelExprs;
2624 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002625 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002626 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002627 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002628 false, argType, SourceLocation()));
Steve Naroff574440f2007-10-24 22:48:43 +00002629 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2630 &SelExprs[0], SelExprs.size());
2631 MsgExprs.push_back(SelExp);
Mike Stump11289f42009-09-09 15:08:12 +00002632
Steve Naroff574440f2007-10-24 22:48:43 +00002633 // Now push any user supplied arguments.
2634 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroffe7f18192007-11-14 23:54:14 +00002635 Expr *userExpr = Exp->getArg(i);
Steve Narofff60782b2007-11-15 02:58:25 +00002636 // Make all implicit casts explicit...ICE comes in handy:-)
2637 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2638 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregore200adc2008-10-27 19:41:14 +00002639 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002640 ? Context->getObjCIdType()
Douglas Gregore200adc2008-10-27 19:41:14 +00002641 : ICE->getType();
Anders Carlssona2615922009-07-31 00:48:10 +00002642 userExpr = new (Context) CStyleCastExpr(type, CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002643 userExpr, type, SourceLocation(),
Anders Carlssona2615922009-07-31 00:48:10 +00002644 SourceLocation());
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002645 }
2646 // Make id<P...> cast into an 'id' cast.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002647 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002648 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregorf19b2312008-10-28 15:36:24 +00002649 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002650 userExpr = CE->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002651 userExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002652 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002653 userExpr, Context->getObjCIdType(),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002654 SourceLocation(), SourceLocation());
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002655 }
Mike Stump11289f42009-09-09 15:08:12 +00002656 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002657 MsgExprs.push_back(userExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002658 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2659 // out the argument in the original expression (since we aren't deleting
2660 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2661 //Exp->setArg(i, 0);
Steve Naroff574440f2007-10-24 22:48:43 +00002662 }
Steve Narofff36987c2007-11-04 22:37:50 +00002663 // Generate the funky cast.
2664 CastExpr *cast;
2665 llvm::SmallVector<QualType, 8> ArgTypes;
2666 QualType returnType;
Mike Stump11289f42009-09-09 15:08:12 +00002667
Steve Narofff36987c2007-11-04 22:37:50 +00002668 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff44864e42007-11-15 10:43:57 +00002669 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2670 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2671 else
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002672 ArgTypes.push_back(Context->getObjCIdType());
2673 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattnera4997152009-02-20 18:43:26 +00002674 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Narofff36987c2007-11-04 22:37:50 +00002675 // Push any user argument types.
Chris Lattnera4997152009-02-20 18:43:26 +00002676 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2677 E = OMD->param_end(); PI != E; ++PI) {
2678 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump11289f42009-09-09 15:08:12 +00002679 ? Context->getObjCIdType()
Chris Lattnera4997152009-02-20 18:43:26 +00002680 : (*PI)->getType();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002681 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00002682 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002683 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002684 t = Context->getPointerType(BPT->getPointeeType());
2685 }
Steve Naroff98eb8d12007-11-05 14:36:37 +00002686 ArgTypes.push_back(t);
2687 }
Chris Lattnera4997152009-02-20 18:43:26 +00002688 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2689 ? Context->getObjCIdType() : OMD->getResultType();
Steve Narofff36987c2007-11-04 22:37:50 +00002690 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002691 returnType = Context->getObjCIdType();
Steve Narofff36987c2007-11-04 22:37:50 +00002692 }
2693 // Get the type, we will need to reference it in a couple spots.
Steve Naroff7fa2f042007-11-15 10:28:18 +00002694 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002695
Steve Narofff36987c2007-11-04 22:37:50 +00002696 // Create a reference to the objc_msgSend() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002697 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002698 SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002699
Mike Stump11289f42009-09-09 15:08:12 +00002700 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Narofff36987c2007-11-04 22:37:50 +00002701 // If we don't do this cast, we get the following bizarre warning/note:
2702 // xx.m:13: warning: function called through a non-compatible type
2703 // xx.m:13: note: if this code is reached, the program will abort
Mike Stump11289f42009-09-09 15:08:12 +00002704 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy),
2705 CastExpr::CK_Unknown, DRE,
Douglas Gregore200adc2008-10-27 19:41:14 +00002706 Context->getPointerType(Context->VoidTy),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002707 SourceLocation(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002708
Steve Narofff36987c2007-11-04 22:37:50 +00002709 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002710 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002711 &ArgTypes[0], ArgTypes.size(),
Steve Naroff327f0f42008-03-18 02:02:04 +00002712 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002713 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Narofff36987c2007-11-04 22:37:50 +00002714 castType = Context->getPointerType(castType);
Mike Stump11289f42009-09-09 15:08:12 +00002715 cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown, cast,
2716 castType, SourceLocation(),
Anders Carlssona2615922009-07-31 00:48:10 +00002717 SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002718
2719 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002720 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002721
John McCall9dd450b2009-09-21 23:43:11 +00002722 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002723 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002724 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002725 FT->getResultType(), SourceLocation());
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002726 Stmt *ReplacingStmt = CE;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002727 if (MsgSendStretFlavor) {
2728 // We have the method which returns a struct/union. Must also generate
2729 // call to objc_msgSend_stret and hang both varieties on a conditional
2730 // expression which dictate which one to envoke depending on size of
2731 // method's return type.
Mike Stump11289f42009-09-09 15:08:12 +00002732
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002733 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002734 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002735 SourceLocation());
2736 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Mike Stump11289f42009-09-09 15:08:12 +00002737 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy),
2738 CastExpr::CK_Unknown, STDRE,
Douglas Gregore200adc2008-10-27 19:41:14 +00002739 Context->getPointerType(Context->VoidTy),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002740 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002741 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002742 castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002743 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002744 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002745 castType = Context->getPointerType(castType);
Anders Carlssona2615922009-07-31 00:48:10 +00002746 cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown,
2747 cast, castType, SourceLocation(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002748
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002749 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002750 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002751
John McCall9dd450b2009-09-21 23:43:11 +00002752 FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002753 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002754 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002755 FT->getResultType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002756
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002757 // Build sizeof(returnType)
Mike Stump11289f42009-09-09 15:08:12 +00002758 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCallbcd03502009-12-07 02:54:59 +00002759 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl6f282892008-11-11 17:56:53 +00002760 Context->getSizeType(),
2761 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002762 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2763 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2764 // For X86 it is more complicated and some kind of target specific routine
2765 // is needed to decide what to do.
Mike Stump11289f42009-09-09 15:08:12 +00002766 unsigned IntSize =
Chris Lattner37e05872008-03-05 18:54:05 +00002767 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Mike Stump11289f42009-09-09 15:08:12 +00002768 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002769 Context->IntTy,
2770 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002771 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
2772 BinaryOperator::LE,
2773 Context->IntTy,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002774 SourceLocation());
2775 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump11289f42009-09-09 15:08:12 +00002776 ConditionalOperator *CondExpr =
Douglas Gregor7e112b02009-08-26 14:37:04 +00002777 new (Context) ConditionalOperator(lessThanExpr,
2778 SourceLocation(), CE,
2779 SourceLocation(), STCE, returnType);
Ted Kremenek5a201952009-02-07 01:47:29 +00002780 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002781 }
Mike Stump11289f42009-09-09 15:08:12 +00002782 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002783 return ReplacingStmt;
2784}
2785
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002786Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002787 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Mike Stump11289f42009-09-09 15:08:12 +00002788
Steve Naroff574440f2007-10-24 22:48:43 +00002789 // Now do the actual rewrite.
Chris Lattner2e0d2602008-01-31 19:37:57 +00002790 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00002791
2792 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002793 return ReplacingStmt;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002794}
2795
Steve Naroffd9803712009-04-29 16:37:50 +00002796// typedef struct objc_object Protocol;
2797QualType RewriteObjC::getProtocolType() {
2798 if (!ProtocolTypeDecl) {
John McCallbcd03502009-12-07 02:54:59 +00002799 TypeSourceInfo *TInfo
2800 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroffd9803712009-04-29 16:37:50 +00002801 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002802 SourceLocation(),
Steve Naroffd9803712009-04-29 16:37:50 +00002803 &Context->Idents.get("Protocol"),
John McCallbcd03502009-12-07 02:54:59 +00002804 TInfo);
Steve Naroffd9803712009-04-29 16:37:50 +00002805 }
2806 return Context->getTypeDeclType(ProtocolTypeDecl);
2807}
2808
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00002809/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroffd9803712009-04-29 16:37:50 +00002810/// a synthesized/forward data reference (to the protocol's metadata).
2811/// The forward references (and metadata) are generated in
2812/// RewriteObjC::HandleTranslationUnit().
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002813Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroffd9803712009-04-29 16:37:50 +00002814 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
2815 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump11289f42009-09-09 15:08:12 +00002816 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregored6c7442009-11-23 11:41:28 +00002817 ID, getProtocolType(), 0, VarDecl::Extern);
Steve Naroffd9803712009-04-29 16:37:50 +00002818 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
2819 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
2820 Context->getPointerType(DRE->getType()),
2821 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002822 CastExpr *castExpr = new (Context) CStyleCastExpr(DerefExpr->getType(),
2823 CastExpr::CK_Unknown,
2824 DerefExpr, DerefExpr->getType(),
Steve Naroffd9803712009-04-29 16:37:50 +00002825 SourceLocation(), SourceLocation());
2826 ReplaceStmt(Exp, castExpr);
2827 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump11289f42009-09-09 15:08:12 +00002828 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00002829 return castExpr;
Mike Stump11289f42009-09-09 15:08:12 +00002830
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00002831}
2832
Mike Stump11289f42009-09-09 15:08:12 +00002833bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002834 const char *endBuf) {
2835 while (startBuf < endBuf) {
2836 if (*startBuf == '#') {
2837 // Skip whitespace.
2838 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2839 ;
2840 if (!strncmp(startBuf, "if", strlen("if")) ||
2841 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2842 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2843 !strncmp(startBuf, "define", strlen("define")) ||
2844 !strncmp(startBuf, "undef", strlen("undef")) ||
2845 !strncmp(startBuf, "else", strlen("else")) ||
2846 !strncmp(startBuf, "elif", strlen("elif")) ||
2847 !strncmp(startBuf, "endif", strlen("endif")) ||
2848 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2849 !strncmp(startBuf, "include", strlen("include")) ||
2850 !strncmp(startBuf, "import", strlen("import")) ||
2851 !strncmp(startBuf, "include_next", strlen("include_next")))
2852 return true;
2853 }
2854 startBuf++;
2855 }
2856 return false;
2857}
2858
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002859/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002860/// an objective-c class with ivars.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002861void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002862 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002863 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Mike Stump11289f42009-09-09 15:08:12 +00002864 assert(CDecl->getNameAsCString() &&
Douglas Gregor77324f32008-11-17 14:58:09 +00002865 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00002866 // Do not synthesize more than once.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002867 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00002868 return;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002869 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattner8d1c04f2008-03-16 21:08:55 +00002870 int NumIvars = CDecl->ivar_size();
Steve Naroffdde78982007-11-14 19:25:57 +00002871 SourceLocation LocStart = CDecl->getLocStart();
2872 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00002873
Steve Naroffdde78982007-11-14 19:25:57 +00002874 const char *startBuf = SM->getCharacterData(LocStart);
2875 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00002876
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002877 // If no ivars and no root or if its root, directly or indirectly,
2878 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattner8d1c04f2008-03-16 21:08:55 +00002879 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2880 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner184e65d2009-04-14 23:22:57 +00002881 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Chris Lattner9cc55f52008-01-31 19:51:04 +00002882 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002883 return;
2884 }
Mike Stump11289f42009-09-09 15:08:12 +00002885
2886 // FIXME: This has potential of causing problem. If
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002887 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002888 Result += "\nstruct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002889 Result += CDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00002890 if (LangOpts.Microsoft)
2891 Result += "_IMPL";
Steve Naroffdc5b6b22008-03-12 00:25:36 +00002892
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002893 if (NumIvars > 0) {
Steve Naroffdde78982007-11-14 19:25:57 +00002894 const char *cursor = strchr(startBuf, '{');
Mike Stump11289f42009-09-09 15:08:12 +00002895 assert((cursor && endBuf)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002896 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002897 // If the buffer contains preprocessor directives, we do more fine-grained
2898 // rewrites. This is intended to fix code that looks like (which occurs in
2899 // NSURL.h, for example):
2900 //
2901 // #ifdef XYZ
2902 // @interface Foo : NSObject
2903 // #else
2904 // @interface FooBar : NSObject
2905 // #endif
2906 // {
2907 // int i;
2908 // }
2909 // @end
2910 //
2911 // This clause is segregated to avoid breaking the common case.
2912 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump11289f42009-09-09 15:08:12 +00002913 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002914 CDecl->getClassLoc();
2915 const char *endHeader = SM->getCharacterData(L);
Chris Lattner184e65d2009-04-14 23:22:57 +00002916 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002917
Chris Lattnerf5b77512009-02-20 18:18:36 +00002918 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002919 // advance to the end of the referenced protocols.
2920 while (endHeader < cursor && *endHeader != '>') endHeader++;
2921 endHeader++;
2922 }
2923 // rewrite the original header
2924 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2925 } else {
2926 // rewrite the original header *without* disturbing the '{'
Steve Naroffb0e33902009-12-04 21:36:32 +00002927 ReplaceText(LocStart, cursor-startBuf, Result.c_str(), Result.size());
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002928 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002929 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroffdde78982007-11-14 19:25:57 +00002930 Result = "\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002931 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00002932 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002933 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00002934 Result += "_IVARS;\n";
Mike Stump11289f42009-09-09 15:08:12 +00002935
Steve Naroffdde78982007-11-14 19:25:57 +00002936 // insert the super class structure definition.
Chris Lattner1780a852008-01-31 19:42:41 +00002937 SourceLocation OnePastCurly =
2938 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2939 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Naroffdde78982007-11-14 19:25:57 +00002940 }
2941 cursor++; // past '{'
Mike Stump11289f42009-09-09 15:08:12 +00002942
Steve Naroffdde78982007-11-14 19:25:57 +00002943 // Now comment out any visibility specifiers.
2944 while (cursor < endBuf) {
2945 if (*cursor == '@') {
2946 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner174a8252007-11-14 22:57:51 +00002947 // Skip whitespace.
2948 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2949 /*scan*/;
2950
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002951 // FIXME: presence of @public, etc. inside comment results in
2952 // this transformation as well, which is still correct c-code.
Steve Naroffdde78982007-11-14 19:25:57 +00002953 if (!strncmp(cursor, "public", strlen("public")) ||
2954 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffaf91b9a2008-04-04 22:34:24 +00002955 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002956 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattner1780a852008-01-31 19:42:41 +00002957 InsertText(atLoc, "// ", 3);
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002958 }
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002959 // FIXME: If there are cases where '<' is used in ivar declaration part
2960 // of user code, then scan the ivar list and use needToScanForQualifiers
2961 // for type checking.
2962 else if (*cursor == '<') {
2963 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner1780a852008-01-31 19:42:41 +00002964 InsertText(atLoc, "/* ", 3);
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002965 cursor = strchr(cursor, '>');
2966 cursor++;
2967 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner1780a852008-01-31 19:42:41 +00002968 InsertText(atLoc, " */", 3);
Steve Naroff295570a2008-10-30 12:09:33 +00002969 } else if (*cursor == '^') { // rewrite block specifier.
2970 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2971 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002972 }
Steve Naroffdde78982007-11-14 19:25:57 +00002973 cursor++;
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002974 }
Steve Naroffdde78982007-11-14 19:25:57 +00002975 // Don't forget to add a ';'!!
Chris Lattner1780a852008-01-31 19:42:41 +00002976 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Naroffdde78982007-11-14 19:25:57 +00002977 } else { // we don't have any instance variables - insert super struct.
Chris Lattner184e65d2009-04-14 23:22:57 +00002978 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroffdde78982007-11-14 19:25:57 +00002979 Result += " {\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002980 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00002981 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002982 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00002983 Result += "_IVARS;\n};\n";
Chris Lattner9cc55f52008-01-31 19:51:04 +00002984 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002985 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002986 // Mark this struct as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002987 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff13e74872008-05-06 18:26:51 +00002988 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002989}
2990
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002991// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002992/// class methods.
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002993template<typename MethodIterator>
2994void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
2995 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +00002996 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002997 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +00002998 const char *ClassName,
2999 std::string &Result) {
Chris Lattner31bc07e2007-12-12 07:46:12 +00003000 if (MethodBegin == MethodEnd) return;
Mike Stump11289f42009-09-09 15:08:12 +00003001
Chris Lattner31bc07e2007-12-12 07:46:12 +00003002 if (!objc_impl_method) {
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003003 /* struct _objc_method {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003004 SEL _cmd;
3005 char *method_types;
3006 void *_imp;
3007 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003008 */
Chris Lattner211f8b82007-10-25 17:07:24 +00003009 Result += "\nstruct _objc_method {\n";
3010 Result += "\tSEL _cmd;\n";
3011 Result += "\tchar *method_types;\n";
3012 Result += "\tvoid *_imp;\n";
3013 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003014
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003015 objc_impl_method = true;
Fariborz Jahanian74a1cfa2007-10-19 00:36:46 +00003016 }
Mike Stump11289f42009-09-09 15:08:12 +00003017
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003018 // Build _objc_method_list for class's methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003019
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003020 /* struct {
3021 struct _objc_method_list *next_method;
3022 int method_count;
3023 struct _objc_method method_list[];
3024 }
3025 */
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003026 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003027 Result += "\nstatic struct {\n";
3028 Result += "\tstruct _objc_method_list *next_method;\n";
3029 Result += "\tint method_count;\n";
3030 Result += "\tstruct _objc_method method_list[";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003031 Result += utostr(NumMethods);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003032 Result += "];\n} _OBJC_";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003033 Result += prefix;
3034 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3035 Result += "_METHODS_";
3036 Result += ClassName;
Steve Naroffb327e492008-03-12 17:18:30 +00003037 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003038 Result += IsInstanceMethod ? "inst" : "cls";
3039 Result += "_meth\")))= ";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003040 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003041
Chris Lattner31bc07e2007-12-12 07:46:12 +00003042 Result += "\t,{{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003043 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattner31bc07e2007-12-12 07:46:12 +00003044 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003045 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattner31bc07e2007-12-12 07:46:12 +00003046 Result += "\", \"";
3047 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003048 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003049 Result += MethodInternalNames[*MethodBegin];
3050 Result += "}\n";
3051 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3052 Result += "\t ,{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003053 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003054 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003055 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003056 Result += "\", \"";
3057 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003058 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003059 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanian56338352007-11-13 21:02:00 +00003060 Result += "}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003061 }
Chris Lattner31bc07e2007-12-12 07:46:12 +00003062 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003063}
3064
Steve Naroffd9803712009-04-29 16:37:50 +00003065/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner390d39a2008-07-21 21:32:27 +00003066void RewriteObjC::
Steve Naroffd9803712009-04-29 16:37:50 +00003067RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
3068 const char *ClassName, std::string &Result) {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003069 static bool objc_protocol_methods = false;
Steve Naroffd9803712009-04-29 16:37:50 +00003070
3071 // Output struct protocol_methods holder of method selector and type.
3072 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3073 /* struct protocol_methods {
3074 SEL _cmd;
3075 char *method_types;
3076 }
3077 */
3078 Result += "\nstruct _protocol_methods {\n";
3079 Result += "\tstruct objc_selector *_cmd;\n";
3080 Result += "\tchar *method_types;\n";
3081 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003082
Steve Naroffd9803712009-04-29 16:37:50 +00003083 objc_protocol_methods = true;
3084 }
3085 // Do not synthesize the protocol more than once.
3086 if (ObjCSynthesizedProtocols.count(PDecl))
3087 return;
Mike Stump11289f42009-09-09 15:08:12 +00003088
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003089 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3090 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3091 PDecl->instmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003092 /* struct _objc_protocol_method_list {
3093 int protocol_method_count;
3094 struct protocol_methods protocols[];
3095 }
Steve Naroff251084d2008-03-12 01:06:30 +00003096 */
Steve Naroffd9803712009-04-29 16:37:50 +00003097 Result += "\nstatic struct {\n";
3098 Result += "\tint protocol_method_count;\n";
3099 Result += "\tstruct _protocol_methods protocol_methods[";
3100 Result += utostr(NumMethods);
3101 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3102 Result += PDecl->getNameAsString();
3103 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3104 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003105
Steve Naroffd9803712009-04-29 16:37:50 +00003106 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003107 for (ObjCProtocolDecl::instmeth_iterator
3108 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003109 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003110 if (I == PDecl->instmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003111 Result += "\t ,{{(struct objc_selector *)\"";
3112 else
3113 Result += "\t ,{(struct objc_selector *)\"";
3114 Result += (*I)->getSelector().getAsString().c_str();
3115 std::string MethodTypeString;
3116 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3117 Result += "\", \"";
3118 Result += MethodTypeString;
3119 Result += "\"}\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003120 }
Steve Naroffd9803712009-04-29 16:37:50 +00003121 Result += "\t }\n};\n";
3122 }
Mike Stump11289f42009-09-09 15:08:12 +00003123
Steve Naroffd9803712009-04-29 16:37:50 +00003124 // Output class methods declared in this protocol.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003125 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3126 PDecl->classmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003127 if (NumMethods > 0) {
3128 /* struct _objc_protocol_method_list {
3129 int protocol_method_count;
3130 struct protocol_methods protocols[];
3131 }
3132 */
3133 Result += "\nstatic struct {\n";
3134 Result += "\tint protocol_method_count;\n";
3135 Result += "\tstruct _protocol_methods protocol_methods[";
3136 Result += utostr(NumMethods);
3137 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3138 Result += PDecl->getNameAsString();
3139 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3140 "{\n\t";
3141 Result += utostr(NumMethods);
3142 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003143
Steve Naroffd9803712009-04-29 16:37:50 +00003144 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003145 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003146 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003147 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003148 if (I == PDecl->classmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003149 Result += "\t ,{{(struct objc_selector *)\"";
3150 else
3151 Result += "\t ,{(struct objc_selector *)\"";
3152 Result += (*I)->getSelector().getAsString().c_str();
3153 std::string MethodTypeString;
3154 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3155 Result += "\", \"";
3156 Result += MethodTypeString;
3157 Result += "\"}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003158 }
Steve Naroffd9803712009-04-29 16:37:50 +00003159 Result += "\t }\n};\n";
3160 }
3161
3162 // Output:
3163 /* struct _objc_protocol {
3164 // Objective-C 1.0 extensions
3165 struct _objc_protocol_extension *isa;
3166 char *protocol_name;
3167 struct _objc_protocol **protocol_list;
3168 struct _objc_protocol_method_list *instance_methods;
3169 struct _objc_protocol_method_list *class_methods;
Mike Stump11289f42009-09-09 15:08:12 +00003170 };
Steve Naroffd9803712009-04-29 16:37:50 +00003171 */
3172 static bool objc_protocol = false;
3173 if (!objc_protocol) {
3174 Result += "\nstruct _objc_protocol {\n";
3175 Result += "\tstruct _objc_protocol_extension *isa;\n";
3176 Result += "\tchar *protocol_name;\n";
3177 Result += "\tstruct _objc_protocol **protocol_list;\n";
3178 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3179 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003180 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003181
Steve Naroffd9803712009-04-29 16:37:50 +00003182 objc_protocol = true;
Chris Lattner388f6e92008-07-21 21:33:21 +00003183 }
Mike Stump11289f42009-09-09 15:08:12 +00003184
Steve Naroffd9803712009-04-29 16:37:50 +00003185 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3186 Result += PDecl->getNameAsString();
3187 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3188 "{\n\t0, \"";
3189 Result += PDecl->getNameAsString();
3190 Result += "\", 0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003191 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003192 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3193 Result += PDecl->getNameAsString();
3194 Result += ", ";
3195 }
3196 else
3197 Result += "0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003198 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003199 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3200 Result += PDecl->getNameAsString();
3201 Result += "\n";
3202 }
3203 else
3204 Result += "0\n";
3205 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003206
Steve Naroffd9803712009-04-29 16:37:50 +00003207 // Mark this protocol as having been generated.
3208 if (!ObjCSynthesizedProtocols.insert(PDecl))
3209 assert(false && "protocol already synthesized");
3210
3211}
3212
3213void RewriteObjC::
3214RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3215 const char *prefix, const char *ClassName,
3216 std::string &Result) {
3217 if (Protocols.empty()) return;
Mike Stump11289f42009-09-09 15:08:12 +00003218
Steve Naroffd9803712009-04-29 16:37:50 +00003219 for (unsigned i = 0; i != Protocols.size(); i++)
3220 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3221
Chris Lattner388f6e92008-07-21 21:33:21 +00003222 // Output the top lovel protocol meta-data for the class.
3223 /* struct _objc_protocol_list {
3224 struct _objc_protocol_list *next;
3225 int protocol_count;
3226 struct _objc_protocol *class_protocols[];
3227 }
3228 */
3229 Result += "\nstatic struct {\n";
3230 Result += "\tstruct _objc_protocol_list *next;\n";
3231 Result += "\tint protocol_count;\n";
3232 Result += "\tstruct _objc_protocol *class_protocols[";
3233 Result += utostr(Protocols.size());
3234 Result += "];\n} _OBJC_";
3235 Result += prefix;
3236 Result += "_PROTOCOLS_";
3237 Result += ClassName;
3238 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3239 "{\n\t0, ";
3240 Result += utostr(Protocols.size());
3241 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003242
Chris Lattner388f6e92008-07-21 21:33:21 +00003243 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003244 Result += Protocols[0]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003245 Result += " \n";
Mike Stump11289f42009-09-09 15:08:12 +00003246
Chris Lattner388f6e92008-07-21 21:33:21 +00003247 for (unsigned i = 1; i != Protocols.size(); i++) {
3248 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003249 Result += Protocols[i]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003250 Result += "\n";
3251 }
3252 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003253}
3254
Steve Naroffd9803712009-04-29 16:37:50 +00003255
Mike Stump11289f42009-09-09 15:08:12 +00003256/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003257/// implementation.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003258void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003259 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003260 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003261 // Find category declaration for this implementation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003262 ObjCCategoryDecl *CDecl;
Mike Stump11289f42009-09-09 15:08:12 +00003263 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003264 CDecl = CDecl->getNextClassCategory())
3265 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3266 break;
Mike Stump11289f42009-09-09 15:08:12 +00003267
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003268 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003269 FullCategoryName += '_';
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003270 FullCategoryName += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003271
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003272 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003273 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003274 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003275
3276 // If any of our property implementations have associated getters or
3277 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003278 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3279 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003280 Prop != PropEnd; ++Prop) {
3281 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3282 continue;
3283 if (!(*Prop)->getPropertyIvarDecl())
3284 continue;
3285 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3286 if (!PD)
3287 continue;
3288 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3289 InstanceMethods.push_back(Getter);
3290 if (PD->isReadOnly())
3291 continue;
3292 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3293 InstanceMethods.push_back(Setter);
3294 }
3295 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003296 true, "CATEGORY_", FullCategoryName.c_str(),
3297 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003298
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003299 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003300 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003301 false, "CATEGORY_", FullCategoryName.c_str(),
3302 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003303
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003304 // Protocols referenced in class declaration?
Fariborz Jahanian989e0392007-11-13 22:09:49 +00003305 // Null CDecl is case of a category implementation with no category interface
3306 if (CDecl)
Steve Naroffd9803712009-04-29 16:37:50 +00003307 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3308 FullCategoryName.c_str(), Result);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003309 /* struct _objc_category {
3310 char *category_name;
3311 char *class_name;
3312 struct _objc_method_list *instance_methods;
3313 struct _objc_method_list *class_methods;
3314 struct _objc_protocol_list *protocols;
3315 // Objective-C 1.0 extensions
3316 uint32_t size; // sizeof (struct _objc_category)
Mike Stump11289f42009-09-09 15:08:12 +00003317 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003318 // @property decl.
Mike Stump11289f42009-09-09 15:08:12 +00003319 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003320 */
Mike Stump11289f42009-09-09 15:08:12 +00003321
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003322 static bool objc_category = false;
3323 if (!objc_category) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003324 Result += "\nstruct _objc_category {\n";
3325 Result += "\tchar *category_name;\n";
3326 Result += "\tchar *class_name;\n";
3327 Result += "\tstruct _objc_method_list *instance_methods;\n";
3328 Result += "\tstruct _objc_method_list *class_methods;\n";
3329 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003330 Result += "\tunsigned int size;\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003331 Result += "\tstruct _objc_property_list *instance_properties;\n";
3332 Result += "};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003333 objc_category = true;
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003334 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003335 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3336 Result += FullCategoryName;
Steve Naroffb327e492008-03-12 17:18:30 +00003337 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003338 Result += IDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003339 Result += "\"\n\t, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003340 Result += ClassDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003341 Result += "\"\n";
Mike Stump11289f42009-09-09 15:08:12 +00003342
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003343 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003344 Result += "\t, (struct _objc_method_list *)"
3345 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3346 Result += FullCategoryName;
3347 Result += "\n";
3348 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003349 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003350 Result += "\t, 0\n";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003351 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003352 Result += "\t, (struct _objc_method_list *)"
3353 "&_OBJC_CATEGORY_CLASS_METHODS_";
3354 Result += FullCategoryName;
3355 Result += "\n";
3356 }
3357 else
3358 Result += "\t, 0\n";
Mike Stump11289f42009-09-09 15:08:12 +00003359
Chris Lattnerf5b77512009-02-20 18:18:36 +00003360 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump11289f42009-09-09 15:08:12 +00003361 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003362 Result += FullCategoryName;
3363 Result += "\n";
3364 }
3365 else
3366 Result += "\t, 0\n";
3367 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003368}
3369
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003370/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3371/// ivar offset.
Mike Stump11289f42009-09-09 15:08:12 +00003372void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
3373 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003374 std::string &Result) {
Steve Naroffde7d0f62008-07-16 18:22:22 +00003375 if (ivar->isBitField()) {
3376 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3377 // place all bitfields at offset 0.
3378 Result += "0";
3379 } else {
3380 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003381 Result += IDecl->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003382 if (LangOpts.Microsoft)
3383 Result += "_IMPL";
3384 Result += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003385 Result += ivar->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003386 Result += ")";
3387 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003388}
3389
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003390//===----------------------------------------------------------------------===//
3391// Meta Data Emission
3392//===----------------------------------------------------------------------===//
3393
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003394void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003395 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003396 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00003397
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003398 // Explictly declared @interface's are already synthesized.
Steve Naroffaac654a2009-04-20 20:09:33 +00003399 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump11289f42009-09-09 15:08:12 +00003400 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003401 // produce correct synthesis as yet.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003402 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003403 }
Mike Stump11289f42009-09-09 15:08:12 +00003404
Chris Lattner30d23e82007-12-12 07:56:42 +00003405 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003406 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump11289f42009-09-09 15:08:12 +00003407 ? IDecl->ivar_size()
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003408 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003409 if (NumIvars > 0) {
3410 static bool objc_ivar = false;
3411 if (!objc_ivar) {
3412 /* struct _objc_ivar {
3413 char *ivar_name;
3414 char *ivar_type;
3415 int ivar_offset;
Mike Stump11289f42009-09-09 15:08:12 +00003416 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003417 */
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003418 Result += "\nstruct _objc_ivar {\n";
3419 Result += "\tchar *ivar_name;\n";
3420 Result += "\tchar *ivar_type;\n";
3421 Result += "\tint ivar_offset;\n";
3422 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003423
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003424 objc_ivar = true;
3425 }
3426
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003427 /* struct {
3428 int ivar_count;
3429 struct _objc_ivar ivar_list[nIvars];
Mike Stump11289f42009-09-09 15:08:12 +00003430 };
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003431 */
Mike Stump11289f42009-09-09 15:08:12 +00003432 Result += "\nstatic struct {\n";
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003433 Result += "\tint ivar_count;\n";
3434 Result += "\tstruct _objc_ivar ivar_list[";
3435 Result += utostr(NumIvars);
3436 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003437 Result += IDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003438 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003439 "{\n\t";
3440 Result += utostr(NumIvars);
3441 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003442
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003443 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor5f662052009-04-23 03:23:08 +00003444 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003445 if (!IDecl->ivar_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00003446 for (ObjCImplementationDecl::ivar_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003447 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor5f662052009-04-23 03:23:08 +00003448 IV != IVEnd; ++IV)
3449 IVars.push_back(*IV);
3450 IVI = IVars.begin();
3451 IVE = IVars.end();
Chris Lattner30d23e82007-12-12 07:56:42 +00003452 } else {
3453 IVI = CDecl->ivar_begin();
3454 IVE = CDecl->ivar_end();
3455 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003456 Result += "\t,{{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003457 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003458 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003459 std::string TmpString, StrEncoding;
3460 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3461 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003462 Result += StrEncoding;
3463 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003464 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003465 Result += "}\n";
Chris Lattner30d23e82007-12-12 07:56:42 +00003466 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003467 Result += "\t ,{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003468 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003469 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003470 std::string TmpString, StrEncoding;
3471 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3472 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003473 Result += StrEncoding;
3474 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003475 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003476 Result += "}\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003477 }
Mike Stump11289f42009-09-09 15:08:12 +00003478
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003479 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003480 }
Mike Stump11289f42009-09-09 15:08:12 +00003481
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003482 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003483 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003484 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003485
3486 // If any of our property implementations have associated getters or
3487 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003488 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3489 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003490 Prop != PropEnd; ++Prop) {
3491 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3492 continue;
3493 if (!(*Prop)->getPropertyIvarDecl())
3494 continue;
3495 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3496 if (!PD)
3497 continue;
3498 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3499 InstanceMethods.push_back(Getter);
3500 if (PD->isReadOnly())
3501 continue;
3502 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3503 InstanceMethods.push_back(Setter);
3504 }
3505 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003506 true, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003507
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003508 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003509 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003510 false, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003511
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003512 // Protocols referenced in class declaration?
Steve Naroffd9803712009-04-29 16:37:50 +00003513 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3514 "CLASS", CDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003515
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003516 // Declaration of class/meta-class metadata
3517 /* struct _objc_class {
3518 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003519 const char *super_class_name;
3520 char *name;
3521 long version;
3522 long info;
3523 long instance_size;
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003524 struct _objc_ivar_list *ivars;
3525 struct _objc_method_list *methods;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003526 struct objc_cache *cache;
3527 struct objc_protocol_list *protocols;
3528 const char *ivar_layout;
3529 struct _objc_class_ext *ext;
Mike Stump11289f42009-09-09 15:08:12 +00003530 };
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003531 */
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003532 static bool objc_class = false;
3533 if (!objc_class) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003534 Result += "\nstruct _objc_class {\n";
3535 Result += "\tstruct _objc_class *isa;\n";
3536 Result += "\tconst char *super_class_name;\n";
3537 Result += "\tchar *name;\n";
3538 Result += "\tlong version;\n";
3539 Result += "\tlong info;\n";
3540 Result += "\tlong instance_size;\n";
3541 Result += "\tstruct _objc_ivar_list *ivars;\n";
3542 Result += "\tstruct _objc_method_list *methods;\n";
3543 Result += "\tstruct objc_cache *cache;\n";
3544 Result += "\tstruct _objc_protocol_list *protocols;\n";
3545 Result += "\tconst char *ivar_layout;\n";
3546 Result += "\tstruct _objc_class_ext *ext;\n";
3547 Result += "};\n";
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003548 objc_class = true;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003549 }
Mike Stump11289f42009-09-09 15:08:12 +00003550
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003551 // Meta-class metadata generation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003552 ObjCInterfaceDecl *RootClass = 0;
3553 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003554 while (SuperClass) {
3555 RootClass = SuperClass;
3556 SuperClass = SuperClass->getSuperClass();
3557 }
3558 SuperClass = CDecl->getSuperClass();
Mike Stump11289f42009-09-09 15:08:12 +00003559
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003560 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003561 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003562 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003563 "{\n\t(struct _objc_class *)\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003564 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003565 Result += "\"";
3566
3567 if (SuperClass) {
3568 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003569 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003570 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003571 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003572 Result += "\"";
3573 }
3574 else {
3575 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003576 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003577 Result += "\"";
3578 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003579 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003580 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003581 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003582 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff0b844f02008-03-11 18:14:26 +00003583 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003584 Result += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003585 Result += "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003586 }
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003587 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003588 Result += ", 0\n";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003589 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003590 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003591 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003592 Result += ",0,0\n";
3593 }
Fariborz Jahanian486f7182007-10-24 20:54:23 +00003594 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003595 Result += "\t,0,0,0,0\n";
3596 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003597
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003598 // class metadata generation.
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003599 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003600 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003601 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003602 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003603 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003604 if (SuperClass) {
3605 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003606 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003607 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003608 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003609 Result += "\"";
3610 }
3611 else {
3612 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003613 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003614 Result += "\"";
3615 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003616 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003617 Result += ", 0,1";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003618 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003619 Result += ",0";
3620 else {
3621 // class has size. Must synthesize its size.
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00003622 Result += ",sizeof(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003623 Result += CDecl->getNameAsString();
Steve Naroff14a07462008-03-10 23:33:22 +00003624 if (LangOpts.Microsoft)
3625 Result += "_IMPL";
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003626 Result += ")";
3627 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003628 if (NumIvars > 0) {
Steve Naroff17978c42008-03-11 17:37:02 +00003629 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003630 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003631 Result += "\n\t";
3632 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003633 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003634 Result += ",0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003635 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003636 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003637 Result += CDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003638 Result += ", 0\n\t";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003639 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003640 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003641 Result += ",0,0";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003642 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003643 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003644 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003645 Result += ", 0,0\n";
3646 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003647 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003648 Result += ",0,0,0\n";
3649 Result += "};\n";
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003650}
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003651
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003652/// RewriteImplementations - This routine rewrites all method implementations
3653/// and emits meta-data.
3654
Steve Narofff8cfd162008-11-13 20:07:04 +00003655void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003656 int ClsDefCount = ClassImplementation.size();
3657 int CatDefCount = CategoryImplementation.size();
Mike Stump11289f42009-09-09 15:08:12 +00003658
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003659 // Rewrite implemented methods
3660 for (int i = 0; i < ClsDefCount; i++)
3661 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003662
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00003663 for (int i = 0; i < CatDefCount; i++)
3664 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofff8cfd162008-11-13 20:07:04 +00003665}
Mike Stump11289f42009-09-09 15:08:12 +00003666
Steve Narofff8cfd162008-11-13 20:07:04 +00003667void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3668 int ClsDefCount = ClassImplementation.size();
3669 int CatDefCount = CategoryImplementation.size();
3670
Steve Naroff30ac2222008-05-07 21:23:49 +00003671 // This is needed for determining instance variable offsets.
Fariborz Jahanian9ab63492010-01-07 18:31:42 +00003672 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003673 // For each implemented class, write out all its meta data.
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003674 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003675 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump11289f42009-09-09 15:08:12 +00003676
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003677 // For each implemented category, write out all its meta data.
3678 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003679 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroffd9803712009-04-29 16:37:50 +00003680
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003681 // Write objc_symtab metadata
3682 /*
3683 struct _objc_symtab
3684 {
3685 long sel_ref_cnt;
3686 SEL *refs;
3687 short cls_def_cnt;
3688 short cat_def_cnt;
3689 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump11289f42009-09-09 15:08:12 +00003690 };
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003691 */
Mike Stump11289f42009-09-09 15:08:12 +00003692
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003693 Result += "\nstruct _objc_symtab {\n";
3694 Result += "\tlong sel_ref_cnt;\n";
3695 Result += "\tSEL *refs;\n";
3696 Result += "\tshort cls_def_cnt;\n";
3697 Result += "\tshort cat_def_cnt;\n";
3698 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3699 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003700
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003701 Result += "static struct _objc_symtab "
Steve Naroffb327e492008-03-12 17:18:30 +00003702 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003703 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003704 + ", " + utostr(CatDefCount) + "\n";
3705 for (int i = 0; i < ClsDefCount; i++) {
3706 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003707 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003708 Result += "\n";
3709 }
Mike Stump11289f42009-09-09 15:08:12 +00003710
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003711 for (int i = 0; i < CatDefCount; i++) {
3712 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003713 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003714 Result += "_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003715 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003716 Result += "\n";
3717 }
Mike Stump11289f42009-09-09 15:08:12 +00003718
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003719 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003720
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003721 // Write objc_module metadata
Mike Stump11289f42009-09-09 15:08:12 +00003722
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003723 /*
3724 struct _objc_module {
3725 long version;
3726 long size;
3727 const char *name;
3728 struct _objc_symtab *symtab;
3729 }
3730 */
Mike Stump11289f42009-09-09 15:08:12 +00003731
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003732 Result += "\nstruct _objc_module {\n";
3733 Result += "\tlong version;\n";
3734 Result += "\tlong size;\n";
3735 Result += "\tconst char *name;\n";
3736 Result += "\tstruct _objc_symtab *symtab;\n";
3737 Result += "};\n\n";
3738 Result += "static struct _objc_module "
Steve Naroffb327e492008-03-12 17:18:30 +00003739 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003740 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003741 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003742 Result += "};\n\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003743
3744 if (LangOpts.Microsoft) {
Steve Naroffd9803712009-04-29 16:37:50 +00003745 if (ProtocolExprDecls.size()) {
3746 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
3747 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump11289f42009-09-09 15:08:12 +00003748 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00003749 E = ProtocolExprDecls.end(); I != E; ++I) {
3750 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
3751 Result += (*I)->getNameAsString();
3752 Result += " = &_OBJC_PROTOCOL_";
3753 Result += (*I)->getNameAsString();
3754 Result += ";\n";
3755 }
3756 Result += "#pragma data_seg(pop)\n\n";
3757 }
Steve Naroff945a3b12008-03-10 20:43:59 +00003758 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffcab93d52008-05-07 00:06:16 +00003759 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003760 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3761 Result += "&_OBJC_MODULES;\n";
3762 Result += "#pragma data_seg(pop)\n\n";
3763 }
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003764}
Chris Lattnera7c19fe2007-10-16 22:36:42 +00003765
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003766void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3767 const std::string &Name,
3768 ValueDecl *VD) {
3769 assert(BlockByRefDeclNo.count(VD) &&
3770 "RewriteByRefString: ByRef decl missing");
3771 ResultStr += "struct __Block_byref_" + Name +
3772 "_" + utostr(BlockByRefDeclNo[VD]) ;
3773}
3774
Steve Naroff677ab3a2008-10-27 17:20:55 +00003775std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3776 const char *funcName,
3777 std::string Tag) {
3778 const FunctionType *AFT = CE->getFunctionType();
3779 QualType RT = AFT->getResultType();
3780 std::string StructRef = "struct " + Tag;
3781 std::string S = "static " + RT.getAsString() + " __" +
3782 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00003783
Steve Naroff677ab3a2008-10-27 17:20:55 +00003784 BlockDecl *BD = CE->getBlockDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003785
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003786 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump11289f42009-09-09 15:08:12 +00003787 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Narofff26a1d42009-02-02 17:19:26 +00003788 // block (to reference imported block decl refs).
3789 S += "(" + StructRef + " *__cself)";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003790 } else if (BD->param_empty()) {
3791 S += "(" + StructRef + " *__cself)";
3792 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003793 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003794 assert(FT && "SynthesizeBlockFunc: No function proto");
3795 S += '(';
3796 // first add the implicit argument.
3797 S += StructRef + " *__cself, ";
3798 std::string ParamStr;
3799 for (BlockDecl::param_iterator AI = BD->param_begin(),
3800 E = BD->param_end(); AI != E; ++AI) {
3801 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003802 ParamStr = (*AI)->getNameAsString();
Douglas Gregor7de59662009-05-29 20:38:28 +00003803 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003804 S += ParamStr;
3805 }
3806 if (FT->isVariadic()) {
3807 if (!BD->param_empty()) S += ", ";
3808 S += "...";
3809 }
3810 S += ')';
3811 }
3812 S += " {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003813
Steve Naroff677ab3a2008-10-27 17:20:55 +00003814 // Create local declarations to avoid rewriting all closure decl ref exprs.
3815 // First, emit a declaration for all "by ref" decls.
Mike Stump11289f42009-09-09 15:08:12 +00003816 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003817 E = BlockByRefDecls.end(); I != E; ++I) {
3818 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003819 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003820 std::string TypeString;
3821 RewriteByRefString(TypeString, Name, (*I));
3822 TypeString += " *";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003823 Name = TypeString + Name;
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003824 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump11289f42009-09-09 15:08:12 +00003825 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003826 // Next, emit a declaration for all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003827 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003828 E = BlockByCopyDecls.end(); I != E; ++I) {
3829 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003830 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003831 // Handle nested closure invocation. For example:
3832 //
3833 // void (^myImportedClosure)(void);
3834 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003835 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003836 // void (^anotherClosure)(void);
3837 // anotherClosure = ^(void) {
3838 // myImportedClosure(); // import and invoke the closure
3839 // };
3840 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003841 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003842 S += "struct __block_impl *";
3843 else
Douglas Gregor7de59662009-05-29 20:38:28 +00003844 (*I)->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003845 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003846 }
3847 std::string RewrittenStr = RewrittenBlockExprs[CE];
3848 const char *cstr = RewrittenStr.c_str();
3849 while (*cstr++ != '{') ;
3850 S += cstr;
3851 S += "\n";
3852 return S;
3853}
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00003854
Steve Naroff677ab3a2008-10-27 17:20:55 +00003855std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3856 const char *funcName,
3857 std::string Tag) {
3858 std::string StructRef = "struct " + Tag;
3859 std::string S = "static void __";
Mike Stump11289f42009-09-09 15:08:12 +00003860
Steve Naroff677ab3a2008-10-27 17:20:55 +00003861 S += funcName;
3862 S += "_block_copy_" + utostr(i);
3863 S += "(" + StructRef;
3864 S += "*dst, " + StructRef;
3865 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003866 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003867 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003868 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003869 S += (*I)->getNameAsString();
Steve Naroff5ac4eac2008-12-11 20:51:38 +00003870 S += ", (void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003871 S += (*I)->getNameAsString();
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003872 if (BlockByRefDecls.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003873 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003874 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003875 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003876 }
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003877 S += "}\n";
3878
Steve Naroff677ab3a2008-10-27 17:20:55 +00003879 S += "\nstatic void __";
3880 S += funcName;
3881 S += "_block_dispose_" + utostr(i);
3882 S += "(" + StructRef;
3883 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003884 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003885 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003886 S += "_Block_object_dispose((void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003887 S += (*I)->getNameAsString();
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003888 if (BlockByRefDecls.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003889 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003890 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003891 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003892 }
Mike Stump11289f42009-09-09 15:08:12 +00003893 S += "}\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003894 return S;
3895}
3896
Steve Naroff30484702009-12-06 21:14:13 +00003897std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3898 std::string Desc) {
Steve Naroff295570a2008-10-30 12:09:33 +00003899 std::string S = "\nstruct " + Tag;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003900 std::string Constructor = " " + Tag;
Mike Stump11289f42009-09-09 15:08:12 +00003901
Steve Naroff677ab3a2008-10-27 17:20:55 +00003902 S += " {\n struct __block_impl impl;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003903 S += " struct " + Desc;
3904 S += "* Desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003905
Steve Naroff30484702009-12-06 21:14:13 +00003906 Constructor += "(void *fp, "; // Invoke function pointer.
3907 Constructor += "struct " + Desc; // Descriptor pointer.
3908 Constructor += " *desc";
Mike Stump11289f42009-09-09 15:08:12 +00003909
Steve Naroff677ab3a2008-10-27 17:20:55 +00003910 if (BlockDeclRefs.size()) {
3911 // Output all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003912 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003913 E = BlockByCopyDecls.end(); I != E; ++I) {
3914 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003915 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003916 std::string ArgName = "_" + FieldName;
3917 // Handle nested closure invocation. For example:
3918 //
3919 // void (^myImportedBlock)(void);
3920 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003921 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003922 // void (^anotherBlock)(void);
3923 // anotherBlock = ^(void) {
3924 // myImportedBlock(); // import and invoke the closure
3925 // };
3926 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003927 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003928 S += "struct __block_impl *";
3929 Constructor += ", void *" + ArgName;
3930 } else {
Douglas Gregor7de59662009-05-29 20:38:28 +00003931 (*I)->getType().getAsStringInternal(FieldName, Context->PrintingPolicy);
3932 (*I)->getType().getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003933 Constructor += ", " + ArgName;
3934 }
3935 S += FieldName + ";\n";
3936 }
3937 // Output all "by ref" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003938 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003939 E = BlockByRefDecls.end(); I != E; ++I) {
3940 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003941 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003942 std::string ArgName = "_" + FieldName;
3943 // Handle nested closure invocation. For example:
3944 //
3945 // void (^myImportedBlock)(void);
3946 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003947 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003948 // void (^anotherBlock)(void);
3949 // anotherBlock = ^(void) {
3950 // myImportedBlock(); // import and invoke the closure
3951 // };
3952 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003953 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003954 S += "struct __block_impl *";
3955 Constructor += ", void *" + ArgName;
3956 } else {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003957 std::string TypeString;
3958 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003959 TypeString += " *";
3960 FieldName = TypeString + FieldName;
3961 ArgName = TypeString + ArgName;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003962 Constructor += ", " + ArgName;
3963 }
3964 S += FieldName + "; // by ref\n";
3965 }
3966 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00003967 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003968 if (GlobalVarDecl)
3969 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3970 else
3971 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003972 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003973
Steve Naroff30484702009-12-06 21:14:13 +00003974 Constructor += " Desc = desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003975
Steve Naroff677ab3a2008-10-27 17:20:55 +00003976 // Initialize all "by copy" arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003977 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003978 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003979 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003980 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00003981 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003982 Constructor += Name + " = (struct __block_impl *)_";
3983 else
3984 Constructor += Name + " = _";
3985 Constructor += Name + ";\n";
3986 }
3987 // Initialize all "by ref" arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003988 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003989 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003990 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003991 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00003992 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003993 Constructor += Name + " = (struct __block_impl *)_";
3994 else
3995 Constructor += Name + " = _";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003996 Constructor += Name + "->__forwarding;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003997 }
3998 } else {
3999 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004000 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00004001 if (GlobalVarDecl)
4002 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4003 else
4004 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004005 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4006 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004007 }
4008 Constructor += " ";
4009 Constructor += "}\n";
4010 S += Constructor;
4011 S += "};\n";
4012 return S;
4013}
4014
Steve Naroff30484702009-12-06 21:14:13 +00004015std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4016 std::string ImplTag, int i,
4017 const char *FunName,
4018 unsigned hasCopy) {
4019 std::string S = "\nstatic struct " + DescTag;
4020
4021 S += " {\n unsigned long reserved;\n";
4022 S += " unsigned long Block_size;\n";
4023 if (hasCopy) {
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004024 S += " void (*copy)(struct ";
4025 S += ImplTag; S += "*, struct ";
4026 S += ImplTag; S += "*);\n";
4027
4028 S += " void (*dispose)(struct ";
4029 S += ImplTag; S += "*);\n";
Steve Naroff30484702009-12-06 21:14:13 +00004030 }
4031 S += "} ";
4032
4033 S += DescTag + "_DATA = { 0, sizeof(struct ";
4034 S += ImplTag + ")";
4035 if (hasCopy) {
4036 S += ", __" + std::string(FunName) + "_block_copy_" + utostr(i);
4037 S += ", __" + std::string(FunName) + "_block_dispose_" + utostr(i);
4038 }
4039 S += "};\n";
4040 return S;
4041}
4042
Steve Naroff677ab3a2008-10-27 17:20:55 +00004043void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004044 const char *FunName) {
4045 // Insert declaration for the function in which block literal is used.
Fariborz Jahanian5c26eee2010-01-15 18:14:52 +00004046 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004047 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004048 // Insert closures that were part of the function.
4049 for (unsigned i = 0; i < Blocks.size(); i++) {
4050
4051 CollectBlockDeclRefInfo(Blocks[i]);
4052
Steve Naroff30484702009-12-06 21:14:13 +00004053 std::string ImplTag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
4054 std::string DescTag = "__" + std::string(FunName) + "_block_desc_" + utostr(i);
Mike Stump11289f42009-09-09 15:08:12 +00004055
Steve Naroff30484702009-12-06 21:14:13 +00004056 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004057
4058 InsertText(FunLocStart, CI.c_str(), CI.size());
4059
Steve Naroff30484702009-12-06 21:14:13 +00004060 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump11289f42009-09-09 15:08:12 +00004061
Steve Naroff677ab3a2008-10-27 17:20:55 +00004062 InsertText(FunLocStart, CF.c_str(), CF.size());
4063
4064 if (ImportedBlockDecls.size()) {
Steve Naroff30484702009-12-06 21:14:13 +00004065 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004066 InsertText(FunLocStart, HF.c_str(), HF.size());
4067 }
Steve Naroff30484702009-12-06 21:14:13 +00004068 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4069 ImportedBlockDecls.size() > 0);
4070 InsertText(FunLocStart, BD.c_str(), BD.size());
Mike Stump11289f42009-09-09 15:08:12 +00004071
Steve Naroff677ab3a2008-10-27 17:20:55 +00004072 BlockDeclRefs.clear();
4073 BlockByRefDecls.clear();
4074 BlockByCopyDecls.clear();
4075 BlockCallExprs.clear();
4076 ImportedBlockDecls.clear();
4077 }
4078 Blocks.clear();
4079 RewrittenBlockExprs.clear();
4080}
4081
4082void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4083 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner86d7d912008-11-24 03:54:41 +00004084 const char *FuncName = FD->getNameAsCString();
Mike Stump11289f42009-09-09 15:08:12 +00004085
Steve Naroff677ab3a2008-10-27 17:20:55 +00004086 SynthesizeBlockLiterals(FunLocStart, FuncName);
4087}
4088
4089void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff295570a2008-10-30 12:09:33 +00004090 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4091 //SourceLocation FunLocStart = MD->getLocStart();
4092 // FIXME: This hack works around a bug in Rewrite.InsertText().
4093 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattnere4b95692008-11-24 03:33:13 +00004094 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004095 // Convert colons to underscores.
4096 std::string::size_type loc = 0;
4097 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4098 FuncName.replace(loc, 1, "_");
Mike Stump11289f42009-09-09 15:08:12 +00004099
Steve Naroff677ab3a2008-10-27 17:20:55 +00004100 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
4101}
4102
4103void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4104 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4105 CI != E; ++CI)
4106 if (*CI) {
4107 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4108 GetBlockDeclRefExprs(CBE->getBody());
4109 else
4110 GetBlockDeclRefExprs(*CI);
4111 }
4112 // Handle specific things.
4113 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
4114 // FIXME: Handle enums.
4115 if (!isa<FunctionDecl>(CDRE->getDecl()))
4116 BlockDeclRefs.push_back(CDRE);
4117 return;
4118}
4119
4120void RewriteObjC::GetBlockCallExprs(Stmt *S) {
4121 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4122 CI != E; ++CI)
4123 if (*CI) {
4124 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4125 GetBlockCallExprs(CBE->getBody());
4126 else
4127 GetBlockCallExprs(*CI);
4128 }
Mike Stump11289f42009-09-09 15:08:12 +00004129
Steve Naroff677ab3a2008-10-27 17:20:55 +00004130 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4131 if (CE->getCallee()->getType()->isBlockPointerType()) {
4132 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
4133 }
4134 }
4135 return;
4136}
4137
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004138Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004139 // Navigate to relevant type information.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004140 const BlockPointerType *CPT = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004141
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004142 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004143 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004144 } else if (const BlockDeclRefExpr *CDRE =
4145 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004146 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004147 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004148 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004149 }
4150 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4151 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4152 }
4153 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4154 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4155 else if (const ConditionalOperator *CEXPR =
4156 dyn_cast<ConditionalOperator>(BlockExp)) {
4157 Expr *LHSExp = CEXPR->getLHS();
4158 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4159 Expr *RHSExp = CEXPR->getRHS();
4160 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4161 Expr *CONDExp = CEXPR->getCond();
4162 ConditionalOperator *CondExpr =
4163 new (Context) ConditionalOperator(CONDExp,
4164 SourceLocation(), cast<Expr>(LHSStmt),
4165 SourceLocation(), cast<Expr>(RHSStmt),
4166 Exp->getType());
4167 return CondExpr;
Fariborz Jahanian6ab7ed42009-12-18 01:15:21 +00004168 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4169 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004170 } else {
4171 assert(1 && "RewriteBlockClass: Bad type");
4172 }
4173 assert(CPT && "RewriteBlockClass: Bad type");
John McCall9dd450b2009-09-21 23:43:11 +00004174 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004175 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004176 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004177 // FTP will be null for closures that don't take arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004178
Steve Naroff350b6652008-10-30 10:07:53 +00004179 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4180 SourceLocation(),
4181 &Context->Idents.get("__block_impl"));
4182 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff677ab3a2008-10-27 17:20:55 +00004183
Steve Naroff350b6652008-10-30 10:07:53 +00004184 // Generate a funky cast.
4185 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00004186
Steve Naroff350b6652008-10-30 10:07:53 +00004187 // Push the block argument type.
4188 ArgTypes.push_back(PtrBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004189 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004190 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff350b6652008-10-30 10:07:53 +00004191 E = FTP->arg_type_end(); I && (I != E); ++I) {
4192 QualType t = *I;
4193 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00004194 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004195 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff350b6652008-10-30 10:07:53 +00004196 t = Context->getPointerType(BPT->getPointeeType());
4197 }
4198 ArgTypes.push_back(t);
4199 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004200 }
Steve Naroff350b6652008-10-30 10:07:53 +00004201 // Now do the pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00004202 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Steve Naroff350b6652008-10-30 10:07:53 +00004203 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004204
Steve Naroff350b6652008-10-30 10:07:53 +00004205 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump11289f42009-09-09 15:08:12 +00004206
4207 CastExpr *BlkCast = new (Context) CStyleCastExpr(PtrBlock,
Anders Carlssona2615922009-07-31 00:48:10 +00004208 CastExpr::CK_Unknown,
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004209 const_cast<Expr*>(BlockExp),
Ted Kremenek5a201952009-02-07 01:47:29 +00004210 PtrBlock, SourceLocation(),
4211 SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004212 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00004213 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4214 BlkCast);
Steve Naroff350b6652008-10-30 10:07:53 +00004215 //PE->dump();
Mike Stump11289f42009-09-09 15:08:12 +00004216
Douglas Gregor91f84212008-12-11 16:49:14 +00004217 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004218 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004219 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek5a201952009-02-07 01:47:29 +00004220 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4221 FD->getType());
Mike Stump11289f42009-09-09 15:08:12 +00004222
Anders Carlssona2615922009-07-31 00:48:10 +00004223 CastExpr *FunkCast = new (Context) CStyleCastExpr(PtrToFuncCastType,
4224 CastExpr::CK_Unknown, ME,
Ted Kremenek5a201952009-02-07 01:47:29 +00004225 PtrToFuncCastType,
4226 SourceLocation(),
4227 SourceLocation());
4228 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump11289f42009-09-09 15:08:12 +00004229
Steve Naroff350b6652008-10-30 10:07:53 +00004230 llvm::SmallVector<Expr*, 8> BlkExprs;
4231 // Add the implicit argument.
4232 BlkExprs.push_back(BlkCast);
4233 // Add the user arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004234 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004235 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00004236 BlkExprs.push_back(*I);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004237 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004238 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4239 BlkExprs.size(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004240 Exp->getType(), SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004241 return CE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004242}
4243
4244void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004245 Stmt *BlockCall = SynthesizeBlockCall(Exp, Exp->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00004246 ReplaceStmt(Exp, BlockCall);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004247}
4248
Steve Naroffd9803712009-04-29 16:37:50 +00004249// We need to return the rewritten expression to handle cases where the
4250// BlockDeclRefExpr is embedded in another expression being rewritten.
4251// For example:
4252//
4253// int main() {
4254// __block Foo *f;
4255// __block int i;
Mike Stump11289f42009-09-09 15:08:12 +00004256//
Steve Naroffd9803712009-04-29 16:37:50 +00004257// void (^myblock)() = ^() {
4258// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4259// i = 77;
4260// };
4261//}
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004262Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanian25c07fa2009-12-23 19:26:34 +00004263 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004264 // for each DeclRefExp where BYREFVAR is name of the variable.
4265 ValueDecl *VD;
4266 bool isArrow = true;
4267 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4268 VD = BDRE->getDecl();
4269 else {
4270 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4271 isArrow = false;
4272 }
4273
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004274 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4275 &Context->Idents.get("__forwarding"),
4276 Context->VoidPtrTy, 0,
4277 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004278 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4279 FD, SourceLocation(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004280 FD->getType());
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004281
4282 const char *Name = VD->getNameAsCString();
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004283 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4284 &Context->Idents.get(Name),
4285 Context->VoidPtrTy, 0,
4286 /*BitWidth=*/0, /*Mutable=*/true);
4287 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004288 DeclRefExp->getType());
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004289
4290
4291
Steve Narofff26a1d42009-02-02 17:19:26 +00004292 // Need parens to enforce precedence.
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004293 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4294 ME);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004295 ReplaceStmt(DeclRefExp, PE);
Steve Naroffd9803712009-04-29 16:37:50 +00004296 return PE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004297}
4298
Steve Naroffc989a7b2008-11-03 23:29:32 +00004299void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4300 SourceLocation LocStart = CE->getLParenLoc();
4301 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofff4b992a2008-10-28 20:29:00 +00004302
4303 // Need to avoid trying to rewrite synthesized casts.
4304 if (LocStart.isInvalid())
4305 return;
Steve Naroff3e7ced12008-11-03 11:20:24 +00004306 // Need to avoid trying to rewrite casts contained in macros.
4307 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4308 return;
Mike Stump11289f42009-09-09 15:08:12 +00004309
Steve Naroff677ab3a2008-10-27 17:20:55 +00004310 const char *startBuf = SM->getCharacterData(LocStart);
4311 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00004312
Steve Naroff677ab3a2008-10-27 17:20:55 +00004313 // advance the location to startArgList.
4314 const char *argPtr = startBuf;
Mike Stump11289f42009-09-09 15:08:12 +00004315
Steve Naroff677ab3a2008-10-27 17:20:55 +00004316 while (*argPtr++ && (argPtr < endBuf)) {
4317 switch (*argPtr) {
Mike Stump11289f42009-09-09 15:08:12 +00004318 case '^':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004319 // Replace the '^' with '*'.
4320 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
4321 ReplaceText(LocStart, 1, "*", 1);
4322 break;
4323 }
4324 }
4325 return;
4326}
4327
4328void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4329 SourceLocation DeclLoc = FD->getLocation();
4330 unsigned parenCount = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004331
Steve Naroff677ab3a2008-10-27 17:20:55 +00004332 // We have 1 or more arguments that have closure pointers.
4333 const char *startBuf = SM->getCharacterData(DeclLoc);
4334 const char *startArgList = strchr(startBuf, '(');
Mike Stump11289f42009-09-09 15:08:12 +00004335
Steve Naroff677ab3a2008-10-27 17:20:55 +00004336 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004337
Steve Naroff677ab3a2008-10-27 17:20:55 +00004338 parenCount++;
4339 // advance the location to startArgList.
4340 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4341 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump11289f42009-09-09 15:08:12 +00004342
Steve Naroff677ab3a2008-10-27 17:20:55 +00004343 const char *argPtr = startArgList;
Mike Stump11289f42009-09-09 15:08:12 +00004344
Steve Naroff677ab3a2008-10-27 17:20:55 +00004345 while (*argPtr++ && parenCount) {
4346 switch (*argPtr) {
Mike Stump11289f42009-09-09 15:08:12 +00004347 case '^':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004348 // Replace the '^' with '*'.
4349 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
4350 ReplaceText(DeclLoc, 1, "*", 1);
4351 break;
Mike Stump11289f42009-09-09 15:08:12 +00004352 case '(':
4353 parenCount++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004354 break;
Mike Stump11289f42009-09-09 15:08:12 +00004355 case ')':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004356 parenCount--;
4357 break;
4358 }
4359 }
4360 return;
4361}
4362
4363bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004364 const FunctionProtoType *FTP;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004365 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004366 if (PT) {
John McCall9dd450b2009-09-21 23:43:11 +00004367 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004368 } else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004369 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004370 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall9dd450b2009-09-21 23:43:11 +00004371 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004372 }
4373 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004374 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004375 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +00004376 if (isTopLevelBlockPointerType(*I))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004377 return true;
4378 }
4379 return false;
4380}
4381
Ted Kremenek5a201952009-02-07 01:47:29 +00004382void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4383 const char *&RParen) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004384 const char *argPtr = strchr(Name, '(');
4385 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004386
Steve Naroff677ab3a2008-10-27 17:20:55 +00004387 LParen = argPtr; // output the start.
4388 argPtr++; // skip past the left paren.
4389 unsigned parenCount = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004390
Steve Naroff677ab3a2008-10-27 17:20:55 +00004391 while (*argPtr && parenCount) {
4392 switch (*argPtr) {
4393 case '(': parenCount++; break;
4394 case ')': parenCount--; break;
4395 default: break;
4396 }
4397 if (parenCount) argPtr++;
4398 }
4399 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4400 RParen = argPtr; // output the end
4401}
4402
4403void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4404 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4405 RewriteBlockPointerFunctionArgs(FD);
4406 return;
Mike Stump11289f42009-09-09 15:08:12 +00004407 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004408 // Handle Variables and Typedefs.
4409 SourceLocation DeclLoc = ND->getLocation();
4410 QualType DeclT;
4411 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4412 DeclT = VD->getType();
4413 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4414 DeclT = TDD->getUnderlyingType();
4415 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4416 DeclT = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004417 else
Steve Naroff677ab3a2008-10-27 17:20:55 +00004418 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump11289f42009-09-09 15:08:12 +00004419
Steve Naroff677ab3a2008-10-27 17:20:55 +00004420 const char *startBuf = SM->getCharacterData(DeclLoc);
4421 const char *endBuf = startBuf;
4422 // scan backward (from the decl location) for the end of the previous decl.
4423 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4424 startBuf--;
Mike Stump11289f42009-09-09 15:08:12 +00004425
Steve Naroff677ab3a2008-10-27 17:20:55 +00004426 // *startBuf != '^' if we are dealing with a pointer to function that
4427 // may take block argument types (which will be handled below).
4428 if (*startBuf == '^') {
4429 // Replace the '^' with '*', computing a negative offset.
4430 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4431 ReplaceText(DeclLoc, 1, "*", 1);
4432 }
4433 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4434 // Replace the '^' with '*' for arguments.
4435 DeclLoc = ND->getLocation();
4436 startBuf = SM->getCharacterData(DeclLoc);
4437 const char *argListBegin, *argListEnd;
4438 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4439 while (argListBegin < argListEnd) {
4440 if (*argListBegin == '^') {
4441 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4442 ReplaceText(CaretLoc, 1, "*", 1);
4443 }
4444 argListBegin++;
4445 }
4446 }
4447 return;
4448}
4449
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004450
4451/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4452/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4453/// struct Block_byref_id_object *src) {
4454/// _Block_object_assign (&_dest->object, _src->object,
4455/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4456/// [|BLOCK_FIELD_IS_WEAK]) // object
4457/// _Block_object_assign(&_dest->object, _src->object,
4458/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4459/// [|BLOCK_FIELD_IS_WEAK]) // block
4460/// }
4461/// And:
4462/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4463/// _Block_object_dispose(_src->object,
4464/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4465/// [|BLOCK_FIELD_IS_WEAK]) // object
4466/// _Block_object_dispose(_src->object,
4467/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4468/// [|BLOCK_FIELD_IS_WEAK]) // block
4469/// }
4470
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004471std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4472 int flag) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004473 std::string S;
Benjamin Kramere056cea2010-01-10 19:57:50 +00004474 if (CopyDestroyCache.count(flag))
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004475 return S;
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004476 CopyDestroyCache.insert(flag);
4477 S = "static void __Block_byref_id_object_copy_";
4478 S += utostr(flag);
4479 S += "(void *dst, void *src) {\n";
4480
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004481 // offset into the object pointer is computed as:
4482 // void * + void* + int + int + void* + void *
4483 unsigned IntSize =
4484 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4485 unsigned VoidPtrSize =
4486 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4487
4488 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
4489 S += " _Block_object_assign((char*)dst + ";
4490 S += utostr(offset);
4491 S += ", *(void * *) ((char*)src + ";
4492 S += utostr(offset);
4493 S += "), ";
4494 S += utostr(flag);
4495 S += ");\n}\n";
4496
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004497 S += "static void __Block_byref_id_object_dispose_";
4498 S += utostr(flag);
4499 S += "(void *src) {\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004500 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4501 S += utostr(offset);
4502 S += "), ";
4503 S += utostr(flag);
4504 S += ");\n}\n";
4505 return S;
4506}
4507
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004508/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4509/// the declaration into:
4510/// struct __Block_byref_ND {
4511/// void *__isa; // NULL for everything except __weak pointers
4512/// struct __Block_byref_ND *__forwarding;
4513/// int32_t __flags;
4514/// int32_t __size;
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004515/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4516/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004517/// typex ND;
4518/// };
4519///
4520/// It then replaces declaration of ND variable with:
4521/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4522/// __size=sizeof(struct __Block_byref_ND),
4523/// ND=initializer-if-any};
4524///
4525///
4526void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004527 // Insert declaration for the function in which block literal is
4528 // used.
4529 if (CurFunctionDeclToDeclareForBlock)
4530 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004531 int flag = 0;
4532 int isa = 0;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004533 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4534 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian92368a12009-12-30 20:38:08 +00004535 SourceLocation X = ND->getLocEnd();
4536 X = SM->getInstantiationLoc(X);
4537 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004538 std::string Name(ND->getNameAsString());
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004539 std::string ByrefType;
4540 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004541 ByrefType += " {\n";
4542 ByrefType += " void *__isa;\n";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004543 RewriteByRefString(ByrefType, Name, ND);
4544 ByrefType += " *__forwarding;\n";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004545 ByrefType += " int __flags;\n";
4546 ByrefType += " int __size;\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004547 // Add void *__Block_byref_id_object_copy;
4548 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004549 QualType Ty = ND->getType();
4550 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4551 if (HasCopyAndDispose) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004552 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4553 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004554 }
4555
4556 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004557 ByrefType += " " + Name + ";\n";
4558 ByrefType += "};\n";
4559 // Insert this type in global scope. It is needed by helper function.
4560 assert(CurFunctionDef && "RewriteByRefVar - CurFunctionDef is null");
4561 SourceLocation FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4562 InsertText(FunLocStart, ByrefType.c_str(), ByrefType.size());
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004563 if (Ty.isObjCGCWeak()) {
4564 flag |= BLOCK_FIELD_IS_WEAK;
4565 isa = 1;
4566 }
4567
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004568 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004569 flag = BLOCK_BYREF_CALLER;
4570 QualType Ty = ND->getType();
4571 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4572 if (Ty->isBlockPointerType())
4573 flag |= BLOCK_FIELD_IS_BLOCK;
4574 else
4575 flag |= BLOCK_FIELD_IS_OBJECT;
4576 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004577 if (!HF.empty())
4578 InsertText(FunLocStart, HF.c_str(), HF.size());
4579 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004580
4581 // struct __Block_byref_ND ND =
4582 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4583 // initializer-if-any};
4584 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanianf7945432010-01-05 18:15:57 +00004585 unsigned flags = 0;
4586 if (HasCopyAndDispose)
4587 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004588 Name = ND->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004589 ByrefType.clear();
4590 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004591 if (!hasInit) {
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004592 ByrefType += " " + Name + " = {(void*)";
4593 ByrefType += utostr(isa);
4594 ByrefType += ", &" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004595 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004596 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004597 ByrefType += "sizeof(";
4598 RewriteByRefString(ByrefType, Name, ND);
4599 ByrefType += ")";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004600 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004601 ByrefType += ", __Block_byref_id_object_copy_";
4602 ByrefType += utostr(flag);
4603 ByrefType += ", __Block_byref_id_object_dispose_";
4604 ByrefType += utostr(flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004605 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004606 ByrefType += "};\n";
4607 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(),
4608 ByrefType.c_str(), ByrefType.size());
4609 }
4610 else {
4611 SourceLocation startLoc = ND->getInit()->getLocStart();
Fariborz Jahanianb8646ed2010-01-05 23:06:29 +00004612 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004613 ByrefType += " " + Name;
4614 ReplaceText(DeclLoc, endBuf-startBuf,
4615 ByrefType.c_str(), ByrefType.size());
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004616 ByrefType = " = {(void*)";
4617 ByrefType += utostr(isa);
4618 ByrefType += ", &" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004619 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004620 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004621 ByrefType += "sizeof(";
4622 RewriteByRefString(ByrefType, Name, ND);
4623 ByrefType += "), ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004624 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004625 ByrefType += "__Block_byref_id_object_copy_";
4626 ByrefType += utostr(flag);
4627 ByrefType += ", __Block_byref_id_object_dispose_";
4628 ByrefType += utostr(flag);
4629 ByrefType += ", ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004630 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004631 InsertText(startLoc, ByrefType.c_str(), ByrefType.size());
Steve Naroff13468372009-12-23 17:24:33 +00004632
4633 // Complete the newly synthesized compound expression by inserting a right
4634 // curly brace before the end of the declaration.
4635 // FIXME: This approach avoids rewriting the initializer expression. It
4636 // also assumes there is only one declarator. For example, the following
4637 // isn't currently supported by this routine (in general):
4638 //
4639 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4640 //
4641 const char *startBuf = SM->getCharacterData(startLoc);
4642 const char *semiBuf = strchr(startBuf, ';');
4643 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4644 SourceLocation semiLoc =
4645 startLoc.getFileLocWithOffset(semiBuf-startBuf);
4646
4647 InsertText(semiLoc, "}", 1);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004648 }
Fariborz Jahanian81203462009-12-22 00:48:54 +00004649 return;
4650}
4651
Mike Stump11289f42009-09-09 15:08:12 +00004652void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004653 // Add initializers for any closure decl refs.
4654 GetBlockDeclRefExprs(Exp->getBody());
4655 if (BlockDeclRefs.size()) {
4656 // Unique all "by copy" declarations.
4657 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4658 if (!BlockDeclRefs[i]->isByRef())
4659 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
4660 // Unique all "by ref" declarations.
4661 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4662 if (BlockDeclRefs[i]->isByRef()) {
4663 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4664 }
4665 // Find any imported blocks...they will need special attention.
4666 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004667 if (BlockDeclRefs[i]->isByRef() ||
4668 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4669 BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroff832d8902008-11-13 17:40:07 +00004670 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004671 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4672 }
4673 }
4674}
4675
Steve Narofff4b992a2008-10-28 20:29:00 +00004676FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4677 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004678 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump11289f42009-09-09 15:08:12 +00004679 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004680 ID, FType, 0, FunctionDecl::Extern, false,
Douglas Gregor739ef0c2009-02-25 16:33:18 +00004681 false);
Steve Narofff4b992a2008-10-28 20:29:00 +00004682}
4683
Steve Naroffd8907b72008-10-29 18:15:37 +00004684Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004685 Blocks.push_back(Exp);
4686
4687 CollectBlockDeclRefInfo(Exp);
4688 std::string FuncName;
Mike Stump11289f42009-09-09 15:08:12 +00004689
Steve Narofff4b992a2008-10-28 20:29:00 +00004690 if (CurFunctionDef)
Chris Lattnere4b95692008-11-24 03:33:13 +00004691 FuncName = CurFunctionDef->getNameAsString();
Steve Narofff4b992a2008-10-28 20:29:00 +00004692 else if (CurMethodDef) {
Chris Lattnere4b95692008-11-24 03:33:13 +00004693 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofff4b992a2008-10-28 20:29:00 +00004694 // Convert colons to underscores.
4695 std::string::size_type loc = 0;
4696 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4697 FuncName.replace(loc, 1, "_");
Steve Naroffd8907b72008-10-29 18:15:37 +00004698 } else if (GlobalVarDecl)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004699 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +00004700
Steve Narofff4b992a2008-10-28 20:29:00 +00004701 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump11289f42009-09-09 15:08:12 +00004702
Steve Narofff4b992a2008-10-28 20:29:00 +00004703 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4704 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump11289f42009-09-09 15:08:12 +00004705
Steve Narofff4b992a2008-10-28 20:29:00 +00004706 // Get a pointer to the function type so we can cast appropriately.
4707 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4708
4709 FunctionDecl *FD;
4710 Expr *NewRep;
Mike Stump11289f42009-09-09 15:08:12 +00004711
Steve Narofff4b992a2008-10-28 20:29:00 +00004712 // Simulate a contructor call...
4713 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004714 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004715
Steve Narofff4b992a2008-10-28 20:29:00 +00004716 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00004717
Steve Naroffe2514232008-10-29 21:23:59 +00004718 // Initialize the block function.
Steve Narofff4b992a2008-10-28 20:29:00 +00004719 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004720 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4721 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004722 CastExpr *castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4723 CastExpr::CK_Unknown, Arg,
Ted Kremenek5a201952009-02-07 01:47:29 +00004724 Context->VoidPtrTy, SourceLocation(),
4725 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004726 InitExprs.push_back(castExpr);
4727
Steve Naroff30484702009-12-06 21:14:13 +00004728 // Initialize the block descriptor.
4729 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump11289f42009-09-09 15:08:12 +00004730
Steve Naroff30484702009-12-06 21:14:13 +00004731 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
4732 &Context->Idents.get(DescData.c_str()),
4733 Context->VoidPtrTy, 0,
4734 VarDecl::Static);
4735 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
4736 new (Context) DeclRefExpr(NewVD,
4737 Context->VoidPtrTy, SourceLocation()),
4738 UnaryOperator::AddrOf,
4739 Context->getPointerType(Context->VoidPtrTy),
4740 SourceLocation());
4741 InitExprs.push_back(DescRefExpr);
4742
Steve Narofff4b992a2008-10-28 20:29:00 +00004743 // Add initializers for any closure decl refs.
4744 if (BlockDeclRefs.size()) {
Steve Naroffe2514232008-10-29 21:23:59 +00004745 Expr *Exp;
Steve Narofff4b992a2008-10-28 20:29:00 +00004746 // Output all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004747 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004748 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004749 if (isObjCType((*I)->getType())) {
Steve Naroffe2514232008-10-29 21:23:59 +00004750 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner86d7d912008-11-24 03:54:41 +00004751 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004752 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroffa5c0db82008-12-11 21:05:33 +00004753 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004754 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004755 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004756 Exp = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4757 CastExpr::CK_Unknown, Arg,
4758 Context->VoidPtrTy,
Anders Carlssona2615922009-07-31 00:48:10 +00004759 SourceLocation(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004760 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004761 } else {
Chris Lattner86d7d912008-11-24 03:54:41 +00004762 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004763 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004764 }
Mike Stump11289f42009-09-09 15:08:12 +00004765 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004766 }
4767 // Output all "by ref" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004768 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004769 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004770 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004771 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4772 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004773 Context->getPointerType(Exp->getType()),
Steve Naroffe2514232008-10-29 21:23:59 +00004774 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004775 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004776 }
4777 }
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004778 if (ImportedBlockDecls.size()) {
4779 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4780 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff30484702009-12-06 21:14:13 +00004781 unsigned IntSize =
4782 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004783 Expr *FlagExp = new (Context) IntegerLiteral(llvm::APInt(IntSize, flag),
4784 Context->IntTy, SourceLocation());
4785 InitExprs.push_back(FlagExp);
Steve Naroff30484702009-12-06 21:14:13 +00004786 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004787 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4788 FType, SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00004789 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004790 Context->getPointerType(NewRep->getType()),
Steve Narofff4b992a2008-10-28 20:29:00 +00004791 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004792 NewRep = new (Context) CStyleCastExpr(FType, CastExpr::CK_Unknown, NewRep,
Anders Carlssona2615922009-07-31 00:48:10 +00004793 FType, SourceLocation(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004794 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004795 BlockDeclRefs.clear();
4796 BlockByRefDecls.clear();
4797 BlockByCopyDecls.clear();
4798 ImportedBlockDecls.clear();
4799 return NewRep;
4800}
4801
4802//===----------------------------------------------------------------------===//
4803// Function Body / Expression rewriting
4804//===----------------------------------------------------------------------===//
4805
Steve Naroff4588d0f2008-12-04 16:24:46 +00004806// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4807// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4808// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4809// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4810// Since the rewriter isn't capable of rewriting rewritten code, it's important
4811// we get this right.
4812void RewriteObjC::CollectPropertySetters(Stmt *S) {
4813 // Perform a bottom up traversal of all children.
4814 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4815 CI != E; ++CI)
4816 if (*CI)
4817 CollectPropertySetters(*CI);
4818
4819 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4820 if (BinOp->isAssignmentOp()) {
4821 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4822 PropSetters[PRE] = BinOp;
4823 }
4824 }
4825}
4826
Steve Narofff4b992a2008-10-28 20:29:00 +00004827Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump11289f42009-09-09 15:08:12 +00004828 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004829 isa<DoStmt>(S) || isa<ForStmt>(S))
4830 Stmts.push_back(S);
4831 else if (isa<ObjCForCollectionStmt>(S)) {
4832 Stmts.push_back(S);
Chris Lattnerb71980f2010-01-09 21:45:57 +00004833 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofff4b992a2008-10-28 20:29:00 +00004834 }
Mike Stump11289f42009-09-09 15:08:12 +00004835
Steve Narofff4b992a2008-10-28 20:29:00 +00004836 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004837
Steve Narofff4b992a2008-10-28 20:29:00 +00004838 // Perform a bottom up rewrite of all children.
4839 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4840 CI != E; ++CI)
4841 if (*CI) {
4842 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Mike Stump11289f42009-09-09 15:08:12 +00004843 if (newStmt)
Steve Narofff4b992a2008-10-28 20:29:00 +00004844 *CI = newStmt;
4845 }
Mike Stump11289f42009-09-09 15:08:12 +00004846
Steve Narofff4b992a2008-10-28 20:29:00 +00004847 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4848 // Rewrite the block body in place.
4849 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Mike Stump11289f42009-09-09 15:08:12 +00004850
Steve Narofff4b992a2008-10-28 20:29:00 +00004851 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenekdb2ef372010-01-07 18:00:35 +00004852 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroffd8907b72008-10-29 18:15:37 +00004853 RewrittenBlockExprs[BE] = Str;
Mike Stump11289f42009-09-09 15:08:12 +00004854
Steve Narofff4b992a2008-10-28 20:29:00 +00004855 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4856 //blockTranscribed->dump();
Steve Naroffd8907b72008-10-29 18:15:37 +00004857 ReplaceStmt(S, blockTranscribed);
Steve Narofff4b992a2008-10-28 20:29:00 +00004858 return blockTranscribed;
4859 }
4860 // Handle specific things.
4861 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4862 return RewriteAtEncode(AtEncode);
Mike Stump11289f42009-09-09 15:08:12 +00004863
Steve Narofff4b992a2008-10-28 20:29:00 +00004864 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4865 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4866
Steve Naroff4588d0f2008-12-04 16:24:46 +00004867 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4868 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4869 if (BinOp) {
4870 // Because the rewriter doesn't allow us to rewrite rewritten code,
4871 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroff08628db2008-12-09 12:56:34 +00004872 DisableReplaceStmt = true;
4873 // Save the source range. Even if we disable the replacement, the
4874 // rewritten node will have been inserted into the tree. If the synthesized
4875 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump11289f42009-09-09 15:08:12 +00004876 // self.errorHandler = handler ? handler :
Steve Naroff08628db2008-12-09 12:56:34 +00004877 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4878 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroff4588d0f2008-12-04 16:24:46 +00004879 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroff08628db2008-12-09 12:56:34 +00004880 DisableReplaceStmt = false;
Steve Naroff22216db2008-12-04 23:50:32 +00004881 //
4882 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4883 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4884 // to see the original expression). Consider this example:
4885 //
4886 // Foo *obj1, *obj2;
4887 //
4888 // obj1.i = [obj2 rrrr];
4889 //
4890 // 'BinOp' for the previous expression looks like:
4891 //
4892 // (BinaryOperator 0x231ccf0 'int' '='
4893 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4894 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4895 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4896 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4897 //
4898 // 'newStmt' represents the rewritten message expression. For example:
4899 //
4900 // (CallExpr 0x231d300 'id':'struct objc_object *'
4901 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4902 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4903 // (CStyleCastExpr 0x231d220 'void *'
4904 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4905 //
4906 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4907 // can be used as the setter argument. ReplaceStmt() will still 'see'
4908 // the original RHS (since we haven't altered BinOp).
4909 //
Mike Stump11289f42009-09-09 15:08:12 +00004910 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff22216db2008-12-04 23:50:32 +00004911 // node. As a result, we now leak the original AST nodes.
4912 //
Steve Naroff08628db2008-12-09 12:56:34 +00004913 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroff4588d0f2008-12-04 16:24:46 +00004914 } else {
4915 return RewritePropertyGetter(PropRefExpr);
Steve Narofff326f402008-12-03 00:56:33 +00004916 }
4917 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004918 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4919 return RewriteAtSelector(AtSelector);
Mike Stump11289f42009-09-09 15:08:12 +00004920
Steve Narofff4b992a2008-10-28 20:29:00 +00004921 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4922 return RewriteObjCStringLiteral(AtString);
Mike Stump11289f42009-09-09 15:08:12 +00004923
Steve Narofff4b992a2008-10-28 20:29:00 +00004924 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00004925#if 0
Steve Narofff4b992a2008-10-28 20:29:00 +00004926 // Before we rewrite it, put the original message expression in a comment.
4927 SourceLocation startLoc = MessExpr->getLocStart();
4928 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00004929
Steve Narofff4b992a2008-10-28 20:29:00 +00004930 const char *startBuf = SM->getCharacterData(startLoc);
4931 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004932
Steve Narofff4b992a2008-10-28 20:29:00 +00004933 std::string messString;
4934 messString += "// ";
4935 messString.append(startBuf, endBuf-startBuf+1);
4936 messString += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00004937
4938 // FIXME: Missing definition of
Steve Narofff4b992a2008-10-28 20:29:00 +00004939 // InsertText(clang::SourceLocation, char const*, unsigned int).
4940 // InsertText(startLoc, messString.c_str(), messString.size());
4941 // Tried this, but it didn't work either...
4942 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff4588d0f2008-12-04 16:24:46 +00004943#endif
Steve Narofff4b992a2008-10-28 20:29:00 +00004944 return RewriteMessageExpr(MessExpr);
4945 }
Mike Stump11289f42009-09-09 15:08:12 +00004946
Steve Narofff4b992a2008-10-28 20:29:00 +00004947 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4948 return RewriteObjCTryStmt(StmtTry);
4949
4950 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4951 return RewriteObjCSynchronizedStmt(StmtTry);
4952
4953 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4954 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump11289f42009-09-09 15:08:12 +00004955
Steve Narofff4b992a2008-10-28 20:29:00 +00004956 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4957 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump11289f42009-09-09 15:08:12 +00004958
4959 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofff4b992a2008-10-28 20:29:00 +00004960 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump11289f42009-09-09 15:08:12 +00004961 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofff4b992a2008-10-28 20:29:00 +00004962 OrigStmtRange.getEnd());
4963 if (BreakStmt *StmtBreakStmt =
4964 dyn_cast<BreakStmt>(S))
4965 return RewriteBreakStmt(StmtBreakStmt);
4966 if (ContinueStmt *StmtContinueStmt =
4967 dyn_cast<ContinueStmt>(S))
4968 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump11289f42009-09-09 15:08:12 +00004969
4970 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofff4b992a2008-10-28 20:29:00 +00004971 // and cast exprs.
4972 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4973 // FIXME: What we're doing here is modifying the type-specifier that
4974 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump11289f42009-09-09 15:08:12 +00004975 // a separate type-specifier that we can rewrite.
Steve Naroffe70a52a2009-12-05 15:55:59 +00004976 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4977 // the context of an ObjCForCollectionStmt. For example:
4978 // NSArray *someArray;
4979 // for (id <FooProtocol> index in someArray) ;
4980 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4981 // and it depends on the original text locations/positions.
Benjamin Krameracc5fa12009-12-05 22:16:51 +00004982 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroffe70a52a2009-12-05 15:55:59 +00004983 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump11289f42009-09-09 15:08:12 +00004984
Steve Narofff4b992a2008-10-28 20:29:00 +00004985 // Blocks rewrite rules.
4986 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4987 DI != DE; ++DI) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004988 Decl *SD = *DI;
Steve Narofff4b992a2008-10-28 20:29:00 +00004989 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004990 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004991 RewriteBlockPointerDecl(ND);
Mike Stump11289f42009-09-09 15:08:12 +00004992 else if (ND->getType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004993 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004994 if (VarDecl *VD = dyn_cast<VarDecl>(SD))
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004995 if (VD->hasAttr<BlocksAttr>()) {
4996 static unsigned uniqueByrefDeclCount = 0;
4997 assert(!BlockByRefDeclNo.count(ND) &&
4998 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4999 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005000 RewriteByRefVar(VD);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005001 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005002 }
5003 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005004 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005005 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005006 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005007 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5008 }
5009 }
5010 }
Mike Stump11289f42009-09-09 15:08:12 +00005011
Steve Narofff4b992a2008-10-28 20:29:00 +00005012 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5013 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump11289f42009-09-09 15:08:12 +00005014
5015 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00005016 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5017 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump11289f42009-09-09 15:08:12 +00005018 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5019 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005020 && "Statement stack mismatch");
5021 Stmts.pop_back();
5022 }
5023 // Handle blocks rewriting.
5024 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5025 if (BDRE->isByRef())
Steve Naroffd9803712009-04-29 16:37:50 +00005026 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofff4b992a2008-10-28 20:29:00 +00005027 }
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005028 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5029 ValueDecl *VD = DRE->getDecl();
5030 if (VD->hasAttr<BlocksAttr>())
5031 return RewriteBlockDeclRefExpr(DRE);
5032 }
5033
Steve Narofff4b992a2008-10-28 20:29:00 +00005034 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff350b6652008-10-30 10:07:53 +00005035 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00005036 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00005037 ReplaceStmt(S, BlockCall);
5038 return BlockCall;
5039 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005040 }
Steve Naroffc989a7b2008-11-03 23:29:32 +00005041 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005042 RewriteCastExpr(CE);
5043 }
5044#if 0
5045 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek5a201952009-02-07 01:47:29 +00005046 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00005047 // Get the new text.
5048 std::string SStr;
5049 llvm::raw_string_ostream Buf(SStr);
Eli Friedman0905f142009-05-30 05:19:26 +00005050 Replacement->printPretty(Buf, *Context);
Steve Narofff4b992a2008-10-28 20:29:00 +00005051 const std::string &Str = Buf.str();
5052
5053 printf("CAST = %s\n", &Str[0]);
5054 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5055 delete S;
5056 return Replacement;
5057 }
5058#endif
5059 // Return this stmt unmodified.
5060 return S;
5061}
5062
Steve Naroffe70a52a2009-12-05 15:55:59 +00005063void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5064 for (RecordDecl::field_iterator i = RD->field_begin(),
5065 e = RD->field_end(); i != e; ++i) {
5066 FieldDecl *FD = *i;
5067 if (isTopLevelBlockPointerType(FD->getType()))
5068 RewriteBlockPointerDecl(FD);
5069 if (FD->getType()->isObjCQualifiedIdType() ||
5070 FD->getType()->isObjCQualifiedInterfaceType())
5071 RewriteObjCQualifiedInterfaceTypes(FD);
5072 }
5073}
5074
Steve Narofff4b992a2008-10-28 20:29:00 +00005075/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5076/// main file of the input.
5077void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5078 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffb1368882008-12-17 00:20:22 +00005079 if (FD->isOverloadedOperator())
5080 return;
Mike Stump11289f42009-09-09 15:08:12 +00005081
Steve Narofff4b992a2008-10-28 20:29:00 +00005082 // Since function prototypes don't have ParmDecl's, we check the function
5083 // prototype. This enables us to rewrite function declarations and
5084 // definitions using the same code.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005085 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005086
Sebastian Redla7b98a72009-04-26 20:35:05 +00005087 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005088 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005089 CurFunctionDef = FD;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005090 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005091 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005092 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005093 Body =
5094 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5095 FD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005096 CurrentBody = 0;
5097 if (PropParentMap) {
5098 delete PropParentMap;
5099 PropParentMap = 0;
5100 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005101 // This synthesizes and inserts the block "impl" struct, invoke function,
5102 // and any copy/dispose helper functions.
5103 InsertBlockLiteralsWithinFunction(FD);
5104 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005105 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005106 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005107 return;
5108 }
5109 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005110 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005111 CurMethodDef = MD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005112 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005113 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005114 Body =
5115 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5116 MD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005117 CurrentBody = 0;
5118 if (PropParentMap) {
5119 delete PropParentMap;
5120 PropParentMap = 0;
5121 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005122 InsertBlockLiteralsWithinMethod(MD);
5123 CurMethodDef = 0;
5124 }
5125 }
5126 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5127 ClassImplementation.push_back(CI);
5128 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5129 CategoryImplementation.push_back(CI);
5130 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5131 RewriteForwardClassDecl(CD);
5132 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5133 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroffa5c0db82008-12-11 21:05:33 +00005134 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005135 RewriteBlockPointerDecl(VD);
Steve Naroffd8907b72008-10-29 18:15:37 +00005136 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005137 CheckFunctionPointerDecl(VD->getType(), VD);
5138 if (VD->getInit()) {
Steve Naroffc989a7b2008-11-03 23:29:32 +00005139 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005140 RewriteCastExpr(CE);
5141 }
5142 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00005143 } else if (VD->getType()->isRecordType()) {
5144 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5145 if (RD->isDefinition())
5146 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005147 }
Steve Naroffd8907b72008-10-29 18:15:37 +00005148 if (VD->getInit()) {
5149 GlobalVarDecl = VD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005150 CollectPropertySetters(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005151 CurrentBody = VD->getInit();
Steve Naroffd8907b72008-10-29 18:15:37 +00005152 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005153 CurrentBody = 0;
5154 if (PropParentMap) {
5155 delete PropParentMap;
5156 PropParentMap = 0;
5157 }
Mike Stump11289f42009-09-09 15:08:12 +00005158 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner86d7d912008-11-24 03:54:41 +00005159 VD->getNameAsCString());
Steve Naroffd8907b72008-10-29 18:15:37 +00005160 GlobalVarDecl = 0;
5161
5162 // This is needed for blocks.
Steve Naroffc989a7b2008-11-03 23:29:32 +00005163 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroffd8907b72008-10-29 18:15:37 +00005164 RewriteCastExpr(CE);
5165 }
5166 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005167 return;
5168 }
5169 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005170 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005171 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005172 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005173 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Steve Naroffe70a52a2009-12-05 15:55:59 +00005174 else if (TD->getUnderlyingType()->isRecordType()) {
5175 RecordDecl *RD = TD->getUnderlyingType()->getAs<RecordType>()->getDecl();
5176 if (RD->isDefinition())
5177 RewriteRecordBody(RD);
5178 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005179 return;
5180 }
5181 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroffe70a52a2009-12-05 15:55:59 +00005182 if (RD->isDefinition())
5183 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005184 return;
5185 }
5186 // Nothing yet.
5187}
5188
Chris Lattnercf169832009-03-28 04:11:33 +00005189void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005190 // Get the top-level buffer that this corresponds to.
Mike Stump11289f42009-09-09 15:08:12 +00005191
Steve Narofff4b992a2008-10-28 20:29:00 +00005192 // Rewrite tabs if we care.
5193 //RewriteTabs();
Mike Stump11289f42009-09-09 15:08:12 +00005194
Steve Narofff4b992a2008-10-28 20:29:00 +00005195 if (Diags.hasErrorOccurred())
5196 return;
Mike Stump11289f42009-09-09 15:08:12 +00005197
Steve Narofff4b992a2008-10-28 20:29:00 +00005198 RewriteInclude();
Mike Stump11289f42009-09-09 15:08:12 +00005199
Steve Naroffd9803712009-04-29 16:37:50 +00005200 // Here's a great place to add any extra declarations that may be needed.
5201 // Write out meta data for each @protocol(<expr>).
Mike Stump11289f42009-09-09 15:08:12 +00005202 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00005203 E = ProtocolExprDecls.end(); I != E; ++I)
5204 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5205
Mike Stump11289f42009-09-09 15:08:12 +00005206 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Narofff4b992a2008-10-28 20:29:00 +00005207 Preamble.c_str(), Preamble.size(), false);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005208 if (ClassImplementation.size() || CategoryImplementation.size())
5209 RewriteImplementations();
Steve Naroffd9803712009-04-29 16:37:50 +00005210
Steve Narofff4b992a2008-10-28 20:29:00 +00005211 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5212 // we are done.
Mike Stump11289f42009-09-09 15:08:12 +00005213 if (const RewriteBuffer *RewriteBuf =
Steve Narofff4b992a2008-10-28 20:29:00 +00005214 Rewrite.getRewriteBufferFor(MainFileID)) {
5215 //printf("Changed:\n");
5216 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5217 } else {
5218 fprintf(stderr, "No changes\n");
5219 }
Steve Narofff8cfd162008-11-13 20:07:04 +00005220
Steve Naroffd9803712009-04-29 16:37:50 +00005221 if (ClassImplementation.size() || CategoryImplementation.size() ||
5222 ProtocolExprDecls.size()) {
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005223 // Rewrite Objective-c meta data*
5224 std::string ResultStr;
5225 SynthesizeMetaDataIntoBuffer(ResultStr);
5226 // Emit metadata.
5227 *OutFile << ResultStr;
5228 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005229 OutFile->flush();
5230}
5231