blob: 1ecde6a7fad9a1a04ac798adef867ff5524e7dc7 [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
Daniel Dunbarc1b17292010-06-15 17:48:49 +000014#include "clang/Rewrite/ASTConsumers.h"
Chris Lattner16a0de42007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattnere99c8322007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Steve Naroff1042ff32008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Chris Lattner16a0de42007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner4431a1b2007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattnerf3a59a12007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000023#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
Chris Lattner211f8b82007-10-25 17:07:24 +000025#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian99e96b02007-10-26 19:46:17 +000026#include "llvm/ADT/SmallPtrSet.h"
Ted Kremenek2d470fc2008-09-13 05:16:45 +000027#include "llvm/ADT/OwningPtr.h"
Fariborz Jahaniane3891582010-01-05 18:04:40 +000028#include "llvm/ADT/DenseSet.h"
Fariborz Jahanianf4609d42010-03-01 23:36:21 +000029
Chris Lattnere99c8322007-10-11 00:43:27 +000030using namespace clang;
Chris Lattner211f8b82007-10-25 17:07:24 +000031using llvm::utostr;
Chris Lattnere99c8322007-10-11 00:43:27 +000032
Chris Lattnere99c8322007-10-11 00:43:27 +000033namespace {
Steve Naroff1dc53ef2008-04-14 22:03:09 +000034 class RewriteObjC : public ASTConsumer {
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000035 enum {
Nico Weber1879bca2010-11-22 10:26:41 +000036 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000037 block, ... */
38 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
39 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
40 __block variable */
Nico Weber1879bca2010-11-22 10:26:41 +000041 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000042 helpers */
Nico Weber1879bca2010-11-22 10:26:41 +000043 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000044 support routines */
45 BLOCK_BYREF_CURRENT_MAX = 256
46 };
47
48 enum {
49 BLOCK_NEEDS_FREE = (1 << 24),
50 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
51 BLOCK_HAS_CXX_OBJ = (1 << 26),
52 BLOCK_IS_GC = (1 << 27),
53 BLOCK_IS_GLOBAL = (1 << 28),
54 BLOCK_HAS_DESCRIPTOR = (1 << 29)
55 };
56
Chris Lattner0bd1c972007-10-16 21:07:07 +000057 Rewriter Rewrite;
Chris Lattnere9c810c2007-11-30 22:25:36 +000058 Diagnostic &Diags;
Steve Naroff945a3b12008-03-10 20:43:59 +000059 const LangOptions &LangOpts;
Steve Naroff7b3579b2008-01-30 19:17:43 +000060 unsigned RewriteFailedDiag;
Steve Naroff6d6da252008-12-05 17:03:39 +000061 unsigned TryFinallyContainsReturnDiag;
Mike Stump11289f42009-09-09 15:08:12 +000062
Chris Lattnerc6d91c02007-10-17 22:35:30 +000063 ASTContext *Context;
Chris Lattnere99c8322007-10-11 00:43:27 +000064 SourceManager *SM;
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +000065 TranslationUnitDecl *TUDecl;
Chris Lattnerd32480d2009-01-17 06:22:33 +000066 FileID MainFileID;
Chris Lattnerf3a59a12007-12-02 01:13:47 +000067 const char *MainFileStart, *MainFileEnd;
Chris Lattner0bd1c972007-10-16 21:07:07 +000068 SourceLocation LastIncLoc;
Mike Stump11289f42009-09-09 15:08:12 +000069
Ted Kremenek1b0ea822008-01-07 19:49:32 +000070 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
71 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
72 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Naroff13e74872008-05-06 18:26:51 +000073 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremenek1b0ea822008-01-07 19:49:32 +000074 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
75 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +000076 llvm::SmallVector<Stmt *, 32> Stmts;
77 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffd9803712009-04-29 16:37:50 +000078 // Remember all the @protocol(<expr>) expressions.
79 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahaniane3891582010-01-05 18:04:40 +000080
81 llvm::DenseSet<uint64_t> CopyDestroyCache;
82
Steve Naroffce8e8862008-03-15 00:55:56 +000083 unsigned NumObjCStringLiterals;
Mike Stump11289f42009-09-09 15:08:12 +000084
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000085 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +000086 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +000087 FunctionDecl *MsgSendStretFunctionDecl;
88 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian4f76f222007-12-03 21:26:48 +000089 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000090 FunctionDecl *GetClassFunctionDecl;
Steve Naroffb2f8ff12007-12-07 03:50:46 +000091 FunctionDecl *GetMetaClassFunctionDecl;
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +000092 FunctionDecl *GetSuperClassFunctionDecl;
Steve Naroff574440f2007-10-24 22:48:43 +000093 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff265a6b92007-11-08 14:30:50 +000094 FunctionDecl *CFStringFunctionDecl;
Steve Naroff17978c42008-03-11 17:37:02 +000095 FunctionDecl *SuperContructorFunctionDecl;
Mike Stump11289f42009-09-09 15:08:12 +000096
Steve Naroffa397efd2007-11-03 11:27:19 +000097 // ObjC string constant support.
Steve Naroff08899ff2008-04-15 22:42:06 +000098 VarDecl *ConstantStringClassReference;
Steve Naroffa397efd2007-11-03 11:27:19 +000099 RecordDecl *NSStringRecord;
Mike Stump11289f42009-09-09 15:08:12 +0000100
Fariborz Jahanian19d42bf2008-01-16 00:09:11 +0000101 // ObjC foreach break/continue generation support.
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000102 int BcLabelCount;
Mike Stump11289f42009-09-09 15:08:12 +0000103
Steve Naroff7fa2f042007-11-15 10:28:18 +0000104 // Needed for super.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000105 ObjCMethodDecl *CurMethodDef;
Steve Naroff7fa2f042007-11-15 10:28:18 +0000106 RecordDecl *SuperStructDecl;
Steve Naroffce8e8862008-03-15 00:55:56 +0000107 RecordDecl *ConstantStringDecl;
Mike Stump11289f42009-09-09 15:08:12 +0000108
Steve Naroffd9803712009-04-29 16:37:50 +0000109 TypeDecl *ProtocolTypeDecl;
110 QualType getProtocolType();
Mike Stump11289f42009-09-09 15:08:12 +0000111
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000112 // Needed for header files being rewritten
113 bool IsHeader;
Mike Stump11289f42009-09-09 15:08:12 +0000114
Steve Narofff9e7c902008-03-28 22:26:09 +0000115 std::string InFileName;
Eli Friedman94cf21e2009-05-18 22:20:00 +0000116 llvm::raw_ostream* OutFile;
Eli Friedmanf22439a2009-05-18 22:39:16 +0000117
118 bool SilenceRewriteMacroWarning;
Fariborz Jahanianbc6811c2010-01-07 22:51:18 +0000119 bool objc_impl_method;
Eli Friedmanf22439a2009-05-18 22:39:16 +0000120
Steve Naroff00a31762008-03-27 22:29:16 +0000121 std::string Preamble;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000122
123 // Block expressions.
124 llvm::SmallVector<BlockExpr *, 32> Blocks;
Fariborz Jahanian8652be02010-02-24 22:48:18 +0000125 llvm::SmallVector<int, 32> InnerDeclRefsCount;
126 llvm::SmallVector<BlockDeclRefExpr *, 32> InnerDeclRefs;
127
Steve Naroff677ab3a2008-10-27 17:20:55 +0000128 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
Mike Stump11289f42009-09-09 15:08:12 +0000129
Steve Naroff677ab3a2008-10-27 17:20:55 +0000130 // Block related declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +0000131 llvm::SmallVector<ValueDecl *, 8> BlockByCopyDecls;
132 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
133 llvm::SmallVector<ValueDecl *, 8> BlockByRefDecls;
134 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +0000135 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000136 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
Fariborz Jahanian3a106e72010-03-11 18:20:03 +0000137 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
138
Steve Naroff677ab3a2008-10-27 17:20:55 +0000139 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
140
Steve Naroff4588d0f2008-12-04 16:24:46 +0000141 // This maps a property to it's assignment statement.
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +0000142 llvm::DenseMap<Expr *, BinaryOperator *> PropSetters;
Steve Naroff1042ff32008-12-08 16:43:47 +0000143 // This maps a property to it's synthesied message expression.
144 // This allows us to rewrite chained getters (e.g. o.a.b.c).
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +0000145 llvm::DenseMap<Expr *, Stmt *> PropGetters;
Mike Stump11289f42009-09-09 15:08:12 +0000146
Steve Naroff22216db2008-12-04 23:50:32 +0000147 // This maps an original source AST to it's rewritten form. This allows
148 // us to avoid rewriting the same node twice (which is very uncommon).
149 // This is needed to support some of the exotic property rewriting.
150 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Narofff326f402008-12-03 00:56:33 +0000151
Steve Naroff677ab3a2008-10-27 17:20:55 +0000152 FunctionDecl *CurFunctionDef;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000153 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Steve Naroffd8907b72008-10-29 18:15:37 +0000154 VarDecl *GlobalVarDecl;
Mike Stump11289f42009-09-09 15:08:12 +0000155
Steve Naroff08628db2008-12-09 12:56:34 +0000156 bool DisableReplaceStmt;
Mike Stump11289f42009-09-09 15:08:12 +0000157
Nick Lewycky508ef2c2010-10-31 21:07:24 +0000158 static const int OBJC_ABI_VERSION = 7;
Chris Lattnere99c8322007-10-11 00:43:27 +0000159 public:
Ted Kremenek380df932008-05-31 20:11:04 +0000160 virtual void Initialize(ASTContext &context);
161
Chris Lattner3c799d72007-10-24 17:06:59 +0000162 // Top Level Driver code.
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000163 virtual void HandleTopLevelDecl(DeclGroupRef D) {
164 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
165 HandleTopLevelSingleDecl(*I);
166 }
167 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000168 void HandleDeclInMainFile(Decl *D);
Eli Friedman94cf21e2009-05-18 22:20:00 +0000169 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000170 Diagnostic &D, const LangOptions &LOpts,
171 bool silenceMacroWarn);
Ted Kremenek6231e7e2008-08-08 04:15:52 +0000172
173 ~RewriteObjC() {}
Mike Stump11289f42009-09-09 15:08:12 +0000174
Chris Lattnercf169832009-03-28 04:11:33 +0000175 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump11289f42009-09-09 15:08:12 +0000176
Fariborz Jahaniana7e1dcd2010-02-05 16:43:40 +0000177 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff22216db2008-12-04 23:50:32 +0000178 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump11289f42009-09-09 15:08:12 +0000179
Steve Naroff22216db2008-12-04 23:50:32 +0000180 if (ReplacingStmt)
181 return; // We can't rewrite the same node twice.
Chris Lattner2e0d2602008-01-31 19:37:57 +0000182
Steve Naroff08628db2008-12-09 12:56:34 +0000183 if (DisableReplaceStmt)
184 return; // Used when rewriting the assignment of a property setter.
185
Steve Naroff22216db2008-12-04 23:50:32 +0000186 // If replacement succeeded or warning disabled return with no warning.
Fariborz Jahaniana7e1dcd2010-02-05 16:43:40 +0000187 if (!Rewrite.ReplaceStmt(Old, New)) {
Steve Naroff22216db2008-12-04 23:50:32 +0000188 ReplacedNodes[Old] = New;
189 return;
190 }
191 if (SilenceRewriteMacroWarning)
192 return;
Chris Lattner8488c822008-11-18 07:04:44 +0000193 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
194 << Old->getSourceRange();
Chris Lattner2e0d2602008-01-31 19:37:57 +0000195 }
Steve Naroff08628db2008-12-09 12:56:34 +0000196
197 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
Nick Lewycky508ef2c2010-10-31 21:07:24 +0000198 // Measure the old text.
Steve Naroff08628db2008-12-09 12:56:34 +0000199 int Size = Rewrite.getRangeSize(SrcRange);
200 if (Size == -1) {
201 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
202 << Old->getSourceRange();
203 return;
204 }
205 // Get the new text.
206 std::string SStr;
207 llvm::raw_string_ostream S(SStr);
Chris Lattnerc61089a2009-06-30 01:26:17 +0000208 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroff08628db2008-12-09 12:56:34 +0000209 const std::string &Str = S.str();
210
211 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000212 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroff08628db2008-12-09 12:56:34 +0000213 ReplacedNodes[Old] = New;
214 return;
215 }
216 if (SilenceRewriteMacroWarning)
217 return;
218 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
219 << Old->getSourceRange();
220 }
221
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000222 void InsertText(SourceLocation Loc, llvm::StringRef Str,
Steve Naroff00a31762008-03-27 22:29:16 +0000223 bool InsertAfter = true) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000224 // If insertion succeeded or warning disabled return with no warning.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000225 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
Chris Lattner1780a852008-01-31 19:42:41 +0000226 SilenceRewriteMacroWarning)
227 return;
Mike Stump11289f42009-09-09 15:08:12 +0000228
Chris Lattner1780a852008-01-31 19:42:41 +0000229 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
230 }
Mike Stump11289f42009-09-09 15:08:12 +0000231
Chris Lattner9cc55f52008-01-31 19:51:04 +0000232 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000233 llvm::StringRef Str) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000234 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000235 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattner9cc55f52008-01-31 19:51:04 +0000236 SilenceRewriteMacroWarning)
237 return;
Mike Stump11289f42009-09-09 15:08:12 +0000238
Chris Lattner9cc55f52008-01-31 19:51:04 +0000239 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
240 }
Mike Stump11289f42009-09-09 15:08:12 +0000241
Chris Lattner3c799d72007-10-24 17:06:59 +0000242 // Syntactic Rewriting.
Fariborz Jahanian80258362008-01-19 00:30:35 +0000243 void RewriteInclude();
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000244 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffc038b3a2008-12-02 17:36:43 +0000245 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
246 ObjCImplementationDecl *IMD,
247 ObjCCategoryImplDecl *CID);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000248 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000249 void RewriteImplementationDecl(Decl *Dcl);
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000250 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
251 ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000252 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
253 const FunctionType *&FPRetType);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +0000254 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
255 ValueDecl *VD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000256 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
257 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
258 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
259 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000260 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000261 void RewriteFunctionDecl(FunctionDecl *FD);
Daniel Dunbar8ab6c542010-06-30 19:16:53 +0000262 void RewriteBlockPointerType(std::string& Str, QualType Type);
263 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000264 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000265 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +0000266 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff873bd842008-07-29 18:15:38 +0000267 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroff50d42052007-11-01 13:24:47 +0000268 bool needToScanForQualifiers(QualType T);
Steve Naroff7fa2f042007-11-15 10:28:18 +0000269 QualType getSuperStructType();
Steve Naroffce8e8862008-03-15 00:55:56 +0000270 QualType getConstantStringStructType();
Fariborz Jahanian19c62402010-05-25 15:56:08 +0000271 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
Steve Naroffcd92aeb2008-05-31 14:15:04 +0000272 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump11289f42009-09-09 15:08:12 +0000273
Chris Lattner3c799d72007-10-24 17:06:59 +0000274 // Expression Rewriting.
Steve Naroff20113382007-11-09 15:20:18 +0000275 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroff4588d0f2008-12-04 16:24:46 +0000276 void CollectPropertySetters(Stmt *S);
Mike Stump11289f42009-09-09 15:08:12 +0000277
Steve Naroff1042ff32008-12-08 16:43:47 +0000278 Stmt *CurrentBody;
279 ParentMap *PropParentMap; // created lazily.
Mike Stump11289f42009-09-09 15:08:12 +0000280
Chris Lattner69534692007-10-24 16:57:36 +0000281 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +0000282 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart,
283 bool &replaced);
284 Stmt *RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +0000285 Stmt *RewritePropertyOrImplicitGetter(Expr *PropOrGetterRefExpr);
286 Stmt *RewritePropertyOrImplicitSetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroff08628db2008-12-09 12:56:34 +0000287 SourceRange SrcRange);
Steve Naroffe4f9b232007-11-05 14:50:49 +0000288 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner69534692007-10-24 16:57:36 +0000289 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffa397efd2007-11-03 11:27:19 +0000290 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian33c0e812007-12-07 18:47:10 +0000291 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffec60b432009-12-05 21:43:12 +0000292 void WarnAboutReturnGotoStmts(Stmt *S);
293 void HasReturnStmts(Stmt *S, bool &hasReturns);
294 void RewriteTryReturnStmts(Stmt *S);
295 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000296 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian284011b2008-01-29 22:59:37 +0000297 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000298 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattnera779d692008-01-31 05:10:40 +0000299 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
300 SourceLocation OrigEnd);
Mike Stump11289f42009-09-09 15:08:12 +0000301 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +0000302 Expr **args, unsigned nargs,
303 SourceLocation StartLoc=SourceLocation(),
304 SourceLocation EndLoc=SourceLocation());
305 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
306 SourceLocation StartLoc=SourceLocation(),
307 SourceLocation EndLoc=SourceLocation());
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000308 Stmt *RewriteBreakStmt(BreakStmt *S);
309 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian965a8962008-01-08 22:06:28 +0000310 void SynthCountByEnumWithState(std::string &buf);
Mike Stump11289f42009-09-09 15:08:12 +0000311
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000312 void SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +0000313 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000314 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +0000315 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000316 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000317 void SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +0000318 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +0000319 void SynthGetSuperClassFunctionDecl();
Fariborz Jahanian31e18502007-12-04 21:47:40 +0000320 void SynthSelGetUidFunctionDecl();
Steve Naroff17978c42008-03-11 17:37:02 +0000321 void SynthSuperContructorFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000322
Chris Lattner3c799d72007-10-24 17:06:59 +0000323 // Metadata emission.
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000324 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000325 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000326
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000327 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000328 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000329
Douglas Gregor29bd76f2009-04-23 01:02:12 +0000330 template<typename MethodIterator>
331 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
332 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +0000333 bool IsInstanceMethod,
Daniel Dunbar56df9772010-08-17 22:39:59 +0000334 llvm::StringRef prefix,
335 llvm::StringRef ClassName,
Chris Lattner211f8b82007-10-25 17:07:24 +0000336 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000337
Steve Naroffd9803712009-04-29 16:37:50 +0000338 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
Daniel Dunbar56df9772010-08-17 22:39:59 +0000339 llvm::StringRef prefix,
340 llvm::StringRef ClassName,
Steve Naroffd9803712009-04-29 16:37:50 +0000341 std::string &Result);
342 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Daniel Dunbar56df9772010-08-17 22:39:59 +0000343 llvm::StringRef prefix,
344 llvm::StringRef ClassName,
Steve Naroffd9803712009-04-29 16:37:50 +0000345 std::string &Result);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000346 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000347 std::string &Result);
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000348 void SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000349 std::string &Result);
Steve Narofff8cfd162008-11-13 20:07:04 +0000350 void RewriteImplementations();
351 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000352
Steve Naroff677ab3a2008-10-27 17:20:55 +0000353 // Block rewriting.
Mike Stump11289f42009-09-09 15:08:12 +0000354 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000355 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump11289f42009-09-09 15:08:12 +0000356
Steve Naroff677ab3a2008-10-27 17:20:55 +0000357 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
358 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump11289f42009-09-09 15:08:12 +0000359
360 // Block specific rewrite rules.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000361 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000362 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahaniane3891582010-01-05 18:04:40 +0000363 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +0000364 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +0000365 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000366 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump11289f42009-09-09 15:08:12 +0000367
368 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Daniel Dunbar56df9772010-08-17 22:39:59 +0000369 llvm::StringRef funcName, std::string Tag);
Mike Stump11289f42009-09-09 15:08:12 +0000370 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Daniel Dunbar56df9772010-08-17 22:39:59 +0000371 llvm::StringRef funcName, std::string Tag);
Steve Naroff30484702009-12-06 21:14:13 +0000372 std::string SynthesizeBlockImpl(BlockExpr *CE,
373 std::string Tag, std::string Desc);
374 std::string SynthesizeBlockDescriptor(std::string DescTag,
375 std::string ImplTag,
Daniel Dunbar56df9772010-08-17 22:39:59 +0000376 int i, llvm::StringRef funcName,
Steve Naroff30484702009-12-06 21:14:13 +0000377 unsigned hasCopy);
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +0000378 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000379 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Daniel Dunbar56df9772010-08-17 22:39:59 +0000380 llvm::StringRef FunName);
Steve Naroffe70a52a2009-12-05 15:55:59 +0000381 void RewriteRecordBody(RecordDecl *RD);
Mike Stump11289f42009-09-09 15:08:12 +0000382
Steve Naroff677ab3a2008-10-27 17:20:55 +0000383 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000384 void GetBlockDeclRefExprs(Stmt *S);
Fariborz Jahanian8652be02010-02-24 22:48:18 +0000385 void GetInnerBlockDeclRefExprs(Stmt *S,
386 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +0000387 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
Mike Stump11289f42009-09-09 15:08:12 +0000388
Steve Naroff677ab3a2008-10-27 17:20:55 +0000389 // We avoid calling Type::isBlockPointerType(), since it operates on the
390 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek5a201952009-02-07 01:47:29 +0000391 bool isTopLevelBlockPointerType(QualType T) {
392 return isa<BlockPointerType>(T);
393 }
Mike Stump11289f42009-09-09 15:08:12 +0000394
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +0000395 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
396 /// to a function pointer type and upon success, returns true; false
397 /// otherwise.
398 bool convertBlockPointerToFunctionPointer(QualType &T) {
399 if (isTopLevelBlockPointerType(T)) {
400 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
401 T = Context->getPointerType(BPT->getPointeeType());
402 return true;
403 }
404 return false;
405 }
406
Fariborz Jahanian90d2e572010-11-05 18:34:46 +0000407 void convertToUnqualifiedObjCType(QualType &T) {
408 if (T->isObjCQualifiedIdType())
409 T = Context->getObjCIdType();
410 else if (T->isObjCQualifiedClassType())
411 T = Context->getObjCClassType();
412 else if (T->isObjCObjectPointerType() &&
413 T->getPointeeType()->isObjCQualifiedInterfaceType())
414 T = Context->getObjCIdType();
415 }
416
Steve Naroff677ab3a2008-10-27 17:20:55 +0000417 // FIXME: This predicate seems like it would be useful to add to ASTContext.
418 bool isObjCType(QualType T) {
419 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
420 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000421
Steve Naroff677ab3a2008-10-27 17:20:55 +0000422 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000423
Steve Naroff677ab3a2008-10-27 17:20:55 +0000424 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
425 OCT == Context->getCanonicalType(Context->getObjCClassType()))
426 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000427
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000428 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +0000429 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Narofffb4330f2009-06-17 22:40:22 +0000430 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff677ab3a2008-10-27 17:20:55 +0000431 return true;
432 }
433 return false;
434 }
435 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +0000436 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
Ted Kremenek5a201952009-02-07 01:47:29 +0000437 void GetExtentOfArgList(const char *Name, const char *&LParen,
438 const char *&RParen);
Steve Naroffc989a7b2008-11-03 23:29:32 +0000439 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump11289f42009-09-09 15:08:12 +0000440
Daniel Dunbar56df9772010-08-17 22:39:59 +0000441 FunctionDecl *SynthBlockInitFunctionDecl(llvm::StringRef name);
Fariborz Jahanian8652be02010-02-24 22:48:18 +0000442 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
443 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
Mike Stump11289f42009-09-09 15:08:12 +0000444
Steve Naroffd9803712009-04-29 16:37:50 +0000445 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump11289f42009-09-09 15:08:12 +0000446 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroffd9803712009-04-29 16:37:50 +0000447 if (From[i] == '"')
448 To += "\\\"";
449 else
450 To += From[i];
451 }
452 }
Chris Lattnere99c8322007-10-11 00:43:27 +0000453 };
John McCall97513962010-01-15 18:39:57 +0000454
455 // Helper function: create a CStyleCastExpr with trivial type source info.
456 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +0000457 CastKind Kind, Expr *E) {
John McCall97513962010-01-15 18:39:57 +0000458 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
John McCall7decc9e2010-11-18 06:31:45 +0000459 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
John McCallcf142162010-08-07 06:22:56 +0000460 SourceLocation(), SourceLocation());
John McCall97513962010-01-15 18:39:57 +0000461 }
Chris Lattnere99c8322007-10-11 00:43:27 +0000462}
463
Mike Stump11289f42009-09-09 15:08:12 +0000464void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
465 NamedDecl *D) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000466 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000467 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +0000468 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +0000469 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +0000470 // All the args are checked/rewritten. Don't call twice!
471 RewriteBlockPointerDecl(D);
472 break;
473 }
474 }
475}
476
477void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000478 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +0000479 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000480 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000481}
482
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000483static bool IsHeaderFile(const std::string &Filename) {
484 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump11289f42009-09-09 15:08:12 +0000485
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000486 if (DotPos == std::string::npos) {
487 // no file extension
Mike Stump11289f42009-09-09 15:08:12 +0000488 return false;
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000489 }
Mike Stump11289f42009-09-09 15:08:12 +0000490
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000491 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
492 // C header: .h
493 // C++ header: .hh or .H;
494 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump11289f42009-09-09 15:08:12 +0000495}
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000496
Eli Friedman94cf21e2009-05-18 22:20:00 +0000497RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000498 Diagnostic &D, const LangOptions &LOpts,
499 bool silenceMacroWarn)
500 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
501 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Narofff9e7c902008-03-28 22:26:09 +0000502 IsHeader = IsHeaderFile(inFile);
Mike Stump11289f42009-09-09 15:08:12 +0000503 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Narofff9e7c902008-03-28 22:26:09 +0000504 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump11289f42009-09-09 15:08:12 +0000505 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek5a201952009-02-07 01:47:29 +0000506 "rewriter doesn't support user-specified control flow semantics "
507 "for @try/@finally (code may not execute properly)");
Steve Narofff9e7c902008-03-28 22:26:09 +0000508}
509
Eli Friedmana63ab2d2009-05-18 22:29:17 +0000510ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
511 llvm::raw_ostream* OS,
Mike Stump11289f42009-09-09 15:08:12 +0000512 Diagnostic &Diags,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000513 const LangOptions &LOpts,
514 bool SilenceRewriteMacroWarning) {
515 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere9c810c2007-11-30 22:25:36 +0000516}
Chris Lattnere99c8322007-10-11 00:43:27 +0000517
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000518void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner187f6262008-01-31 19:38:44 +0000519 Context = &context;
520 SM = &Context->getSourceManager();
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +0000521 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner187f6262008-01-31 19:38:44 +0000522 MsgSendFunctionDecl = 0;
523 MsgSendSuperFunctionDecl = 0;
524 MsgSendStretFunctionDecl = 0;
525 MsgSendSuperStretFunctionDecl = 0;
526 MsgSendFpretFunctionDecl = 0;
527 GetClassFunctionDecl = 0;
528 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +0000529 GetSuperClassFunctionDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000530 SelGetUidFunctionDecl = 0;
531 CFStringFunctionDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000532 ConstantStringClassReference = 0;
533 NSStringRecord = 0;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000534 CurMethodDef = 0;
535 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000536 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000537 GlobalVarDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000538 SuperStructDecl = 0;
Steve Naroffd9803712009-04-29 16:37:50 +0000539 ProtocolTypeDecl = 0;
Steve Naroff60a9ef62008-03-27 22:59:54 +0000540 ConstantStringDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000541 BcLabelCount = 0;
Steve Naroff17978c42008-03-11 17:37:02 +0000542 SuperContructorFunctionDecl = 0;
Steve Naroffce8e8862008-03-15 00:55:56 +0000543 NumObjCStringLiterals = 0;
Steve Narofff1ab6002008-12-08 20:01:41 +0000544 PropParentMap = 0;
545 CurrentBody = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000546 DisableReplaceStmt = false;
Fariborz Jahanianbc6811c2010-01-07 22:51:18 +0000547 objc_impl_method = false;
Mike Stump11289f42009-09-09 15:08:12 +0000548
Chris Lattner187f6262008-01-31 19:38:44 +0000549 // Get the ID and start/end of the main file.
550 MainFileID = SM->getMainFileID();
551 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
552 MainFileStart = MainBuf->getBufferStart();
553 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000554
Chris Lattner184e65d2009-04-14 23:22:57 +0000555 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump11289f42009-09-09 15:08:12 +0000556
Chris Lattner187f6262008-01-31 19:38:44 +0000557 // declaring objc_selector outside the parameter list removes a silly
558 // scope related warning...
Steve Naroff00a31762008-03-27 22:29:16 +0000559 if (IsHeader)
Steve Narofffcc6fd52009-02-03 20:39:18 +0000560 Preamble = "#pragma once\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000561 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff6ab6dc72008-12-23 20:11:22 +0000562 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroff00a31762008-03-27 22:29:16 +0000563 Preamble += "struct objc_object *superClass; ";
Steve Naroff17978c42008-03-11 17:37:02 +0000564 if (LangOpts.Microsoft) {
565 // Add a constructor for creating temporary objects.
Ted Kremenek5a201952009-02-07 01:47:29 +0000566 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
567 ": ";
Steve Naroff00a31762008-03-27 22:29:16 +0000568 Preamble += "object(o), superClass(s) {} ";
Steve Naroff17978c42008-03-11 17:37:02 +0000569 }
Steve Naroff00a31762008-03-27 22:29:16 +0000570 Preamble += "};\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000571 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
572 Preamble += "typedef struct objc_object Protocol;\n";
573 Preamble += "#define _REWRITER_typedef_Protocol\n";
574 Preamble += "#endif\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000575 if (LangOpts.Microsoft) {
576 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
577 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
578 } else
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000579 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000580 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroff00a31762008-03-27 22:29:16 +0000581 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000582 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroff00a31762008-03-27 22:29:16 +0000583 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000584 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000585 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000586 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000587 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000588 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroff00a31762008-03-27 22:29:16 +0000589 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000590 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000591 Preamble += "(const char *);\n";
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +0000592 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
593 Preamble += "(struct objc_class *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000594 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000595 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000596 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
597 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
598 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
599 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
600 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroffd30f8c52008-05-09 21:17:56 +0000601 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff8dd15252008-07-16 18:58:11 +0000602 // @synchronized hooks.
Steve Narofff122ff02008-12-08 17:30:33 +0000603 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
604 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
605 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000606 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
607 Preamble += "struct __objcFastEnumerationState {\n\t";
608 Preamble += "unsigned long state;\n\t";
Steve Naroff4dbab8a2008-04-04 22:58:22 +0000609 Preamble += "void **itemsPtr;\n\t";
Steve Naroff00a31762008-03-27 22:29:16 +0000610 Preamble += "unsigned long *mutationsPtr;\n\t";
611 Preamble += "unsigned long extra[5];\n};\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000612 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000613 Preamble += "#define __FASTENUMERATIONSTATE\n";
614 Preamble += "#endif\n";
615 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
616 Preamble += "struct __NSConstantStringImpl {\n";
617 Preamble += " int *isa;\n";
618 Preamble += " int flags;\n";
619 Preamble += " char *str;\n";
620 Preamble += " long length;\n";
621 Preamble += "};\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000622 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
623 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
624 Preamble += "#else\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000625 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000626 Preamble += "#endif\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000627 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
628 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000629 // Blocks preamble.
630 Preamble += "#ifndef BLOCK_IMPL\n";
631 Preamble += "#define BLOCK_IMPL\n";
632 Preamble += "struct __block_impl {\n";
633 Preamble += " void *isa;\n";
634 Preamble += " int Flags;\n";
Steve Naroff30484702009-12-06 21:14:13 +0000635 Preamble += " int Reserved;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000636 Preamble += " void *FuncPtr;\n";
637 Preamble += "};\n";
Steve Naroff61d879e2008-12-16 15:50:30 +0000638 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroff287a2bf2009-12-06 01:52:22 +0000639 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000640 Preamble += "extern \"C\" __declspec(dllexport) "
641 "void _Block_object_assign(void *, const void *, const int);\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000642 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
643 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
644 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
645 Preamble += "#else\n";
Steve Naroff7bf01ea2010-01-05 18:09:31 +0000646 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
647 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000648 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
649 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
650 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000651 Preamble += "#endif\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000652 if (LangOpts.Microsoft) {
Steve Narofff122ff02008-12-08 17:30:33 +0000653 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
654 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Chris Lattner8d269dc2010-04-13 17:33:56 +0000655 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
Steve Naroffcb04e882008-10-27 18:50:14 +0000656 Preamble += "#define __attribute__(X)\n";
Chris Lattner8d269dc2010-04-13 17:33:56 +0000657 Preamble += "#endif\n";
Fariborz Jahanianf0462ff2010-01-15 22:29:39 +0000658 Preamble += "#define __weak\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000659 }
Fariborz Jahanian7fac6552010-01-05 19:21:35 +0000660 else {
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000661 Preamble += "#define __block\n";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +0000662 Preamble += "#define __weak\n";
663 }
Fariborz Jahaniandb217c42010-03-02 01:19:04 +0000664 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
665 // as this avoids warning in any 64bit/32bit compilation model.
666 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
Chris Lattner187f6262008-01-31 19:38:44 +0000667}
668
669
Chris Lattner3c799d72007-10-24 17:06:59 +0000670//===----------------------------------------------------------------------===//
671// Top Level Driver Code
672//===----------------------------------------------------------------------===//
673
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000674void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremenek31e7f0f2010-02-05 21:28:51 +0000675 if (Diags.hasErrorOccurred())
676 return;
677
Chris Lattner0bd1c972007-10-16 21:07:07 +0000678 // Two cases: either the decl could be in the main file, or it could be in a
679 // #included file. If the former, rewrite it now. If the later, check to see
680 // if we rewrote the #include/#import.
681 SourceLocation Loc = D->getLocation();
Chris Lattner8a425862009-01-16 07:36:28 +0000682 Loc = SM->getInstantiationLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000683
Chris Lattner0bd1c972007-10-16 21:07:07 +0000684 // If this is for a builtin, ignore it.
685 if (Loc.isInvalid()) return;
686
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000687 // Look for built-in declarations that we need to refer during the rewrite.
688 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000689 RewriteFunctionDecl(FD);
Steve Naroff08899ff2008-04-15 22:42:06 +0000690 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000691 // declared in <Foundation/NSString.h>
Daniel Dunbar56df9772010-08-17 22:39:59 +0000692 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffa397efd2007-11-03 11:27:19 +0000693 ConstantStringClassReference = FVD;
694 return;
695 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000696 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff161a92b2007-10-26 20:53:56 +0000697 RewriteInterfaceDecl(MD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000698 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000699 RewriteCategoryDecl(CD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000700 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff921385f2007-10-30 16:42:30 +0000701 RewriteProtocolDecl(PD);
Mike Stump11289f42009-09-09 15:08:12 +0000702 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000703 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000704 RewriteForwardProtocolDecl(FP);
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000705 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
706 // Recurse into linkage specifications
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000707 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
708 DIEnd = LSD->decls_end();
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000709 DI != DIEnd; ++DI)
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000710 HandleTopLevelSingleDecl(*DI);
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000711 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000712 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekd61ed3b2008-04-14 21:24:13 +0000713 if (SM->isFromMainFile(Loc))
Chris Lattner0bd1c972007-10-16 21:07:07 +0000714 return HandleDeclInMainFile(D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000715}
716
Chris Lattner3c799d72007-10-24 17:06:59 +0000717//===----------------------------------------------------------------------===//
718// Syntactic (non-AST) Rewriting Code
719//===----------------------------------------------------------------------===//
720
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000721void RewriteObjC::RewriteInclude() {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000722 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000723 llvm::StringRef MainBuf = SM->getBufferData(MainFileID);
724 const char *MainBufStart = MainBuf.begin();
725 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian80258362008-01-19 00:30:35 +0000726 size_t ImportLen = strlen("import");
Mike Stump11289f42009-09-09 15:08:12 +0000727
Fariborz Jahanian137d6932008-01-19 01:03:17 +0000728 // Loop over the whole file, looking for includes.
Fariborz Jahanian80258362008-01-19 00:30:35 +0000729 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
730 if (*BufPtr == '#') {
731 if (++BufPtr == MainBufEnd)
732 return;
733 while (*BufPtr == ' ' || *BufPtr == '\t')
734 if (++BufPtr == MainBufEnd)
735 return;
736 if (!strncmp(BufPtr, "import", ImportLen)) {
737 // replace import with include
Mike Stump11289f42009-09-09 15:08:12 +0000738 SourceLocation ImportLoc =
Fariborz Jahanian80258362008-01-19 00:30:35 +0000739 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000740 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian80258362008-01-19 00:30:35 +0000741 BufPtr += ImportLen;
742 }
743 }
744 }
Chris Lattner0bd1c972007-10-16 21:07:07 +0000745}
746
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000747static std::string getIvarAccessString(ObjCIvarDecl *OID) {
748 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroff9af94912008-12-02 15:48:25 +0000749 std::string S;
750 S = "((struct ";
751 S += ClassDecl->getIdentifier()->getName();
752 S += "_IMPL *)self)->";
Daniel Dunbar70e7ead2009-10-18 20:26:27 +0000753 S += OID->getName();
Steve Naroff9af94912008-12-02 15:48:25 +0000754 return S;
755}
756
Steve Naroffc038b3a2008-12-02 17:36:43 +0000757void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
758 ObjCImplementationDecl *IMD,
759 ObjCCategoryImplDecl *CID) {
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000760 static bool objcGetPropertyDefined = false;
761 static bool objcSetPropertyDefined = false;
Steve Naroffe1908e32008-12-01 20:33:01 +0000762 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000763 InsertText(startLoc, "// ");
Steve Naroff9af94912008-12-02 15:48:25 +0000764 const char *startBuf = SM->getCharacterData(startLoc);
765 assert((*startBuf == '@') && "bogus @synthesize location");
766 const char *semiBuf = strchr(startBuf, ';');
767 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek5a201952009-02-07 01:47:29 +0000768 SourceLocation onePastSemiLoc =
769 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroff9af94912008-12-02 15:48:25 +0000770
771 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
772 return; // FIXME: is this correct?
Mike Stump11289f42009-09-09 15:08:12 +0000773
Steve Naroff9af94912008-12-02 15:48:25 +0000774 // Generate the 'getter' function.
Steve Naroff9af94912008-12-02 15:48:25 +0000775 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroff9af94912008-12-02 15:48:25 +0000776 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000777
Steve Naroff003d00e2008-12-02 16:05:55 +0000778 if (!OID)
779 return;
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000780 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000781 if (!PD->getGetterMethodDecl()->isDefined()) {
782 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
783 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
784 ObjCPropertyDecl::OBJC_PR_copy));
785 std::string Getr;
786 if (GenGetProperty && !objcGetPropertyDefined) {
787 objcGetPropertyDefined = true;
788 // FIXME. Is this attribute correct in all cases?
789 Getr = "\nextern \"C\" __declspec(dllimport) "
790 "id objc_getProperty(id, SEL, long, bool);\n";
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000791 }
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000792 RewriteObjCMethodDecl(OID->getContainingInterface(),
793 PD->getGetterMethodDecl(), Getr);
794 Getr += "{ ";
795 // Synthesize an explicit cast to gain access to the ivar.
796 // See objc-act.c:objc_synthesize_new_getter() for details.
797 if (GenGetProperty) {
798 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
799 Getr += "typedef ";
800 const FunctionType *FPRetType = 0;
801 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
802 FPRetType);
803 Getr += " _TYPE";
804 if (FPRetType) {
805 Getr += ")"; // close the precedence "scope" for "*".
806
807 // Now, emit the argument types (if any).
808 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
809 Getr += "(";
810 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
811 if (i) Getr += ", ";
812 std::string ParamStr = FT->getArgType(i).getAsString(
813 Context->PrintingPolicy);
814 Getr += ParamStr;
815 }
816 if (FT->isVariadic()) {
817 if (FT->getNumArgs()) Getr += ", ";
818 Getr += "...";
819 }
820 Getr += ")";
821 } else
822 Getr += "()";
823 }
824 Getr += ";\n";
825 Getr += "return (_TYPE)";
826 Getr += "objc_getProperty(self, _cmd, ";
827 SynthesizeIvarOffsetComputation(OID, Getr);
828 Getr += ", 1)";
829 }
830 else
831 Getr += "return " + getIvarAccessString(OID);
832 Getr += "; }";
833 InsertText(onePastSemiLoc, Getr);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000834 }
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000835
836 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
Steve Naroff9af94912008-12-02 15:48:25 +0000837 return;
Mike Stump11289f42009-09-09 15:08:12 +0000838
Steve Naroff9af94912008-12-02 15:48:25 +0000839 // Generate the 'setter' function.
840 std::string Setr;
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000841 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
842 ObjCPropertyDecl::OBJC_PR_copy);
843 if (GenSetProperty && !objcSetPropertyDefined) {
844 objcSetPropertyDefined = true;
845 // FIXME. Is this attribute correct in all cases?
846 Setr = "\nextern \"C\" __declspec(dllimport) "
847 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
848 }
849
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000850 RewriteObjCMethodDecl(OID->getContainingInterface(),
851 PD->getSetterMethodDecl(), Setr);
Steve Naroff9af94912008-12-02 15:48:25 +0000852 Setr += "{ ";
Steve Naroff003d00e2008-12-02 16:05:55 +0000853 // Synthesize an explicit cast to initialize the ivar.
Steve Narofff326f402008-12-03 00:56:33 +0000854 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000855 if (GenSetProperty) {
856 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000857 SynthesizeIvarOffsetComputation(OID, Setr);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000858 Setr += ", (id)";
Daniel Dunbar56df9772010-08-17 22:39:59 +0000859 Setr += PD->getName();
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000860 Setr += ", ";
861 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
862 Setr += "0, ";
863 else
864 Setr += "1, ";
865 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
866 Setr += "1)";
867 else
868 Setr += "0)";
869 }
870 else {
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000871 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar56df9772010-08-17 22:39:59 +0000872 Setr += PD->getName();
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000873 }
Steve Naroff003d00e2008-12-02 16:05:55 +0000874 Setr += "; }";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000875 InsertText(onePastSemiLoc, Setr);
Steve Naroffe1908e32008-12-01 20:33:01 +0000876}
Chris Lattner16a0de42007-10-11 18:38:32 +0000877
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000878void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattner3c799d72007-10-24 17:06:59 +0000879 // Get the start location and compute the semi location.
880 SourceLocation startLoc = ClassDecl->getLocation();
881 const char *startBuf = SM->getCharacterData(startLoc);
882 const char *semiPtr = strchr(startBuf, ';');
Mike Stump11289f42009-09-09 15:08:12 +0000883
Chris Lattner3c799d72007-10-24 17:06:59 +0000884 // Translate to typedef's that forward reference structs with the same name
885 // as the class. As a convenience, we include the original declaration
886 // as a comment.
887 std::string typedefString;
Fariborz Jahanian1c2cb6d2010-01-11 22:48:40 +0000888 typedefString += "// @class ";
889 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
890 I != E; ++I) {
891 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
892 typedefString += ForwardDecl->getNameAsString();
893 if (I+1 != E)
894 typedefString += ", ";
895 else
896 typedefString += ";\n";
897 }
898
Chris Lattner9ee23b72009-02-20 18:04:31 +0000899 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
900 I != E; ++I) {
Ted Kremenek9b124e12009-11-18 00:28:11 +0000901 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff1b232132007-11-09 12:50:28 +0000902 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000903 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000904 typedefString += "\n";
905 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000906 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000907 typedefString += "\n";
Steve Naroff98eb8d12007-11-05 14:36:37 +0000908 typedefString += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000909 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000910 typedefString += ";\n#endif\n";
Steve Naroff574440f2007-10-24 22:48:43 +0000911 }
Mike Stump11289f42009-09-09 15:08:12 +0000912
Steve Naroff574440f2007-10-24 22:48:43 +0000913 // Replace the @class with typedefs corresponding to the classes.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000914 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
Chris Lattner3c799d72007-10-24 17:06:59 +0000915}
916
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000917void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000918 // When method is a synthesized one, such as a getter/setter there is
919 // nothing to rewrite.
920 if (Method->isSynthesized())
921 return;
Steve Naroff3ce37a62007-12-14 23:37:57 +0000922 SourceLocation LocStart = Method->getLocStart();
923 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000924
Chris Lattner88ea93e2009-02-04 01:06:56 +0000925 if (SM->getInstantiationLineNumber(LocEnd) >
926 SM->getInstantiationLineNumber(LocStart)) {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000927 InsertText(LocStart, "#if 0\n");
928 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff3ce37a62007-12-14 23:37:57 +0000929 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000930 InsertText(LocStart, "// ");
Steve Naroff5448cf62007-10-30 13:30:57 +0000931 }
932}
933
Mike Stump11289f42009-09-09 15:08:12 +0000934void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000935 SourceLocation Loc = prop->getAtLoc();
Mike Stump11289f42009-09-09 15:08:12 +0000936
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000937 ReplaceText(Loc, 0, "// ");
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000938 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahaniane8a30162007-11-07 00:09:37 +0000939}
940
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000941void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000942 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000943
Steve Naroff5448cf62007-10-30 13:30:57 +0000944 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000945 ReplaceText(LocStart, 0, "// ");
Mike Stump11289f42009-09-09 15:08:12 +0000946
Fariborz Jahanian68ebe632010-02-10 01:15:09 +0000947 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
948 E = CatDecl->prop_end(); I != E; ++I)
949 RewriteProperty(*I);
950
Mike Stump11289f42009-09-09 15:08:12 +0000951 for (ObjCCategoryDecl::instmeth_iterator
952 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000953 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000954 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +0000955 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000956 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000957 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000958 RewriteMethodDeclaration(*I);
959
Steve Naroff5448cf62007-10-30 13:30:57 +0000960 // Lastly, comment out the @end.
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +0000961 ReplaceText(CatDecl->getAtEndRange().getBegin(),
962 strlen("@end"), "/* @end */");
Steve Naroff5448cf62007-10-30 13:30:57 +0000963}
964
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000965void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Narofff921385f2007-10-30 16:42:30 +0000966 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000967
Steve Narofff921385f2007-10-30 16:42:30 +0000968 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000969 ReplaceText(LocStart, 0, "// ");
Mike Stump11289f42009-09-09 15:08:12 +0000970
971 for (ObjCProtocolDecl::instmeth_iterator
972 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000973 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000974 RewriteMethodDeclaration(*I);
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000975 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000976 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000977 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000978 RewriteMethodDeclaration(*I);
979
Fariborz Jahanianaa0f2b32010-09-24 18:36:58 +0000980 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
981 E = PDecl->prop_end(); I != E; ++I)
982 RewriteProperty(*I);
983
Steve Narofff921385f2007-10-30 16:42:30 +0000984 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +0000985 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +0000986 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroffa509f042007-11-14 15:03:57 +0000987
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000988 // Must comment out @optional/@required
989 const char *startBuf = SM->getCharacterData(LocStart);
990 const char *endBuf = SM->getCharacterData(LocEnd);
991 for (const char *p = startBuf; p < endBuf; p++) {
992 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Steve Naroffa509f042007-11-14 15:03:57 +0000993 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000994 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump11289f42009-09-09 15:08:12 +0000995
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000996 }
997 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Steve Naroffa509f042007-11-14 15:03:57 +0000998 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000999 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump11289f42009-09-09 15:08:12 +00001000
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +00001001 }
1002 }
Steve Narofff921385f2007-10-30 16:42:30 +00001003}
1004
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001005void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanianda6165c2007-11-14 00:42:16 +00001006 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffc17b0562007-11-14 03:37:28 +00001007 if (LocStart.isInvalid())
1008 assert(false && "Invalid SourceLocation");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +00001009 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001010 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +00001011}
1012
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001013void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1014 const FunctionType *&FPRetType) {
1015 if (T->isObjCQualifiedIdType())
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +00001016 ResultStr += "id";
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001017 else if (T->isFunctionPointerType() ||
1018 T->isBlockPointerType()) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001019 // needs special handling, since pointer-to-functions have special
1020 // syntax (where a decaration models use).
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001021 QualType retType = T;
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001022 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001023 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001024 PointeeTy = PT->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001025 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001026 PointeeTy = BPT->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00001027 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001028 ResultStr += FPRetType->getResultType().getAsString(
1029 Context->PrintingPolicy);
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001030 ResultStr += "(*";
Steve Naroffb067bbd2008-07-16 14:40:40 +00001031 }
1032 } else
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001033 ResultStr += T.getAsString(Context->PrintingPolicy);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001034}
1035
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001036void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1037 ObjCMethodDecl *OMD,
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001038 std::string &ResultStr) {
1039 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1040 const FunctionType *FPRetType = 0;
1041 ResultStr += "\nstatic ";
1042 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001043 ResultStr += " ";
Mike Stump11289f42009-09-09 15:08:12 +00001044
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001045 // Unique method name
Fariborz Jahanian56338352007-11-13 21:02:00 +00001046 std::string NameStr;
Mike Stump11289f42009-09-09 15:08:12 +00001047
Douglas Gregorffca3a22009-01-09 17:18:27 +00001048 if (OMD->isInstanceMethod())
Fariborz Jahanian56338352007-11-13 21:02:00 +00001049 NameStr += "_I_";
1050 else
1051 NameStr += "_C_";
Mike Stump11289f42009-09-09 15:08:12 +00001052
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001053 NameStr += IDecl->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +00001054 NameStr += "_";
Mike Stump11289f42009-09-09 15:08:12 +00001055
1056 if (ObjCCategoryImplDecl *CID =
Steve Naroff11b387f2009-01-08 19:41:02 +00001057 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001058 NameStr += CID->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +00001059 NameStr += "_";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001060 }
Mike Stump11289f42009-09-09 15:08:12 +00001061 // Append selector names, replacing ':' with '_'
Chris Lattnere4b95692008-11-24 03:33:13 +00001062 {
1063 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001064 int len = selString.size();
1065 for (int i = 0; i < len; i++)
1066 if (selString[i] == ':')
1067 selString[i] = '_';
Fariborz Jahanian56338352007-11-13 21:02:00 +00001068 NameStr += selString;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001069 }
Fariborz Jahanian56338352007-11-13 21:02:00 +00001070 // Remember this name for metadata emission
1071 MethodInternalNames[OMD] = NameStr;
1072 ResultStr += NameStr;
Mike Stump11289f42009-09-09 15:08:12 +00001073
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001074 // Rewrite arguments
1075 ResultStr += "(";
Mike Stump11289f42009-09-09 15:08:12 +00001076
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001077 // invisible arguments
Douglas Gregorffca3a22009-01-09 17:18:27 +00001078 if (OMD->isInstanceMethod()) {
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001079 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001080 selfTy = Context->getPointerType(selfTy);
Steve Naroffdc5b6b22008-03-12 00:25:36 +00001081 if (!LangOpts.Microsoft) {
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001082 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroffdc5b6b22008-03-12 00:25:36 +00001083 ResultStr += "struct ";
1084 }
1085 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001086 ResultStr += IDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00001087 ResultStr += " *";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001088 }
1089 else
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001090 ResultStr += Context->getObjCClassType().getAsString(
1091 Context->PrintingPolicy);
Mike Stump11289f42009-09-09 15:08:12 +00001092
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001093 ResultStr += " self, ";
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001094 ResultStr += Context->getObjCSelType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001095 ResultStr += " _cmd";
Mike Stump11289f42009-09-09 15:08:12 +00001096
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001097 // Method arguments.
Chris Lattnera4997152009-02-20 18:43:26 +00001098 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1099 E = OMD->param_end(); PI != E; ++PI) {
1100 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001101 ResultStr += ", ";
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001102 if (PDecl->getType()->isObjCQualifiedIdType()) {
1103 ResultStr += "id ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001104 ResultStr += PDecl->getNameAsString();
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001105 } else {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001106 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00001107 QualType QT = PDecl->getType();
1108 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1109 if (convertBlockPointerToFunctionPointer(QT))
1110 QT.getAsStringInternal(Name, Context->PrintingPolicy);
1111 else
Douglas Gregor7de59662009-05-29 20:38:28 +00001112 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001113 ResultStr += Name;
1114 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001115 }
Fariborz Jahanianeab81cd2008-01-21 20:14:23 +00001116 if (OMD->isVariadic())
1117 ResultStr += ", ...";
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001118 ResultStr += ") ";
Mike Stump11289f42009-09-09 15:08:12 +00001119
Steve Naroffb067bbd2008-07-16 14:40:40 +00001120 if (FPRetType) {
1121 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump11289f42009-09-09 15:08:12 +00001122
Steve Naroffb067bbd2008-07-16 14:40:40 +00001123 // Now, emit the argument types (if any).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001124 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001125 ResultStr += "(";
1126 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1127 if (i) ResultStr += ", ";
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001128 std::string ParamStr = FT->getArgType(i).getAsString(
1129 Context->PrintingPolicy);
Steve Naroffb067bbd2008-07-16 14:40:40 +00001130 ResultStr += ParamStr;
1131 }
1132 if (FT->isVariadic()) {
1133 if (FT->getNumArgs()) ResultStr += ", ";
1134 ResultStr += "...";
1135 }
1136 ResultStr += ")";
1137 } else {
1138 ResultStr += "()";
1139 }
1140 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001141}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001142void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001143 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1144 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump11289f42009-09-09 15:08:12 +00001145
Fariborz Jahanian02d964b2010-02-15 21:11:41 +00001146 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump11289f42009-09-09 15:08:12 +00001147
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001148 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001149 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1150 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001151 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001152 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001153 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001154 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001155 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001156 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redla7b98a72009-04-26 20:35:05 +00001157
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001158 const char *startBuf = SM->getCharacterData(LocStart);
1159 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001160 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001161 }
Mike Stump11289f42009-09-09 15:08:12 +00001162
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001163 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001164 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1165 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001166 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001167 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001168 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001169 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001170 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001171 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +00001172
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001173 const char *startBuf = SM->getCharacterData(LocStart);
1174 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001175 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001176 }
Steve Naroffe1908e32008-12-01 20:33:01 +00001177 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001178 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001179 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001180 I != E; ++I) {
Steve Naroffc038b3a2008-12-02 17:36:43 +00001181 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffe1908e32008-12-01 20:33:01 +00001182 }
1183
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001184 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001185}
1186
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001187void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffc5484042007-10-30 02:23:23 +00001188 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001189 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff2f55b982007-11-01 03:35:41 +00001190 // we haven't seen a forward decl - generate a typedef.
Steve Naroff03f27672007-11-14 23:02:56 +00001191 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001192 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001193 ResultStr += "\n";
1194 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001195 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001196 ResultStr += "\n";
Steve Naroffa1e115e2008-03-10 23:16:54 +00001197 ResultStr += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001198 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001199 ResultStr += ";\n#endif\n";
Steve Naroff2f55b982007-11-01 03:35:41 +00001200 // Mark this typedef as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001201 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff2f55b982007-11-01 03:35:41 +00001202 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001203 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump11289f42009-09-09 15:08:12 +00001204
1205 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001206 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff0c0f5ba2009-01-11 01:06:09 +00001207 RewriteProperty(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001208 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001209 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001210 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001211 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001212 for (ObjCInterfaceDecl::classmeth_iterator
1213 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001214 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001215 RewriteMethodDeclaration(*I);
1216
Steve Naroff4cd61ac2007-10-30 03:43:13 +00001217 // Lastly, comment out the @end.
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +00001218 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1219 "/* @end */");
Steve Naroff161a92b2007-10-26 20:53:56 +00001220}
1221
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001222Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroff08628db2008-12-09 12:56:34 +00001223 SourceRange SrcRange) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001224 ObjCMethodDecl *OMD = 0;
1225 QualType Ty;
1226 Selector Sel;
Duncan Sands3a02f3e2010-10-20 08:21:16 +00001227 Stmt *Receiver = 0;
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001228 bool Super = false;
1229 QualType SuperTy;
1230 SourceLocation SuperLocation;
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001231 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ObjCImplicitSetterGetterRefExpr.
Steve Naroff4588d0f2008-12-04 16:24:46 +00001232 // This allows us to reuse all the fun and games in SynthMessageExpr().
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001233 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS())) {
1234 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1235 OMD = PDecl->getSetterMethodDecl();
1236 Ty = PDecl->getType();
1237 Sel = PDecl->getSetterName();
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001238 Super = PropRefExpr->isSuperReceiver();
1239 if (!Super)
1240 Receiver = PropRefExpr->getBase();
1241 else {
1242 SuperTy = PropRefExpr->getSuperType();
1243 SuperLocation = PropRefExpr->getSuperLocation();
1244 }
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001245 }
1246 else if (ObjCImplicitSetterGetterRefExpr *ImplicitRefExpr =
1247 dyn_cast<ObjCImplicitSetterGetterRefExpr>(BinOp->getLHS())) {
1248 OMD = ImplicitRefExpr->getSetterMethod();
1249 Sel = OMD->getSelector();
1250 Ty = ImplicitRefExpr->getType();
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001251 Super = ImplicitRefExpr->isSuperReceiver();
1252 if (!Super)
1253 Receiver = ImplicitRefExpr->getBase();
1254 else {
1255 SuperTy = ImplicitRefExpr->getSuperType();
1256 SuperLocation = ImplicitRefExpr->getSuperLocation();
1257 }
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001258 }
1259
1260 assert(OMD && "RewritePropertyOrImplicitSetter - null OMD");
Steve Naroff4588d0f2008-12-04 16:24:46 +00001261 llvm::SmallVector<Expr *, 1> ExprVec;
1262 ExprVec.push_back(newStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001263
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001264 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001265 if (Super)
Douglas Gregor9a129192010-04-21 00:45:42 +00001266 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001267 Ty.getNonReferenceType(),
John McCall7decc9e2010-11-18 06:31:45 +00001268 Expr::getValueKindForType(Ty),
Douglas Gregor9a129192010-04-21 00:45:42 +00001269 /*FIXME?*/SourceLocation(),
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001270 SuperLocation,
Douglas Gregor9a129192010-04-21 00:45:42 +00001271 /*IsInstanceSuper=*/true,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001272 SuperTy,
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001273 Sel, OMD,
Douglas Gregor9a129192010-04-21 00:45:42 +00001274 &ExprVec[0], 1,
1275 /*FIXME:*/SourceLocation());
Fariborz Jahanianbb40ea42010-10-20 16:07:20 +00001276 else {
1277 // FIXME. Refactor this into common code with that in
1278 // RewritePropertyOrImplicitGetter
1279 assert(Receiver && "RewritePropertyOrImplicitSetter - null Receiver");
1280 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1281 if (PropGetters[Exp])
1282 // This allows us to handle chain/nested property/implicit getters.
1283 Receiver = PropGetters[Exp];
1284
Douglas Gregor9a129192010-04-21 00:45:42 +00001285 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001286 Ty.getNonReferenceType(),
John McCall7decc9e2010-11-18 06:31:45 +00001287 Expr::getValueKindForType(Ty),
Douglas Gregor9a129192010-04-21 00:45:42 +00001288 /*FIXME: */SourceLocation(),
1289 cast<Expr>(Receiver),
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001290 Sel, OMD,
Douglas Gregor9a129192010-04-21 00:45:42 +00001291 &ExprVec[0], 1,
1292 /*FIXME:*/SourceLocation());
Fariborz Jahanianbb40ea42010-10-20 16:07:20 +00001293 }
Steve Naroff4588d0f2008-12-04 16:24:46 +00001294 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001295
Steve Naroff4588d0f2008-12-04 16:24:46 +00001296 // Now do the actual rewrite.
Steve Naroff08628db2008-12-09 12:56:34 +00001297 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffdf705772008-12-10 14:53:27 +00001298 //delete BinOp;
Ted Kremenek5a201952009-02-07 01:47:29 +00001299 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1300 // to things that stay around.
1301 Context->Deallocate(MsgExpr);
Steve Naroff4588d0f2008-12-04 16:24:46 +00001302 return ReplacingStmt;
Steve Narofff326f402008-12-03 00:56:33 +00001303}
1304
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001305Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(Expr *PropOrGetterRefExpr) {
1306 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ImplicitGetter.
Steve Narofff326f402008-12-03 00:56:33 +00001307 // This allows us to reuse all the fun and games in SynthMessageExpr().
Ted Kremenekc81155e2010-10-19 23:10:22 +00001308 Stmt *Receiver = 0;
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001309 ObjCMethodDecl *OMD = 0;
1310 QualType Ty;
1311 Selector Sel;
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001312 bool Super = false;
1313 QualType SuperTy;
1314 SourceLocation SuperLocation;
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001315 if (ObjCPropertyRefExpr *PropRefExpr =
1316 dyn_cast<ObjCPropertyRefExpr>(PropOrGetterRefExpr)) {
1317 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1318 OMD = PDecl->getGetterMethodDecl();
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001319 Ty = PDecl->getType();
1320 Sel = PDecl->getGetterName();
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001321 Super = PropRefExpr->isSuperReceiver();
1322 if (!Super)
1323 Receiver = PropRefExpr->getBase();
1324 else {
1325 SuperTy = PropRefExpr->getSuperType();
1326 SuperLocation = PropRefExpr->getSuperLocation();
1327 }
Steve Naroff1042ff32008-12-08 16:43:47 +00001328 }
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001329 else if (ObjCImplicitSetterGetterRefExpr *ImplicitRefExpr =
1330 dyn_cast<ObjCImplicitSetterGetterRefExpr>(PropOrGetterRefExpr)) {
1331 OMD = ImplicitRefExpr->getGetterMethod();
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001332 Sel = OMD->getSelector();
1333 Ty = ImplicitRefExpr->getType();
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001334 Super = ImplicitRefExpr->isSuperReceiver();
1335 if (!Super)
1336 Receiver = ImplicitRefExpr->getBase();
1337 else {
1338 SuperTy = ImplicitRefExpr->getSuperType();
1339 SuperLocation = ImplicitRefExpr->getSuperLocation();
1340 }
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001341 }
1342
1343 assert (OMD && "RewritePropertyOrImplicitGetter - OMD is null");
1344
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001345 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001346 if (Super)
Douglas Gregor9a129192010-04-21 00:45:42 +00001347 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001348 Ty.getNonReferenceType(),
John McCall7decc9e2010-11-18 06:31:45 +00001349 Expr::getValueKindForType(Ty),
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001350 /*FIXME?*/SourceLocation(),
1351 SuperLocation,
Douglas Gregor9a129192010-04-21 00:45:42 +00001352 /*IsInstanceSuper=*/true,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001353 SuperTy,
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001354 Sel, OMD,
Douglas Gregor9a129192010-04-21 00:45:42 +00001355 0, 0,
1356 /*FIXME:*/SourceLocation());
Fariborz Jahanianbb40ea42010-10-20 16:07:20 +00001357 else {
1358 assert (Receiver && "RewritePropertyOrImplicitGetter - Receiver is null");
1359 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1360 if (PropGetters[Exp])
1361 // This allows us to handle chain/nested property/implicit getters.
1362 Receiver = PropGetters[Exp];
Douglas Gregor9a129192010-04-21 00:45:42 +00001363 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001364 Ty.getNonReferenceType(),
John McCall7decc9e2010-11-18 06:31:45 +00001365 Expr::getValueKindForType(Ty),
Douglas Gregor9a129192010-04-21 00:45:42 +00001366 /*FIXME:*/SourceLocation(),
1367 cast<Expr>(Receiver),
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001368 Sel, OMD,
Douglas Gregor9a129192010-04-21 00:45:42 +00001369 0, 0,
1370 /*FIXME:*/SourceLocation());
Fariborz Jahanianbb40ea42010-10-20 16:07:20 +00001371 }
Steve Narofff326f402008-12-03 00:56:33 +00001372
Steve Naroff22216db2008-12-04 23:50:32 +00001373 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001374
1375 if (!PropParentMap)
1376 PropParentMap = new ParentMap(CurrentBody);
1377
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001378 Stmt *Parent = PropParentMap->getParent(PropOrGetterRefExpr);
1379 if (Parent && (isa<ObjCPropertyRefExpr>(Parent) ||
1380 isa<ObjCImplicitSetterGetterRefExpr>(Parent))) {
Steve Naroff1042ff32008-12-08 16:43:47 +00001381 // We stash away the ReplacingStmt since actually doing the
1382 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001383 PropGetters[PropOrGetterRefExpr] = ReplacingStmt;
Ted Kremenek5a201952009-02-07 01:47:29 +00001384 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1385 // to things that stay around.
1386 Context->Deallocate(MsgExpr);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001387 return PropOrGetterRefExpr; // return the original...
Steve Naroff1042ff32008-12-08 16:43:47 +00001388 } else {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001389 ReplaceStmt(PropOrGetterRefExpr, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001390 // delete PropRefExpr; elsewhere...
Ted Kremenek5a201952009-02-07 01:47:29 +00001391 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1392 // to things that stay around.
1393 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001394 return ReplacingStmt;
1395 }
Steve Narofff326f402008-12-03 00:56:33 +00001396}
1397
Mike Stump11289f42009-09-09 15:08:12 +00001398Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001399 SourceLocation OrigStart,
1400 bool &replaced) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001401 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001402 const Expr *BaseExpr = IV->getBase();
Steve Naroff677ab3a2008-10-27 17:20:55 +00001403 if (CurMethodDef) {
Fariborz Jahanianf9e8c2b2010-01-26 18:28:51 +00001404 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001405 ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001406 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianf0ed69c2010-01-26 20:37:44 +00001407 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Naroffb1c02372008-05-08 17:52:16 +00001408 // lookup which class implements the instance variable.
1409 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001410 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001411 clsDeclared);
Steve Naroffb1c02372008-05-08 17:52:16 +00001412 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001413
Steve Naroffb1c02372008-05-08 17:52:16 +00001414 // Synthesize an explicit cast to gain access to the ivar.
1415 std::string RecName = clsDeclared->getIdentifier()->getName();
1416 RecName += "_IMPL";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001417 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara6150c882010-05-11 21:36:43 +00001418 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001419 SourceLocation(), II);
Steve Naroffb1c02372008-05-08 17:52:16 +00001420 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1421 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall97513962010-01-15 18:39:57 +00001422 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCallf608deb2010-11-15 09:46:46 +00001423 CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00001424 IV->getBase());
Steve Naroffb1c02372008-05-08 17:52:16 +00001425 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001426 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
John McCall7decc9e2010-11-18 06:31:45 +00001427 IV->getBase()->getLocEnd(),
1428 castExpr);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001429 replaced = true;
Mike Stump11289f42009-09-09 15:08:12 +00001430 if (IV->isFreeIvar() &&
Steve Naroff677ab3a2008-10-27 17:20:55 +00001431 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001432 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
John McCall7decc9e2010-11-18 06:31:45 +00001433 IV->getLocation(),
1434 D->getType(),
1435 VK_LValue, OK_Ordinary);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001436 // delete IV; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffb1c02372008-05-08 17:52:16 +00001437 return ME;
Steve Naroff05caa482007-11-15 11:33:00 +00001438 }
Fariborz Jahanian81310812010-01-28 01:41:20 +00001439 // Get the new text
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001440 // Cannot delete IV->getBase(), since PE points to it.
1441 // Replace the old base with the cast. This is important when doing
1442 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001443 IV->setBase(PE);
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001444 return IV;
Steve Naroff05caa482007-11-15 11:33:00 +00001445 }
Steve Naroff24840f62008-04-18 21:55:08 +00001446 } else { // we are outside a method.
Steve Naroff29ce4e52008-05-06 23:20:07 +00001447 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump11289f42009-09-09 15:08:12 +00001448
Steve Naroff29ce4e52008-05-06 23:20:07 +00001449 // Explicit ivar refs need to have a cast inserted.
1450 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian12e2e862010-01-12 17:31:23 +00001451 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Fariborz Jahanian9146e442010-01-11 17:50:35 +00001452 ObjCInterfaceType *iFaceDecl =
1453 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001454 // lookup which class implements the instance variable.
1455 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001456 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001457 clsDeclared);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001458 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001459
Steve Naroff29ce4e52008-05-06 23:20:07 +00001460 // Synthesize an explicit cast to gain access to the ivar.
1461 std::string RecName = clsDeclared->getIdentifier()->getName();
1462 RecName += "_IMPL";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001463 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara6150c882010-05-11 21:36:43 +00001464 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001465 SourceLocation(), II);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001466 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1467 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall97513962010-01-15 18:39:57 +00001468 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCallf608deb2010-11-15 09:46:46 +00001469 CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00001470 IV->getBase());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001471 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001472 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner34873d22008-05-28 16:38:23 +00001473 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001474 replaced = true;
Steve Naroff29ce4e52008-05-06 23:20:07 +00001475 // Cannot delete IV->getBase(), since PE points to it.
1476 // Replace the old base with the cast. This is important when doing
1477 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001478 IV->setBase(PE);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001479 return IV;
1480 }
Steve Naroff05caa482007-11-15 11:33:00 +00001481 }
Steve Naroff24840f62008-04-18 21:55:08 +00001482 return IV;
Steve Narofff60782b2007-11-15 02:58:25 +00001483}
1484
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001485Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
1486 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1487 CI != E; ++CI) {
1488 if (*CI) {
1489 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1490 if (newStmt)
1491 *CI = newStmt;
1492 }
1493 }
1494 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1495 SourceRange OrigStmtRange = S->getSourceRange();
1496 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1497 replaced);
1498 return newStmt;
Fariborz Jahanian31433382010-02-05 17:48:10 +00001499 }
1500 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1501 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1502 return newStmt;
1503 }
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001504 return S;
1505}
1506
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001507/// SynthCountByEnumWithState - To print:
1508/// ((unsigned int (*)
1509/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001510/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001511/// sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001512/// "countByEnumeratingWithState:objects:count:"),
1513/// &enumState,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001514/// (id *)items, (unsigned int)16)
1515///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001516void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001517 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1518 "id *, unsigned int))(void *)objc_msgSend)";
1519 buf += "\n\t\t";
1520 buf += "((id)l_collection,\n\t\t";
1521 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1522 buf += "\n\t\t";
1523 buf += "&enumState, "
1524 "(id *)items, (unsigned int)16)";
1525}
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001526
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001527/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1528/// statement to exit to its outer synthesized loop.
1529///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001530Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001531 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1532 return S;
1533 // replace break with goto __break_label
1534 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001535
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001536 SourceLocation startLoc = S->getLocStart();
1537 buf = "goto __break_label_";
1538 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001539 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001540
1541 return 0;
1542}
1543
1544/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1545/// statement to continue with its inner synthesized loop.
1546///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001547Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001548 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1549 return S;
1550 // replace continue with goto __continue_label
1551 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001552
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001553 SourceLocation startLoc = S->getLocStart();
1554 buf = "goto __continue_label_";
1555 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001556 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump11289f42009-09-09 15:08:12 +00001557
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001558 return 0;
1559}
1560
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001561/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001562/// It rewrites:
1563/// for ( type elem in collection) { stmts; }
Mike Stump11289f42009-09-09 15:08:12 +00001564
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001565/// Into:
1566/// {
Mike Stump11289f42009-09-09 15:08:12 +00001567/// type elem;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001568/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001569/// id items[16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001570/// id l_collection = (id)collection;
Mike Stump11289f42009-09-09 15:08:12 +00001571/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001572/// objects:items count:16];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001573/// if (limit) {
1574/// unsigned long startMutations = *enumState.mutationsPtr;
1575/// do {
1576/// unsigned long counter = 0;
1577/// do {
Mike Stump11289f42009-09-09 15:08:12 +00001578/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001579/// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001580/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001581/// stmts;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001582/// __continue_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001583/// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001584/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001585/// objects:items count:16]);
1586/// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001587/// __break_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001588/// }
1589/// else
1590/// elem = nil;
1591/// }
1592///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001593Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattnera779d692008-01-31 05:10:40 +00001594 SourceLocation OrigEnd) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001595 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001596 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001597 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump11289f42009-09-09 15:08:12 +00001598 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001599 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001600
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001601 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001602 const char *startBuf = SM->getCharacterData(startLoc);
Daniel Dunbar56df9772010-08-17 22:39:59 +00001603 llvm::StringRef elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001604 std::string elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001605 std::string buf;
1606 buf = "\n{\n\t";
1607 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1608 // type elem;
Chris Lattner529efc72009-03-28 06:33:19 +00001609 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek292b3842008-10-06 22:16:13 +00001610 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001611 if (ElementType->isObjCQualifiedIdType() ||
1612 ElementType->isObjCQualifiedInterfaceType())
1613 // Simply use 'id' for all qualified types.
1614 elementTypeAsString = "id";
1615 else
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001616 elementTypeAsString = ElementType.getAsString(Context->PrintingPolicy);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001617 buf += elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001618 buf += " ";
Daniel Dunbar56df9772010-08-17 22:39:59 +00001619 elementName = D->getName();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001620 buf += elementName;
1621 buf += ";\n\t";
1622 }
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001623 else {
1624 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar56df9772010-08-17 22:39:59 +00001625 elementName = DR->getDecl()->getName();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001626 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1627 if (VD->getType()->isObjCQualifiedIdType() ||
1628 VD->getType()->isObjCQualifiedInterfaceType())
1629 // Simply use 'id' for all qualified types.
1630 elementTypeAsString = "id";
1631 else
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001632 elementTypeAsString = VD->getType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001633 }
Mike Stump11289f42009-09-09 15:08:12 +00001634
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001635 // struct __objcFastEnumerationState enumState = { 0 };
1636 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1637 // id items[16];
1638 buf += "id items[16];\n\t";
1639 // id l_collection = (id)
1640 buf += "id l_collection = (id)";
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001641 // Find start location of 'collection' the hard way!
1642 const char *startCollectionBuf = startBuf;
1643 startCollectionBuf += 3; // skip 'for'
1644 startCollectionBuf = strchr(startCollectionBuf, '(');
1645 startCollectionBuf++; // skip '('
1646 // find 'in' and skip it.
1647 while (*startCollectionBuf != ' ' ||
1648 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1649 (*(startCollectionBuf+3) != ' ' &&
1650 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1651 startCollectionBuf++;
1652 startCollectionBuf += 3;
Mike Stump11289f42009-09-09 15:08:12 +00001653
1654 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001655 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001656 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001657 SourceLocation rightParenLoc = S->getRParenLoc();
1658 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1659 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001660 buf = ";\n\t";
Mike Stump11289f42009-09-09 15:08:12 +00001661
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001662 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1663 // objects:items count:16];
1664 // which is synthesized into:
Mike Stump11289f42009-09-09 15:08:12 +00001665 // unsigned int limit =
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001666 // ((unsigned int (*)
1667 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001668 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001669 // sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001670 // "countByEnumeratingWithState:objects:count:"),
1671 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001672 // (id *)items, (unsigned int)16);
1673 buf += "unsigned long limit =\n\t\t";
1674 SynthCountByEnumWithState(buf);
1675 buf += ";\n\t";
1676 /// if (limit) {
1677 /// unsigned long startMutations = *enumState.mutationsPtr;
1678 /// do {
1679 /// unsigned long counter = 0;
1680 /// do {
Mike Stump11289f42009-09-09 15:08:12 +00001681 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001682 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001683 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001684 buf += "if (limit) {\n\t";
1685 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1686 buf += "do {\n\t\t";
1687 buf += "unsigned long counter = 0;\n\t\t";
1688 buf += "do {\n\t\t\t";
1689 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1690 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1691 buf += elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001692 buf += " = (";
1693 buf += elementTypeAsString;
1694 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001695 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001696 ReplaceText(lparenLoc, 1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001697
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001698 /// __continue_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001699 /// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001700 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001701 /// objects:items count:16]);
1702 /// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001703 /// __break_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001704 /// }
1705 /// else
1706 /// elem = nil;
1707 /// }
Mike Stump11289f42009-09-09 15:08:12 +00001708 ///
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001709 buf = ";\n\t";
1710 buf += "__continue_label_";
1711 buf += utostr(ObjCBcLabelNo.back());
1712 buf += ": ;";
1713 buf += "\n\t\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001714 buf += "} while (counter < limit);\n\t";
1715 buf += "} while (limit = ";
1716 SynthCountByEnumWithState(buf);
1717 buf += ");\n\t";
1718 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001719 buf += " = ((";
1720 buf += elementTypeAsString;
1721 buf += ")0);\n\t";
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001722 buf += "__break_label_";
1723 buf += utostr(ObjCBcLabelNo.back());
1724 buf += ": ;\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001725 buf += "}\n\t";
1726 buf += "else\n\t\t";
1727 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001728 buf += " = ((";
1729 buf += elementTypeAsString;
1730 buf += ")0);\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001731 buf += "}\n";
Mike Stump11289f42009-09-09 15:08:12 +00001732
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001733 // Insert all these *after* the statement body.
Sebastian Redla7b98a72009-04-26 20:35:05 +00001734 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Narofff0ff8792008-07-21 18:26:02 +00001735 if (isa<CompoundStmt>(S->getBody())) {
1736 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001737 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001738 } else {
1739 /* Need to treat single statements specially. For example:
1740 *
1741 * for (A *a in b) if (stuff()) break;
1742 * for (A *a in b) xxxyy;
1743 *
1744 * The following code simply scans ahead to the semi to find the actual end.
1745 */
1746 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1747 const char *semiBuf = strchr(stmtBuf, ';');
1748 assert(semiBuf && "Can't find ';'");
1749 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001750 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001751 }
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001752 Stmts.pop_back();
1753 ObjCBcLabelNo.pop_back();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001754 return 0;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001755}
1756
Mike Stump11289f42009-09-09 15:08:12 +00001757/// RewriteObjCSynchronizedStmt -
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001758/// This routine rewrites @synchronized(expr) stmt;
1759/// into:
1760/// objc_sync_enter(expr);
1761/// @try stmt @finally { objc_sync_exit(expr); }
1762///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001763Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001764 // Get the start location and compute the semi location.
1765 SourceLocation startLoc = S->getLocStart();
1766 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001767
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001768 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump11289f42009-09-09 15:08:12 +00001769
1770 std::string buf;
Steve Naroffb2fc0522008-08-21 13:03:03 +00001771 buf = "objc_sync_enter((id)";
1772 const char *lparenBuf = startBuf;
1773 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001774 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001775 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1776 // the sync expression is typically a message expression that's already
Steve Naroffad7013b2008-08-19 13:04:19 +00001777 // been rewritten! (which implies the SourceLocation's are invalid).
1778 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001779 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffad7013b2008-08-19 13:04:19 +00001780 while (*endBuf != ')') endBuf--;
1781 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001782 buf = ");\n";
1783 // declare a new scope with two variables, _stack and _rethrow.
1784 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1785 buf += "int buf[18/*32-bit i386*/];\n";
1786 buf += "char *pointers[4];} _stack;\n";
1787 buf += "id volatile _rethrow = 0;\n";
1788 buf += "objc_exception_try_enter(&_stack);\n";
1789 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001790 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001791 startLoc = S->getSynchBody()->getLocEnd();
1792 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001793
Steve Naroffad7013b2008-08-19 13:04:19 +00001794 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001795 SourceLocation lastCurlyLoc = startLoc;
1796 buf = "}\nelse {\n";
1797 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroffd9803712009-04-29 16:37:50 +00001798 buf += "}\n";
1799 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001800 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffec60b432009-12-05 21:43:12 +00001801
1802 std::string syncBuf;
1803 syncBuf += " objc_sync_exit(";
John McCall97513962010-01-15 18:39:57 +00001804 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00001805 CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00001806 S->getSynchExpr());
Ted Kremenek2d470fc2008-09-13 05:16:45 +00001807 std::string syncExprBufS;
1808 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00001809 syncExpr->printPretty(syncExprBuf, *Context, 0,
1810 PrintingPolicy(LangOpts));
Steve Naroffec60b432009-12-05 21:43:12 +00001811 syncBuf += syncExprBuf.str();
1812 syncBuf += ");";
1813
1814 buf += syncBuf;
1815 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001816 buf += "}\n";
1817 buf += "}";
Mike Stump11289f42009-09-09 15:08:12 +00001818
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001819 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00001820
1821 bool hasReturns = false;
1822 HasReturnStmts(S->getSynchBody(), hasReturns);
1823 if (hasReturns)
1824 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1825
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001826 return 0;
1827}
1828
Steve Naroffec60b432009-12-05 21:43:12 +00001829void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1830{
Steve Naroff6d6da252008-12-05 17:03:39 +00001831 // Perform a bottom up traversal of all children.
1832 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1833 CI != E; ++CI)
1834 if (*CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001835 WarnAboutReturnGotoStmts(*CI);
Steve Naroff6d6da252008-12-05 17:03:39 +00001836
Steve Naroffec60b432009-12-05 21:43:12 +00001837 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump11289f42009-09-09 15:08:12 +00001838 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff6d6da252008-12-05 17:03:39 +00001839 TryFinallyContainsReturnDiag);
1840 }
1841 return;
1842}
1843
Steve Naroffec60b432009-12-05 21:43:12 +00001844void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1845{
1846 // Perform a bottom up traversal of all children.
1847 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1848 CI != E; ++CI)
1849 if (*CI)
1850 HasReturnStmts(*CI, hasReturns);
1851
1852 if (isa<ReturnStmt>(S))
1853 hasReturns = true;
1854 return;
1855}
1856
1857void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1858 // Perform a bottom up traversal of all children.
1859 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1860 CI != E; ++CI)
1861 if (*CI) {
1862 RewriteTryReturnStmts(*CI);
1863 }
1864 if (isa<ReturnStmt>(S)) {
1865 SourceLocation startLoc = S->getLocStart();
1866 const char *startBuf = SM->getCharacterData(startLoc);
1867
1868 const char *semiBuf = strchr(startBuf, ';');
1869 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1870 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1871
1872 std::string buf;
1873 buf = "{ objc_exception_try_exit(&_stack); return";
1874
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001875 ReplaceText(startLoc, 6, buf);
1876 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001877 }
1878 return;
1879}
1880
1881void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1882 // Perform a bottom up traversal of all children.
1883 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1884 CI != E; ++CI)
1885 if (*CI) {
1886 RewriteSyncReturnStmts(*CI, syncExitBuf);
1887 }
1888 if (isa<ReturnStmt>(S)) {
1889 SourceLocation startLoc = S->getLocStart();
1890 const char *startBuf = SM->getCharacterData(startLoc);
1891
1892 const char *semiBuf = strchr(startBuf, ';');
1893 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1894 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1895
1896 std::string buf;
1897 buf = "{ objc_exception_try_exit(&_stack);";
1898 buf += syncExitBuf;
1899 buf += " return";
1900
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001901 ReplaceText(startLoc, 6, buf);
1902 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001903 }
1904 return;
1905}
1906
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001907Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001908 // Get the start location and compute the semi location.
1909 SourceLocation startLoc = S->getLocStart();
1910 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001911
Steve Naroffbf478ec2007-11-07 04:08:17 +00001912 assert((*startBuf == '@') && "bogus @try location");
1913
1914 std::string buf;
1915 // declare a new scope with two variables, _stack and _rethrow.
1916 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1917 buf += "int buf[18/*32-bit i386*/];\n";
1918 buf += "char *pointers[4];} _stack;\n";
1919 buf += "id volatile _rethrow = 0;\n";
1920 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff16018582007-11-07 18:43:40 +00001921 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffbf478ec2007-11-07 04:08:17 +00001922
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001923 ReplaceText(startLoc, 4, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001924
Steve Naroffbf478ec2007-11-07 04:08:17 +00001925 startLoc = S->getTryBody()->getLocEnd();
1926 startBuf = SM->getCharacterData(startLoc);
1927
1928 assert((*startBuf == '}') && "bogus @try block");
Mike Stump11289f42009-09-09 15:08:12 +00001929
Steve Naroffbf478ec2007-11-07 04:08:17 +00001930 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor96c79492010-04-23 22:50:49 +00001931 if (S->getNumCatchStmts()) {
Steve Naroffce2dca12008-07-16 15:31:30 +00001932 startLoc = startLoc.getFileLocWithOffset(1);
1933 buf = " /* @catch begin */ else {\n";
1934 buf += " id _caught = objc_exception_extract(&_stack);\n";
1935 buf += " objc_exception_try_enter (&_stack);\n";
1936 buf += " if (_setjmp(_stack.buf))\n";
1937 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1938 buf += " else { /* @catch continue */";
Mike Stump11289f42009-09-09 15:08:12 +00001939
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001940 InsertText(startLoc, buf);
Steve Narofffac18fe2008-09-09 19:59:12 +00001941 } else { /* no catch list */
1942 buf = "}\nelse {\n";
1943 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1944 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001945 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffce2dca12008-07-16 15:31:30 +00001946 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001947 bool sawIdTypedCatch = false;
1948 Stmt *lastCatchBody = 0;
Douglas Gregor96c79492010-04-23 22:50:49 +00001949 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1950 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregor46a572b2010-04-26 16:46:50 +00001951 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001952
Douglas Gregor96c79492010-04-23 22:50:49 +00001953 if (I == 0)
Steve Naroffbf478ec2007-11-07 04:08:17 +00001954 buf = "if ("; // we are generating code for the first catch clause
1955 else
1956 buf = "else if (";
Douglas Gregor96c79492010-04-23 22:50:49 +00001957 startLoc = Catch->getLocStart();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001958 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001959
Steve Naroffbf478ec2007-11-07 04:08:17 +00001960 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump11289f42009-09-09 15:08:12 +00001961
Steve Naroffbf478ec2007-11-07 04:08:17 +00001962 const char *lParenLoc = strchr(startBuf, '(');
1963
Douglas Gregor96c79492010-04-23 22:50:49 +00001964 if (Catch->hasEllipsis()) {
Steve Naroffedb5bc62008-02-01 20:02:07 +00001965 // Now rewrite the body...
Douglas Gregor96c79492010-04-23 22:50:49 +00001966 lastCatchBody = Catch->getCatchBody();
Steve Naroffedb5bc62008-02-01 20:02:07 +00001967 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1968 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor96c79492010-04-23 22:50:49 +00001969 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001970 "bogus @catch paren location");
Steve Naroffedb5bc62008-02-01 20:02:07 +00001971 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001972
Steve Naroffedb5bc62008-02-01 20:02:07 +00001973 buf += "1) { id _tmp = _caught;";
Daniel Dunbardec484a2009-08-19 19:10:30 +00001974 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff371b8fb2009-03-03 19:52:17 +00001975 } else if (catchDecl) {
1976 QualType t = catchDecl->getType();
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001977 if (t == Context->getObjCIdType()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001978 buf += "1) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001979 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroffbf478ec2007-11-07 04:08:17 +00001980 sawIdTypedCatch = true;
John McCall96fa4842010-05-17 21:00:27 +00001981 } else if (const ObjCObjectPointerType *Ptr =
1982 t->getAs<ObjCObjectPointerType>()) {
1983 // Should be a pointer to a class.
1984 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1985 if (IDecl) {
Steve Naroff16018582007-11-07 18:43:40 +00001986 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall96fa4842010-05-17 21:00:27 +00001987 buf += IDecl->getNameAsString();
Steve Naroff16018582007-11-07 18:43:40 +00001988 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001989 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroffbf478ec2007-11-07 04:08:17 +00001990 }
1991 }
1992 // Now rewrite the body...
Douglas Gregor96c79492010-04-23 22:50:49 +00001993 lastCatchBody = Catch->getCatchBody();
1994 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001995 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1996 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1997 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1998 assert((*rParenBuf == ')') && "bogus @catch paren location");
1999 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00002000
Mike Stump11289f42009-09-09 15:08:12 +00002001 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroffbf478ec2007-11-07 04:08:17 +00002002 // declares the @catch parameter).
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002003 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff371b8fb2009-03-03 19:52:17 +00002004 } else {
Steve Naroffbf478ec2007-11-07 04:08:17 +00002005 assert(false && "@catch rewrite bug");
Steve Naroffa733c7f2007-11-07 15:32:26 +00002006 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00002007 }
2008 // Complete the catch list...
2009 if (lastCatchBody) {
2010 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00002011 assert(*SM->getCharacterData(bodyLoc) == '}' &&
2012 "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00002013
Steve Naroff4adbe312008-09-11 15:29:03 +00002014 // Insert the last (implicit) else clause *before* the right curly brace.
2015 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
2016 buf = "} /* last catch end */\n";
2017 buf += "else {\n";
2018 buf += " _rethrow = _caught;\n";
2019 buf += " objc_exception_try_exit(&_stack);\n";
2020 buf += "} } /* @catch end */\n";
2021 if (!S->getFinallyStmt())
2022 buf += "}\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002023 InsertText(bodyLoc, buf);
Mike Stump11289f42009-09-09 15:08:12 +00002024
Steve Naroffbf478ec2007-11-07 04:08:17 +00002025 // Set lastCurlyLoc
2026 lastCurlyLoc = lastCatchBody->getLocEnd();
2027 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002028 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00002029 startLoc = finalStmt->getLocStart();
2030 startBuf = SM->getCharacterData(startLoc);
2031 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump11289f42009-09-09 15:08:12 +00002032
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002033 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump11289f42009-09-09 15:08:12 +00002034
Steve Naroffbf478ec2007-11-07 04:08:17 +00002035 Stmt *body = finalStmt->getFinallyBody();
2036 SourceLocation startLoc = body->getLocStart();
2037 SourceLocation endLoc = body->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00002038 assert(*SM->getCharacterData(startLoc) == '{' &&
2039 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00002040 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00002041 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00002042
Steve Naroffbf478ec2007-11-07 04:08:17 +00002043 startLoc = startLoc.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002044 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Steve Naroffbf478ec2007-11-07 04:08:17 +00002045 endLoc = endLoc.getFileLocWithOffset(-1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002046 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump11289f42009-09-09 15:08:12 +00002047
Steve Naroffbf478ec2007-11-07 04:08:17 +00002048 // Set lastCurlyLoc
2049 lastCurlyLoc = body->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00002050
Steve Naroff6d6da252008-12-05 17:03:39 +00002051 // Now check for any return/continue/go statements within the @try.
Steve Naroffec60b432009-12-05 21:43:12 +00002052 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff4adbe312008-09-11 15:29:03 +00002053 } else { /* no finally clause - make sure we synthesize an implicit one */
2054 buf = "{ /* implicit finally clause */\n";
2055 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
2056 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
2057 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002058 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00002059
2060 // Now check for any return/continue/go statements within the @try.
2061 // The implicit finally clause won't called if the @try contains any
2062 // jump statements.
2063 bool hasReturns = false;
2064 HasReturnStmts(S->getTryBody(), hasReturns);
2065 if (hasReturns)
2066 RewriteTryReturnStmts(S->getTryBody());
Steve Naroffbf478ec2007-11-07 04:08:17 +00002067 }
2068 // Now emit the final closing curly brace...
2069 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002070 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00002071 return 0;
2072}
2073
Mike Stump11289f42009-09-09 15:08:12 +00002074// This can't be done with ReplaceStmt(S, ThrowExpr), since
2075// the throw expression is typically a message expression that's already
Steve Naroffa733c7f2007-11-07 15:32:26 +00002076// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002077Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroffa733c7f2007-11-07 15:32:26 +00002078 // Get the start location and compute the semi location.
2079 SourceLocation startLoc = S->getLocStart();
2080 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002081
Steve Naroffa733c7f2007-11-07 15:32:26 +00002082 assert((*startBuf == '@') && "bogus @throw location");
2083
2084 std::string buf;
2085 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffc7d2df22008-01-19 00:42:38 +00002086 if (S->getThrowExpr())
2087 buf = "objc_exception_throw(";
2088 else // add an implicit argument
2089 buf = "objc_exception_throw(_caught";
Mike Stump11289f42009-09-09 15:08:12 +00002090
Steve Naroff29788342008-07-25 15:41:30 +00002091 // handle "@ throw" correctly.
2092 const char *wBuf = strchr(startBuf, 'w');
2093 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002094 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00002095
Steve Naroffa733c7f2007-11-07 15:32:26 +00002096 const char *semiBuf = strchr(startBuf, ';');
2097 assert((*semiBuf == ';') && "@throw: can't find ';'");
2098 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002099 ReplaceText(semiLoc, 1, ");");
Steve Naroffa733c7f2007-11-07 15:32:26 +00002100 return 0;
2101}
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00002102
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002103Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerc6d91c02007-10-17 22:35:30 +00002104 // Create a new string expression.
2105 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlssond8499822007-10-29 05:01:08 +00002106 std::string StrEncoding;
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00002107 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002108 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
2109 StrEncoding.length(), false,StrType,
2110 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002111 ReplaceStmt(Exp, Replacement);
Mike Stump11289f42009-09-09 15:08:12 +00002112
Chris Lattner4431a1b2007-11-30 22:53:43 +00002113 // Replace this subexpr in the parent.
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002114 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattner69534692007-10-24 16:57:36 +00002115 return Replacement;
Chris Lattnera7c19fe2007-10-16 22:36:42 +00002116}
2117
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002118Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff2654e182008-12-22 22:16:07 +00002119 if (!SelGetUidFunctionDecl)
2120 SynthSelGetUidFunctionDecl();
Steve Naroffe4f9b232007-11-05 14:50:49 +00002121 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2122 // Create a call to sel_registerName("selName").
2123 llvm::SmallVector<Expr*, 8> SelExprs;
2124 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002125 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002126 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002127 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002128 false, argType, SourceLocation()));
Steve Naroffe4f9b232007-11-05 14:50:49 +00002129 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2130 &SelExprs[0], SelExprs.size());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002131 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002132 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffe4f9b232007-11-05 14:50:49 +00002133 return SelExp;
2134}
2135
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002136CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002137 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2138 SourceLocation EndLoc) {
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002139 // Get the type, we will need to reference it in a couple spots.
Steve Naroff574440f2007-10-24 22:48:43 +00002140 QualType msgSendType = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002141
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002142 // Create a reference to the objc_msgSend() declaration.
John McCall7decc9e2010-11-18 06:31:45 +00002143 DeclRefExpr *DRE =
2144 new (Context) DeclRefExpr(FD, msgSendType, VK_LValue, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002145
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002146 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattner3c799d72007-10-24 17:06:59 +00002147 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson975979382010-04-23 22:18:37 +00002148 ImplicitCastExpr *ICE =
John McCallf608deb2010-11-15 09:46:46 +00002149 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00002150 DRE, 0, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00002151
John McCall9dd450b2009-09-21 23:43:11 +00002152 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00002153
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002154 CallExpr *Exp =
Douglas Gregor603d81b2010-07-13 08:18:22 +00002155 new (Context) CallExpr(*Context, ICE, args, nargs,
John McCall7decc9e2010-11-18 06:31:45 +00002156 FT->getCallResultType(*Context),
2157 VK_RValue, EndLoc);
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002158 return Exp;
Steve Naroff574440f2007-10-24 22:48:43 +00002159}
2160
Steve Naroff50d42052007-11-01 13:24:47 +00002161static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2162 const char *&startRef, const char *&endRef) {
2163 while (startBuf < endBuf) {
2164 if (*startBuf == '<')
2165 startRef = startBuf; // mark the start.
2166 if (*startBuf == '>') {
Steve Naroff1b232132007-11-09 12:50:28 +00002167 if (startRef && *startRef == '<') {
2168 endRef = startBuf; // mark the end.
2169 return true;
2170 }
2171 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002172 }
2173 startBuf++;
2174 }
2175 return false;
2176}
2177
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002178static void scanToNextArgument(const char *&argRef) {
2179 int angle = 0;
2180 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2181 if (*argRef == '<')
2182 angle++;
2183 else if (*argRef == '>')
2184 angle--;
2185 argRef++;
2186 }
2187 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2188}
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002189
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002190bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian80c54b02010-02-03 21:29:28 +00002191 if (T->isObjCQualifiedIdType())
2192 return true;
Fariborz Jahanian06769f92010-02-02 18:35:07 +00002193 if (const PointerType *PT = T->getAs<PointerType>()) {
2194 if (PT->getPointeeType()->isObjCQualifiedIdType())
2195 return true;
2196 }
2197 if (T->isObjCObjectPointerType()) {
2198 T = T->getPointeeType();
2199 return T->isObjCQualifiedInterfaceType();
2200 }
Fariborz Jahanian7bf13c42010-09-30 20:41:32 +00002201 if (T->isArrayType()) {
2202 QualType ElemTy = Context->getBaseElementType(T);
2203 return needToScanForQualifiers(ElemTy);
2204 }
Fariborz Jahanian06769f92010-02-02 18:35:07 +00002205 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002206}
2207
Steve Naroff873bd842008-07-29 18:15:38 +00002208void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2209 QualType Type = E->getType();
2210 if (needToScanForQualifiers(Type)) {
Steve Naroffdbfc6932008-11-19 21:15:47 +00002211 SourceLocation Loc, EndLoc;
Mike Stump11289f42009-09-09 15:08:12 +00002212
Steve Naroffdbfc6932008-11-19 21:15:47 +00002213 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2214 Loc = ECE->getLParenLoc();
2215 EndLoc = ECE->getRParenLoc();
2216 } else {
2217 Loc = E->getLocStart();
2218 EndLoc = E->getLocEnd();
2219 }
2220 // This will defend against trying to rewrite synthesized expressions.
2221 if (Loc.isInvalid() || EndLoc.isInvalid())
2222 return;
2223
Steve Naroff873bd842008-07-29 18:15:38 +00002224 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffdbfc6932008-11-19 21:15:47 +00002225 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff873bd842008-07-29 18:15:38 +00002226 const char *startRef = 0, *endRef = 0;
2227 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2228 // Get the locations of the startRef, endRef.
2229 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2230 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2231 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002232 InsertText(LessLoc, "/*");
2233 InsertText(GreaterLoc, "*/");
Steve Naroff873bd842008-07-29 18:15:38 +00002234 }
2235 }
2236}
2237
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002238void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002239 SourceLocation Loc;
2240 QualType Type;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002241 const FunctionProtoType *proto = 0;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002242 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2243 Loc = VD->getLocation();
2244 Type = VD->getType();
2245 }
2246 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2247 Loc = FD->getLocation();
2248 // Check for ObjC 'id' and class types that have been adorned with protocol
2249 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall9dd450b2009-09-21 23:43:11 +00002250 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002251 assert(funcType && "missing function type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002252 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002253 if (!proto)
2254 return;
2255 Type = proto->getResultType();
2256 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00002257 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2258 Loc = FD->getLocation();
2259 Type = FD->getType();
2260 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002261 else
2262 return;
Mike Stump11289f42009-09-09 15:08:12 +00002263
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002264 if (needToScanForQualifiers(Type)) {
Steve Naroff50d42052007-11-01 13:24:47 +00002265 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002266
Steve Naroff50d42052007-11-01 13:24:47 +00002267 const char *endBuf = SM->getCharacterData(Loc);
2268 const char *startBuf = endBuf;
Steve Naroff930e0992008-05-31 05:02:17 +00002269 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroff50d42052007-11-01 13:24:47 +00002270 startBuf--; // scan backward (from the decl location) for return type.
2271 const char *startRef = 0, *endRef = 0;
2272 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2273 // Get the locations of the startRef, endRef.
2274 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2275 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2276 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002277 InsertText(LessLoc, "/*");
2278 InsertText(GreaterLoc, "*/");
Steve Naroff37e011c2007-10-31 04:38:33 +00002279 }
2280 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002281 if (!proto)
2282 return; // most likely, was a variable
Steve Naroff50d42052007-11-01 13:24:47 +00002283 // Now check arguments.
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002284 const char *startBuf = SM->getCharacterData(Loc);
2285 const char *startFuncBuf = startBuf;
Steve Naroff50d42052007-11-01 13:24:47 +00002286 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2287 if (needToScanForQualifiers(proto->getArgType(i))) {
2288 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002289
Steve Naroff50d42052007-11-01 13:24:47 +00002290 const char *endBuf = startBuf;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002291 // scan forward (from the decl location) for argument types.
2292 scanToNextArgument(endBuf);
Steve Naroff50d42052007-11-01 13:24:47 +00002293 const char *startRef = 0, *endRef = 0;
2294 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2295 // Get the locations of the startRef, endRef.
Mike Stump11289f42009-09-09 15:08:12 +00002296 SourceLocation LessLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002297 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump11289f42009-09-09 15:08:12 +00002298 SourceLocation GreaterLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002299 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002300 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002301 InsertText(LessLoc, "/*");
2302 InsertText(GreaterLoc, "*/");
Steve Naroff50d42052007-11-01 13:24:47 +00002303 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002304 startBuf = ++endBuf;
2305 }
2306 else {
Steve Naroffc884aa82008-08-06 15:58:23 +00002307 // If the function name is derived from a macro expansion, then the
2308 // argument buffer will not follow the name. Need to speak with Chris.
2309 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002310 startBuf++; // scan forward (from the decl location) for argument types.
2311 startBuf++;
2312 }
Steve Naroff50d42052007-11-01 13:24:47 +00002313 }
Steve Naroff37e011c2007-10-31 04:38:33 +00002314}
2315
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002316void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2317 QualType QT = ND->getType();
2318 const Type* TypePtr = QT->getAs<Type>();
2319 if (!isa<TypeOfExprType>(TypePtr))
2320 return;
2321 while (isa<TypeOfExprType>(TypePtr)) {
2322 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2323 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2324 TypePtr = QT->getAs<Type>();
2325 }
2326 // FIXME. This will not work for multiple declarators; as in:
2327 // __typeof__(a) b,c,d;
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002328 std::string TypeAsString(QT.getAsString(Context->PrintingPolicy));
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002329 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2330 const char *startBuf = SM->getCharacterData(DeclLoc);
2331 if (ND->getInit()) {
2332 std::string Name(ND->getNameAsString());
2333 TypeAsString += " " + Name + " = ";
2334 Expr *E = ND->getInit();
2335 SourceLocation startLoc;
2336 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2337 startLoc = ECE->getLParenLoc();
2338 else
2339 startLoc = E->getLocStart();
2340 startLoc = SM->getInstantiationLoc(startLoc);
2341 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002342 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002343 }
2344 else {
2345 SourceLocation X = ND->getLocEnd();
2346 X = SM->getInstantiationLoc(X);
2347 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002348 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002349 }
2350}
2351
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002352// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002353void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002354 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2355 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002356 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002357 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002358 &ArgTys[0], ArgTys.size(),
2359 false /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002360 false, false, 0, 0,
2361 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002362 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002363 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002364 SelGetUidIdent, getFuncType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002365 SC_Extern,
2366 SC_None, false);
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002367}
2368
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002369void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002370 // declared in <objc/objc.h>
Douglas Gregor1e21c192009-01-09 01:47:02 +00002371 if (FD->getIdentifier() &&
Daniel Dunbar56df9772010-08-17 22:39:59 +00002372 FD->getName() == "sel_registerName") {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002373 SelGetUidFunctionDecl = FD;
Steve Naroff37e011c2007-10-31 04:38:33 +00002374 return;
2375 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002376 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002377}
2378
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002379void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2380 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002381 const char *argPtr = TypeString.c_str();
2382 if (!strchr(argPtr, '^')) {
2383 Str += TypeString;
2384 return;
2385 }
2386 while (*argPtr) {
2387 Str += (*argPtr == '^' ? '*' : *argPtr);
2388 argPtr++;
2389 }
2390}
2391
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002392// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002393void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2394 ValueDecl *VD) {
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002395 QualType Type = VD->getType();
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002396 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002397 const char *argPtr = TypeString.c_str();
2398 int paren = 0;
2399 while (*argPtr) {
2400 switch (*argPtr) {
2401 case '(':
2402 Str += *argPtr;
2403 paren++;
2404 break;
2405 case ')':
2406 Str += *argPtr;
2407 paren--;
2408 break;
2409 case '^':
2410 Str += '*';
2411 if (paren == 1)
2412 Str += VD->getNameAsString();
2413 break;
2414 default:
2415 Str += *argPtr;
2416 break;
2417 }
2418 argPtr++;
2419 }
2420}
2421
2422
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002423void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2424 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2425 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2426 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2427 if (!proto)
2428 return;
2429 QualType Type = proto->getResultType();
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002430 std::string FdStr = Type.getAsString(Context->PrintingPolicy);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002431 FdStr += " ";
Daniel Dunbar56df9772010-08-17 22:39:59 +00002432 FdStr += FD->getName();
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002433 FdStr += "(";
2434 unsigned numArgs = proto->getNumArgs();
2435 for (unsigned i = 0; i < numArgs; i++) {
2436 QualType ArgType = proto->getArgType(i);
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002437 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002438 if (i+1 < numArgs)
2439 FdStr += ", ";
2440 }
2441 FdStr += ");\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002442 InsertText(FunLocStart, FdStr);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002443 CurFunctionDeclToDeclareForBlock = 0;
2444}
2445
Steve Naroff17978c42008-03-11 17:37:02 +00002446// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002447void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroff17978c42008-03-11 17:37:02 +00002448 if (SuperContructorFunctionDecl)
2449 return;
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002450 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroff17978c42008-03-11 17:37:02 +00002451 llvm::SmallVector<QualType, 16> ArgTys;
2452 QualType argT = Context->getObjCIdType();
2453 assert(!argT.isNull() && "Can't find 'id' type");
2454 ArgTys.push_back(argT);
2455 ArgTys.push_back(argT);
2456 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2457 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002458 false, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002459 false, false, 0, 0,
2460 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002461 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002462 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002463 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002464 SC_Extern,
2465 SC_None, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002466}
2467
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002468// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002469void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002470 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2471 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002472 QualType argT = Context->getObjCIdType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002473 assert(!argT.isNull() && "Can't find 'id' type");
2474 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002475 argT = Context->getObjCSelType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002476 assert(!argT.isNull() && "Can't find 'SEL' type");
2477 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002478 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002479 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002480 true /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002481 false, false, 0, 0,
2482 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002483 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002484 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002485 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002486 SC_Extern,
2487 SC_None, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002488}
2489
Steve Naroff7fa2f042007-11-15 10:28:18 +00002490// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002491void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002492 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2493 llvm::SmallVector<QualType, 16> ArgTys;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002494 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002495 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002496 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002497 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2498 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2499 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002500 argT = Context->getObjCSelType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002501 assert(!argT.isNull() && "Can't find 'SEL' type");
2502 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002503 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff7fa2f042007-11-15 10:28:18 +00002504 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002505 true /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002506 false, false, 0, 0,
2507 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002508 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002509 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002510 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002511 SC_Extern,
2512 SC_None, false);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002513}
2514
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002515// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002516void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002517 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2518 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002519 QualType argT = Context->getObjCIdType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002520 assert(!argT.isNull() && "Can't find 'id' type");
2521 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002522 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002523 assert(!argT.isNull() && "Can't find 'SEL' type");
2524 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002525 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002526 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002527 true /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002528 false, false, 0, 0,
2529 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002530 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002531 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002532 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002533 SC_Extern,
2534 SC_None, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002535}
2536
Mike Stump11289f42009-09-09 15:08:12 +00002537// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002538// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002539void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump11289f42009-09-09 15:08:12 +00002540 IdentifierInfo *msgSendIdent =
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002541 &Context->Idents.get("objc_msgSendSuper_stret");
2542 llvm::SmallVector<QualType, 16> ArgTys;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002543 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002544 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002545 &Context->Idents.get("objc_super"));
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002546 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2547 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2548 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002549 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002550 assert(!argT.isNull() && "Can't find 'SEL' type");
2551 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002552 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002553 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002554 true /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002555 false, false, 0, 0,
2556 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002557 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002558 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002559 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002560 SC_Extern,
2561 SC_None, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002562}
2563
Steve Naroff2e4e3852008-05-08 22:02:18 +00002564// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002565void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002566 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2567 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002568 QualType argT = Context->getObjCIdType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002569 assert(!argT.isNull() && "Can't find 'id' type");
2570 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002571 argT = Context->getObjCSelType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002572 assert(!argT.isNull() && "Can't find 'SEL' type");
2573 ArgTys.push_back(argT);
Steve Naroff2e4e3852008-05-08 22:02:18 +00002574 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002575 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002576 true /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002577 false, false, 0, 0,
2578 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002579 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002580 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002581 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002582 SC_Extern,
2583 SC_None, false);
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002584}
2585
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002586// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002587void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002588 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2589 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002590 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002591 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002592 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002593 false /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002594 false, false, 0, 0,
2595 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002596 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002597 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002598 getClassIdent, getClassType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002599 SC_Extern,
2600 SC_None, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002601}
2602
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002603// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2604void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2605 IdentifierInfo *getSuperClassIdent =
2606 &Context->Idents.get("class_getSuperclass");
2607 llvm::SmallVector<QualType, 16> ArgTys;
2608 ArgTys.push_back(Context->getObjCClassType());
2609 QualType getClassType = Context->getFunctionType(Context->getObjCClassType(),
2610 &ArgTys[0], ArgTys.size(),
2611 false /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002612 false, false, 0, 0,
2613 FunctionType::ExtInfo());
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002614 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002615 SourceLocation(),
2616 getSuperClassIdent,
2617 getClassType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002618 SC_Extern,
2619 SC_None,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002620 false);
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002621}
2622
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002623// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002624void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002625 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2626 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002627 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002628 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002629 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002630 false /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002631 false, false, 0, 0,
2632 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002633 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002634 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002635 getClassIdent, getClassType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002636 SC_Extern,
2637 SC_None, false);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002638}
2639
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002640Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffce8e8862008-03-15 00:55:56 +00002641 QualType strType = getConstantStringStructType();
2642
2643 std::string S = "__NSConstantStringImpl_";
Steve Naroffa6141f02008-05-31 03:35:42 +00002644
2645 std::string tmpName = InFileName;
2646 unsigned i;
2647 for (i=0; i < tmpName.length(); i++) {
2648 char c = tmpName.at(i);
2649 // replace any non alphanumeric characters with '_'.
2650 if (!isalpha(c) && (c < '0' || c > '9'))
2651 tmpName[i] = '_';
2652 }
2653 S += tmpName;
2654 S += "_";
Steve Naroffce8e8862008-03-15 00:55:56 +00002655 S += utostr(NumObjCStringLiterals++);
2656
Steve Naroff00a31762008-03-27 22:29:16 +00002657 Preamble += "static __NSConstantStringImpl " + S;
2658 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2659 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffce8e8862008-03-15 00:55:56 +00002660 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek2d470fc2008-09-13 05:16:45 +00002661 std::string prettyBufS;
2662 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00002663 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2664 PrintingPolicy(LangOpts));
Steve Naroff00a31762008-03-27 22:29:16 +00002665 Preamble += prettyBuf.str();
2666 Preamble += ",";
Steve Naroff94ed6dc2009-12-06 01:48:44 +00002667 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002668
2669 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002670 &Context->Idents.get(S), strType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002671 SC_Static, SC_None);
John McCall7decc9e2010-11-18 06:31:45 +00002672 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, VK_LValue,
2673 SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00002674 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002675 Context->getPointerType(DRE->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002676 VK_RValue, OK_Ordinary,
2677 SourceLocation());
Steve Naroff265a6b92007-11-08 14:30:50 +00002678 // cast to NSConstantString *
John McCall97513962010-01-15 18:39:57 +00002679 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCallf608deb2010-11-15 09:46:46 +00002680 CK_BitCast, Unop);
Chris Lattner2e0d2602008-01-31 19:37:57 +00002681 ReplaceStmt(Exp, cast);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002682 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff265a6b92007-11-08 14:30:50 +00002683 return cast;
Steve Naroffa397efd2007-11-03 11:27:19 +00002684}
2685
Steve Naroff7fa2f042007-11-15 10:28:18 +00002686// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002687QualType RewriteObjC::getSuperStructType() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002688 if (!SuperStructDecl) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00002689 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002690 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002691 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002692 QualType FieldTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002693
Steve Naroff7fa2f042007-11-15 10:28:18 +00002694 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002695 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002696 // struct objc_class *super;
Mike Stump11289f42009-09-09 15:08:12 +00002697 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor91f84212008-12-11 16:49:14 +00002698
Steve Naroff7fa2f042007-11-15 10:28:18 +00002699 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002700 for (unsigned i = 0; i < 2; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002701 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2702 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002703 FieldTypes[i], 0,
2704 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002705 /*Mutable=*/false));
Douglas Gregor91f84212008-12-11 16:49:14 +00002706 }
Mike Stump11289f42009-09-09 15:08:12 +00002707
Douglas Gregord5058122010-02-11 01:19:42 +00002708 SuperStructDecl->completeDefinition();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002709 }
2710 return Context->getTagDeclType(SuperStructDecl);
2711}
2712
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002713QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffce8e8862008-03-15 00:55:56 +00002714 if (!ConstantStringDecl) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00002715 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002716 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002717 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffce8e8862008-03-15 00:55:56 +00002718 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002719
Steve Naroffce8e8862008-03-15 00:55:56 +00002720 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002721 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffce8e8862008-03-15 00:55:56 +00002722 // int flags;
Mike Stump11289f42009-09-09 15:08:12 +00002723 FieldTypes[1] = Context->IntTy;
Steve Naroffce8e8862008-03-15 00:55:56 +00002724 // char *str;
Mike Stump11289f42009-09-09 15:08:12 +00002725 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffce8e8862008-03-15 00:55:56 +00002726 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002727 FieldTypes[3] = Context->LongTy;
Douglas Gregor91f84212008-12-11 16:49:14 +00002728
Steve Naroffce8e8862008-03-15 00:55:56 +00002729 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002730 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002731 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2732 ConstantStringDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002733 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002734 FieldTypes[i], 0,
Douglas Gregor91f84212008-12-11 16:49:14 +00002735 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002736 /*Mutable=*/true));
Douglas Gregor91f84212008-12-11 16:49:14 +00002737 }
2738
Douglas Gregord5058122010-02-11 01:19:42 +00002739 ConstantStringDecl->completeDefinition();
Steve Naroffce8e8862008-03-15 00:55:56 +00002740 }
2741 return Context->getTagDeclType(ConstantStringDecl);
2742}
2743
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002744Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2745 SourceLocation StartLoc,
2746 SourceLocation EndLoc) {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002747 if (!SelGetUidFunctionDecl)
2748 SynthSelGetUidFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002749 if (!MsgSendFunctionDecl)
2750 SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002751 if (!MsgSendSuperFunctionDecl)
2752 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002753 if (!MsgSendStretFunctionDecl)
2754 SynthMsgSendStretFunctionDecl();
2755 if (!MsgSendSuperStretFunctionDecl)
2756 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002757 if (!MsgSendFpretFunctionDecl)
2758 SynthMsgSendFpretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002759 if (!GetClassFunctionDecl)
2760 SynthGetClassFunctionDecl();
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002761 if (!GetSuperClassFunctionDecl)
2762 SynthGetSuperClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002763 if (!GetMetaClassFunctionDecl)
2764 SynthGetMetaClassFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002765
Steve Naroff7fa2f042007-11-15 10:28:18 +00002766 // default to objc_msgSend().
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002767 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2768 // May need to use objc_msgSend_stret() as well.
2769 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroffd9803712009-04-29 16:37:50 +00002770 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2771 QualType resultType = mDecl->getResultType();
Douglas Gregor8385a062010-04-26 21:31:17 +00002772 if (resultType->isRecordType())
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002773 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002774 else if (resultType->isRealFloatingType())
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002775 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002776 }
Mike Stump11289f42009-09-09 15:08:12 +00002777
Steve Naroff574440f2007-10-24 22:48:43 +00002778 // Synthesize a call to objc_msgSend().
2779 llvm::SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor9a129192010-04-21 00:45:42 +00002780 switch (Exp->getReceiverKind()) {
2781 case ObjCMessageExpr::SuperClass: {
2782 MsgSendFlavor = MsgSendSuperFunctionDecl;
2783 if (MsgSendStretFlavor)
2784 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2785 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002786
Douglas Gregor9a129192010-04-21 00:45:42 +00002787 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00002788
Douglas Gregor9a129192010-04-21 00:45:42 +00002789 llvm::SmallVector<Expr*, 4> InitExprs;
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002790
Douglas Gregor9a129192010-04-21 00:45:42 +00002791 // set the receiver to self, the first argument to all methods.
2792 InitExprs.push_back(
2793 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002794 CK_BitCast,
Douglas Gregor9a129192010-04-21 00:45:42 +00002795 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall7decc9e2010-11-18 06:31:45 +00002796 Context->getObjCIdType(),
2797 VK_RValue,
2798 SourceLocation()))
Douglas Gregor9a129192010-04-21 00:45:42 +00002799 ); // set the 'receiver'.
Mike Stump11289f42009-09-09 15:08:12 +00002800
Douglas Gregor9a129192010-04-21 00:45:42 +00002801 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2802 llvm::SmallVector<Expr*, 8> ClsExprs;
2803 QualType argType = Context->getPointerType(Context->CharTy);
2804 ClsExprs.push_back(StringLiteral::Create(*Context,
2805 ClassDecl->getIdentifier()->getNameStart(),
2806 ClassDecl->getIdentifier()->getLength(),
2807 false, argType, SourceLocation()));
2808 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2809 &ClsExprs[0],
2810 ClsExprs.size(),
2811 StartLoc,
2812 EndLoc);
2813 // (Class)objc_getClass("CurrentClass")
2814 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2815 Context->getObjCClassType(),
John McCallf608deb2010-11-15 09:46:46 +00002816 CK_BitCast, Cls);
Douglas Gregor9a129192010-04-21 00:45:42 +00002817 ClsExprs.clear();
2818 ClsExprs.push_back(ArgExpr);
2819 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2820 &ClsExprs[0], ClsExprs.size(),
2821 StartLoc, EndLoc);
2822
2823 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2824 // To turn off a warning, type-cast to 'id'
2825 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2826 NoTypeInfoCStyleCastExpr(Context,
2827 Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002828 CK_BitCast, Cls));
Douglas Gregor9a129192010-04-21 00:45:42 +00002829 // struct objc_super
2830 QualType superType = getSuperStructType();
2831 Expr *SuperRep;
Steve Naroffd9803712009-04-29 16:37:50 +00002832
Douglas Gregor9a129192010-04-21 00:45:42 +00002833 if (LangOpts.Microsoft) {
2834 SynthSuperContructorFunctionDecl();
2835 // Simulate a contructor call...
2836 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCall7decc9e2010-11-18 06:31:45 +00002837 superType, VK_LValue,
2838 SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002839 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2840 InitExprs.size(),
John McCall7decc9e2010-11-18 06:31:45 +00002841 superType, VK_LValue,
2842 SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002843 // The code for super is a little tricky to prevent collision with
2844 // the structure definition in the header. The rewriter has it's own
2845 // internal definition (__rw_objc_super) that is uses. This is why
2846 // we need the cast below. For example:
2847 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2848 //
John McCalle3027922010-08-25 11:45:40 +00002849 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002850 Context->getPointerType(SuperRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002851 VK_RValue, OK_Ordinary,
2852 SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002853 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2854 Context->getPointerType(superType),
John McCallf608deb2010-11-15 09:46:46 +00002855 CK_BitCast, SuperRep);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002856 } else {
Douglas Gregor9a129192010-04-21 00:45:42 +00002857 // (struct objc_super) { <exprs from above> }
2858 InitListExpr *ILE =
2859 new (Context) InitListExpr(*Context, SourceLocation(),
2860 &InitExprs[0], InitExprs.size(),
2861 SourceLocation());
2862 TypeSourceInfo *superTInfo
2863 = Context->getTrivialTypeSourceInfo(superType);
2864 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCall7decc9e2010-11-18 06:31:45 +00002865 superType, VK_LValue,
2866 ILE, false);
Douglas Gregor9a129192010-04-21 00:45:42 +00002867 // struct objc_super *
John McCalle3027922010-08-25 11:45:40 +00002868 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002869 Context->getPointerType(SuperRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002870 VK_RValue, OK_Ordinary,
2871 SourceLocation());
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002872 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002873 MsgExprs.push_back(SuperRep);
2874 break;
Steve Naroffe7f18192007-11-14 23:54:14 +00002875 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002876
2877 case ObjCMessageExpr::Class: {
2878 llvm::SmallVector<Expr*, 8> ClsExprs;
2879 QualType argType = Context->getPointerType(Context->CharTy);
2880 ObjCInterfaceDecl *Class
John McCall96fa4842010-05-17 21:00:27 +00002881 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor9a129192010-04-21 00:45:42 +00002882 IdentifierInfo *clsName = Class->getIdentifier();
2883 ClsExprs.push_back(StringLiteral::Create(*Context,
2884 clsName->getNameStart(),
2885 clsName->getLength(),
2886 false, argType,
2887 SourceLocation()));
2888 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2889 &ClsExprs[0],
2890 ClsExprs.size(),
2891 StartLoc, EndLoc);
2892 MsgExprs.push_back(Cls);
2893 break;
2894 }
2895
2896 case ObjCMessageExpr::SuperInstance:{
2897 MsgSendFlavor = MsgSendSuperFunctionDecl;
2898 if (MsgSendStretFlavor)
2899 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2900 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2901 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2902 llvm::SmallVector<Expr*, 4> InitExprs;
2903
2904 InitExprs.push_back(
2905 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002906 CK_BitCast,
Douglas Gregor9a129192010-04-21 00:45:42 +00002907 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall7decc9e2010-11-18 06:31:45 +00002908 Context->getObjCIdType(),
2909 VK_RValue, SourceLocation()))
Douglas Gregor9a129192010-04-21 00:45:42 +00002910 ); // set the 'receiver'.
2911
2912 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2913 llvm::SmallVector<Expr*, 8> ClsExprs;
2914 QualType argType = Context->getPointerType(Context->CharTy);
2915 ClsExprs.push_back(StringLiteral::Create(*Context,
2916 ClassDecl->getIdentifier()->getNameStart(),
2917 ClassDecl->getIdentifier()->getLength(),
2918 false, argType, SourceLocation()));
2919 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2920 &ClsExprs[0],
2921 ClsExprs.size(),
2922 StartLoc, EndLoc);
2923 // (Class)objc_getClass("CurrentClass")
2924 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2925 Context->getObjCClassType(),
John McCallf608deb2010-11-15 09:46:46 +00002926 CK_BitCast, Cls);
Douglas Gregor9a129192010-04-21 00:45:42 +00002927 ClsExprs.clear();
2928 ClsExprs.push_back(ArgExpr);
2929 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2930 &ClsExprs[0], ClsExprs.size(),
2931 StartLoc, EndLoc);
2932
2933 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2934 // To turn off a warning, type-cast to 'id'
2935 InitExprs.push_back(
2936 // set 'super class', using class_getSuperclass().
2937 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002938 CK_BitCast, Cls));
Douglas Gregor9a129192010-04-21 00:45:42 +00002939 // struct objc_super
2940 QualType superType = getSuperStructType();
2941 Expr *SuperRep;
2942
2943 if (LangOpts.Microsoft) {
2944 SynthSuperContructorFunctionDecl();
2945 // Simulate a contructor call...
2946 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCall7decc9e2010-11-18 06:31:45 +00002947 superType, VK_LValue,
2948 SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002949 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2950 InitExprs.size(),
John McCall7decc9e2010-11-18 06:31:45 +00002951 superType, VK_LValue, SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002952 // The code for super is a little tricky to prevent collision with
2953 // the structure definition in the header. The rewriter has it's own
2954 // internal definition (__rw_objc_super) that is uses. This is why
2955 // we need the cast below. For example:
2956 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2957 //
John McCalle3027922010-08-25 11:45:40 +00002958 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002959 Context->getPointerType(SuperRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002960 VK_RValue, OK_Ordinary,
Douglas Gregor9a129192010-04-21 00:45:42 +00002961 SourceLocation());
2962 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2963 Context->getPointerType(superType),
John McCallf608deb2010-11-15 09:46:46 +00002964 CK_BitCast, SuperRep);
Douglas Gregor9a129192010-04-21 00:45:42 +00002965 } else {
2966 // (struct objc_super) { <exprs from above> }
2967 InitListExpr *ILE =
2968 new (Context) InitListExpr(*Context, SourceLocation(),
2969 &InitExprs[0], InitExprs.size(),
2970 SourceLocation());
2971 TypeSourceInfo *superTInfo
2972 = Context->getTrivialTypeSourceInfo(superType);
2973 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCall7decc9e2010-11-18 06:31:45 +00002974 superType, VK_RValue, ILE,
2975 false);
Douglas Gregor9a129192010-04-21 00:45:42 +00002976 }
2977 MsgExprs.push_back(SuperRep);
2978 break;
2979 }
2980
2981 case ObjCMessageExpr::Instance: {
2982 // Remove all type-casts because it may contain objc-style types; e.g.
2983 // Foo<Proto> *.
2984 Expr *recExpr = Exp->getInstanceReceiver();
2985 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2986 recExpr = CE->getSubExpr();
2987 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002988 CK_BitCast, recExpr);
Douglas Gregor9a129192010-04-21 00:45:42 +00002989 MsgExprs.push_back(recExpr);
2990 break;
2991 }
2992 }
2993
Steve Naroffa397efd2007-11-03 11:27:19 +00002994 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff574440f2007-10-24 22:48:43 +00002995 llvm::SmallVector<Expr*, 8> SelExprs;
2996 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002997 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002998 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002999 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00003000 false, argType, SourceLocation()));
Steve Naroff574440f2007-10-24 22:48:43 +00003001 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00003002 &SelExprs[0], SelExprs.size(),
3003 StartLoc,
3004 EndLoc);
Steve Naroff574440f2007-10-24 22:48:43 +00003005 MsgExprs.push_back(SelExp);
Mike Stump11289f42009-09-09 15:08:12 +00003006
Steve Naroff574440f2007-10-24 22:48:43 +00003007 // Now push any user supplied arguments.
3008 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroffe7f18192007-11-14 23:54:14 +00003009 Expr *userExpr = Exp->getArg(i);
Steve Narofff60782b2007-11-15 02:58:25 +00003010 // Make all implicit casts explicit...ICE comes in handy:-)
3011 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3012 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregore200adc2008-10-27 19:41:14 +00003013 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003014 ? Context->getObjCIdType()
Douglas Gregore200adc2008-10-27 19:41:14 +00003015 : ICE->getType();
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003016 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00003017 (void)convertBlockPointerToFunctionPointer(type);
John McCallf608deb2010-11-15 09:46:46 +00003018 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00003019 userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00003020 }
3021 // Make id<P...> cast into an 'id' cast.
Douglas Gregorf19b2312008-10-28 15:36:24 +00003022 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003023 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregorf19b2312008-10-28 15:36:24 +00003024 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00003025 userExpr = CE->getSubExpr();
John McCall97513962010-01-15 18:39:57 +00003026 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00003027 CK_BitCast, userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00003028 }
Mike Stump11289f42009-09-09 15:08:12 +00003029 }
Steve Naroffe7f18192007-11-14 23:54:14 +00003030 MsgExprs.push_back(userExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00003031 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3032 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003033 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00003034 //Exp->setArg(i, 0);
Steve Naroff574440f2007-10-24 22:48:43 +00003035 }
Steve Narofff36987c2007-11-04 22:37:50 +00003036 // Generate the funky cast.
3037 CastExpr *cast;
3038 llvm::SmallVector<QualType, 8> ArgTypes;
3039 QualType returnType;
Mike Stump11289f42009-09-09 15:08:12 +00003040
Steve Narofff36987c2007-11-04 22:37:50 +00003041 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff44864e42007-11-15 10:43:57 +00003042 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3043 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3044 else
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003045 ArgTypes.push_back(Context->getObjCIdType());
3046 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattnera4997152009-02-20 18:43:26 +00003047 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Narofff36987c2007-11-04 22:37:50 +00003048 // Push any user argument types.
Chris Lattnera4997152009-02-20 18:43:26 +00003049 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3050 E = OMD->param_end(); PI != E; ++PI) {
3051 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump11289f42009-09-09 15:08:12 +00003052 ? Context->getObjCIdType()
Chris Lattnera4997152009-02-20 18:43:26 +00003053 : (*PI)->getType();
Steve Naroff52c65fa2008-10-29 14:49:46 +00003054 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00003055 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff98eb8d12007-11-05 14:36:37 +00003056 ArgTypes.push_back(t);
3057 }
Chris Lattnera4997152009-02-20 18:43:26 +00003058 returnType = OMD->getResultType()->isObjCQualifiedIdType()
3059 ? Context->getObjCIdType() : OMD->getResultType();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00003060 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Narofff36987c2007-11-04 22:37:50 +00003061 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003062 returnType = Context->getObjCIdType();
Steve Narofff36987c2007-11-04 22:37:50 +00003063 }
3064 // Get the type, we will need to reference it in a couple spots.
Steve Naroff7fa2f042007-11-15 10:28:18 +00003065 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003066
Steve Narofff36987c2007-11-04 22:37:50 +00003067 // Create a reference to the objc_msgSend() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003068 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
John McCall7decc9e2010-11-18 06:31:45 +00003069 VK_LValue, SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00003070
Mike Stump11289f42009-09-09 15:08:12 +00003071 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Narofff36987c2007-11-04 22:37:50 +00003072 // If we don't do this cast, we get the following bizarre warning/note:
3073 // xx.m:13: warning: function called through a non-compatible type
3074 // xx.m:13: note: if this code is reached, the program will abort
John McCall97513962010-01-15 18:39:57 +00003075 cast = NoTypeInfoCStyleCastExpr(Context,
3076 Context->getPointerType(Context->VoidTy),
John McCallf608deb2010-11-15 09:46:46 +00003077 CK_BitCast, DRE);
Mike Stump11289f42009-09-09 15:08:12 +00003078
Steve Narofff36987c2007-11-04 22:37:50 +00003079 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00003080 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00003081 &ArgTypes[0], ArgTypes.size(),
Steve Naroff327f0f42008-03-18 02:02:04 +00003082 // If we don't have a method decl, force a variadic cast.
Douglas Gregor36c569f2010-02-21 22:15:06 +00003083 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003084 false, false, 0, 0,
3085 FunctionType::ExtInfo());
Steve Narofff36987c2007-11-04 22:37:50 +00003086 castType = Context->getPointerType(castType);
John McCallf608deb2010-11-15 09:46:46 +00003087 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00003088 cast);
Steve Narofff36987c2007-11-04 22:37:50 +00003089
3090 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00003091 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump11289f42009-09-09 15:08:12 +00003092
John McCall9dd450b2009-09-21 23:43:11 +00003093 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003094 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00003095 MsgExprs.size(),
John McCall7decc9e2010-11-18 06:31:45 +00003096 FT->getResultType(), VK_RValue,
3097 EndLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003098 Stmt *ReplacingStmt = CE;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003099 if (MsgSendStretFlavor) {
3100 // We have the method which returns a struct/union. Must also generate
3101 // call to objc_msgSend_stret and hang both varieties on a conditional
3102 // expression which dictate which one to envoke depending on size of
3103 // method's return type.
Mike Stump11289f42009-09-09 15:08:12 +00003104
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003105 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003106 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
John McCall7decc9e2010-11-18 06:31:45 +00003107 VK_LValue, SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003108 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall97513962010-01-15 18:39:57 +00003109 cast = NoTypeInfoCStyleCastExpr(Context,
3110 Context->getPointerType(Context->VoidTy),
John McCallf608deb2010-11-15 09:46:46 +00003111 CK_BitCast, STDRE);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003112 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00003113 castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00003114 &ArgTypes[0], ArgTypes.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00003115 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003116 false, false, 0, 0,
3117 FunctionType::ExtInfo());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003118 castType = Context->getPointerType(castType);
John McCallf608deb2010-11-15 09:46:46 +00003119 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00003120 cast);
Mike Stump11289f42009-09-09 15:08:12 +00003121
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003122 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00003123 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00003124
John McCall9dd450b2009-09-21 23:43:11 +00003125 FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003126 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00003127 MsgExprs.size(),
John McCall7decc9e2010-11-18 06:31:45 +00003128 FT->getResultType(), VK_RValue,
3129 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00003130
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003131 // Build sizeof(returnType)
Mike Stump11289f42009-09-09 15:08:12 +00003132 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCallbcd03502009-12-07 02:54:59 +00003133 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl6f282892008-11-11 17:56:53 +00003134 Context->getSizeType(),
3135 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003136 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3137 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3138 // For X86 it is more complicated and some kind of target specific routine
3139 // is needed to decide what to do.
Mike Stump11289f42009-09-09 15:08:12 +00003140 unsigned IntSize =
Chris Lattner37e05872008-03-05 18:54:05 +00003141 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00003142 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3143 llvm::APInt(IntSize, 8),
3144 Context->IntTy,
3145 SourceLocation());
John McCall7decc9e2010-11-18 06:31:45 +00003146 BinaryOperator *lessThanExpr =
3147 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3148 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003149 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump11289f42009-09-09 15:08:12 +00003150 ConditionalOperator *CondExpr =
Douglas Gregor7e112b02009-08-26 14:37:04 +00003151 new (Context) ConditionalOperator(lessThanExpr,
3152 SourceLocation(), CE,
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00003153 SourceLocation(), STCE, (Expr*)0,
John McCall4bc41ae2010-11-18 19:01:18 +00003154 returnType, VK_RValue, OK_Ordinary);
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00003155 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3156 CondExpr);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003157 }
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003158 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003159 return ReplacingStmt;
3160}
3161
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003162Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00003163 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3164 Exp->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003165
Steve Naroff574440f2007-10-24 22:48:43 +00003166 // Now do the actual rewrite.
Chris Lattner2e0d2602008-01-31 19:37:57 +00003167 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00003168
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003169 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003170 return ReplacingStmt;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00003171}
3172
Steve Naroffd9803712009-04-29 16:37:50 +00003173// typedef struct objc_object Protocol;
3174QualType RewriteObjC::getProtocolType() {
3175 if (!ProtocolTypeDecl) {
John McCallbcd03502009-12-07 02:54:59 +00003176 TypeSourceInfo *TInfo
3177 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroffd9803712009-04-29 16:37:50 +00003178 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00003179 SourceLocation(),
Steve Naroffd9803712009-04-29 16:37:50 +00003180 &Context->Idents.get("Protocol"),
John McCallbcd03502009-12-07 02:54:59 +00003181 TInfo);
Steve Naroffd9803712009-04-29 16:37:50 +00003182 }
3183 return Context->getTypeDeclType(ProtocolTypeDecl);
3184}
3185
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00003186/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroffd9803712009-04-29 16:37:50 +00003187/// a synthesized/forward data reference (to the protocol's metadata).
3188/// The forward references (and metadata) are generated in
3189/// RewriteObjC::HandleTranslationUnit().
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003190Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroffd9803712009-04-29 16:37:50 +00003191 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3192 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump11289f42009-09-09 15:08:12 +00003193 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00003194 ID, getProtocolType(), 0,
John McCall8e7d6562010-08-26 03:08:43 +00003195 SC_Extern, SC_None);
John McCall7decc9e2010-11-18 06:31:45 +00003196 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), VK_LValue,
3197 SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00003198 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroffd9803712009-04-29 16:37:50 +00003199 Context->getPointerType(DRE->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00003200 VK_RValue, OK_Ordinary, SourceLocation());
John McCall97513962010-01-15 18:39:57 +00003201 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCallf608deb2010-11-15 09:46:46 +00003202 CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00003203 DerefExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00003204 ReplaceStmt(Exp, castExpr);
3205 ProtocolExprDecls.insert(Exp->getProtocol());
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003206 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00003207 return castExpr;
Mike Stump11289f42009-09-09 15:08:12 +00003208
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00003209}
3210
Mike Stump11289f42009-09-09 15:08:12 +00003211bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003212 const char *endBuf) {
3213 while (startBuf < endBuf) {
3214 if (*startBuf == '#') {
3215 // Skip whitespace.
3216 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3217 ;
3218 if (!strncmp(startBuf, "if", strlen("if")) ||
3219 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3220 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3221 !strncmp(startBuf, "define", strlen("define")) ||
3222 !strncmp(startBuf, "undef", strlen("undef")) ||
3223 !strncmp(startBuf, "else", strlen("else")) ||
3224 !strncmp(startBuf, "elif", strlen("elif")) ||
3225 !strncmp(startBuf, "endif", strlen("endif")) ||
3226 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3227 !strncmp(startBuf, "include", strlen("include")) ||
3228 !strncmp(startBuf, "import", strlen("import")) ||
3229 !strncmp(startBuf, "include_next", strlen("include_next")))
3230 return true;
3231 }
3232 startBuf++;
3233 }
3234 return false;
3235}
3236
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003237/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003238/// an objective-c class with ivars.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003239void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003240 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003241 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar56df9772010-08-17 22:39:59 +00003242 assert(CDecl->getName() != "" &&
Douglas Gregor77324f32008-11-17 14:58:09 +00003243 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00003244 // Do not synthesize more than once.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003245 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00003246 return;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003247 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003248 int NumIvars = CDecl->ivar_size();
Steve Naroffdde78982007-11-14 19:25:57 +00003249 SourceLocation LocStart = CDecl->getLocStart();
3250 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00003251
Steve Naroffdde78982007-11-14 19:25:57 +00003252 const char *startBuf = SM->getCharacterData(LocStart);
3253 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00003254
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003255 // If no ivars and no root or if its root, directly or indirectly,
3256 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003257 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3258 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner184e65d2009-04-14 23:22:57 +00003259 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003260 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003261 return;
3262 }
Mike Stump11289f42009-09-09 15:08:12 +00003263
3264 // FIXME: This has potential of causing problem. If
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003265 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003266 Result += "\nstruct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003267 Result += CDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00003268 if (LangOpts.Microsoft)
3269 Result += "_IMPL";
Steve Naroffdc5b6b22008-03-12 00:25:36 +00003270
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003271 if (NumIvars > 0) {
Steve Naroffdde78982007-11-14 19:25:57 +00003272 const char *cursor = strchr(startBuf, '{');
Mike Stump11289f42009-09-09 15:08:12 +00003273 assert((cursor && endBuf)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003274 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003275 // If the buffer contains preprocessor directives, we do more fine-grained
3276 // rewrites. This is intended to fix code that looks like (which occurs in
3277 // NSURL.h, for example):
3278 //
3279 // #ifdef XYZ
3280 // @interface Foo : NSObject
3281 // #else
3282 // @interface FooBar : NSObject
3283 // #endif
3284 // {
3285 // int i;
3286 // }
3287 // @end
3288 //
3289 // This clause is segregated to avoid breaking the common case.
3290 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump11289f42009-09-09 15:08:12 +00003291 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003292 CDecl->getClassLoc();
3293 const char *endHeader = SM->getCharacterData(L);
Chris Lattner184e65d2009-04-14 23:22:57 +00003294 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003295
Chris Lattnerf5b77512009-02-20 18:18:36 +00003296 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003297 // advance to the end of the referenced protocols.
3298 while (endHeader < cursor && *endHeader != '>') endHeader++;
3299 endHeader++;
3300 }
3301 // rewrite the original header
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003302 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003303 } else {
3304 // rewrite the original header *without* disturbing the '{'
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003305 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003306 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003307 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroffdde78982007-11-14 19:25:57 +00003308 Result = "\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003309 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003310 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003311 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003312 Result += "_IVARS;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003313
Steve Naroffdde78982007-11-14 19:25:57 +00003314 // insert the super class structure definition.
Chris Lattner1780a852008-01-31 19:42:41 +00003315 SourceLocation OnePastCurly =
3316 LocStart.getFileLocWithOffset(cursor-startBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003317 InsertText(OnePastCurly, Result);
Steve Naroffdde78982007-11-14 19:25:57 +00003318 }
3319 cursor++; // past '{'
Mike Stump11289f42009-09-09 15:08:12 +00003320
Steve Naroffdde78982007-11-14 19:25:57 +00003321 // Now comment out any visibility specifiers.
3322 while (cursor < endBuf) {
3323 if (*cursor == '@') {
3324 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner174a8252007-11-14 22:57:51 +00003325 // Skip whitespace.
3326 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3327 /*scan*/;
3328
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003329 // FIXME: presence of @public, etc. inside comment results in
3330 // this transformation as well, which is still correct c-code.
Steve Naroffdde78982007-11-14 19:25:57 +00003331 if (!strncmp(cursor, "public", strlen("public")) ||
3332 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffaf91b9a2008-04-04 22:34:24 +00003333 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003334 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003335 InsertText(atLoc, "// ");
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003336 }
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003337 // FIXME: If there are cases where '<' is used in ivar declaration part
3338 // of user code, then scan the ivar list and use needToScanForQualifiers
3339 // for type checking.
3340 else if (*cursor == '<') {
3341 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003342 InsertText(atLoc, "/* ");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003343 cursor = strchr(cursor, '>');
3344 cursor++;
3345 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003346 InsertText(atLoc, " */");
Steve Naroff295570a2008-10-30 12:09:33 +00003347 } else if (*cursor == '^') { // rewrite block specifier.
3348 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003349 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003350 }
Steve Naroffdde78982007-11-14 19:25:57 +00003351 cursor++;
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003352 }
Steve Naroffdde78982007-11-14 19:25:57 +00003353 // Don't forget to add a ';'!!
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003354 InsertText(LocEnd.getFileLocWithOffset(1), ";");
Steve Naroffdde78982007-11-14 19:25:57 +00003355 } else { // we don't have any instance variables - insert super struct.
Chris Lattner184e65d2009-04-14 23:22:57 +00003356 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroffdde78982007-11-14 19:25:57 +00003357 Result += " {\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003358 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003359 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003360 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003361 Result += "_IVARS;\n};\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003362 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003363 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003364 // Mark this struct as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003365 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff13e74872008-05-06 18:26:51 +00003366 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003367}
3368
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003369// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003370/// class methods.
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003371template<typename MethodIterator>
3372void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3373 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +00003374 bool IsInstanceMethod,
Daniel Dunbar56df9772010-08-17 22:39:59 +00003375 llvm::StringRef prefix,
3376 llvm::StringRef ClassName,
Chris Lattner211f8b82007-10-25 17:07:24 +00003377 std::string &Result) {
Chris Lattner31bc07e2007-12-12 07:46:12 +00003378 if (MethodBegin == MethodEnd) return;
Mike Stump11289f42009-09-09 15:08:12 +00003379
Chris Lattner31bc07e2007-12-12 07:46:12 +00003380 if (!objc_impl_method) {
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003381 /* struct _objc_method {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003382 SEL _cmd;
3383 char *method_types;
3384 void *_imp;
3385 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003386 */
Chris Lattner211f8b82007-10-25 17:07:24 +00003387 Result += "\nstruct _objc_method {\n";
3388 Result += "\tSEL _cmd;\n";
3389 Result += "\tchar *method_types;\n";
3390 Result += "\tvoid *_imp;\n";
3391 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003392
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003393 objc_impl_method = true;
Fariborz Jahanian74a1cfa2007-10-19 00:36:46 +00003394 }
Mike Stump11289f42009-09-09 15:08:12 +00003395
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003396 // Build _objc_method_list for class's methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003397
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003398 /* struct {
3399 struct _objc_method_list *next_method;
3400 int method_count;
3401 struct _objc_method method_list[];
3402 }
3403 */
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003404 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003405 Result += "\nstatic struct {\n";
3406 Result += "\tstruct _objc_method_list *next_method;\n";
3407 Result += "\tint method_count;\n";
3408 Result += "\tstruct _objc_method method_list[";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003409 Result += utostr(NumMethods);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003410 Result += "];\n} _OBJC_";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003411 Result += prefix;
3412 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3413 Result += "_METHODS_";
3414 Result += ClassName;
Steve Naroffb327e492008-03-12 17:18:30 +00003415 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003416 Result += IsInstanceMethod ? "inst" : "cls";
3417 Result += "_meth\")))= ";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003418 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003419
Chris Lattner31bc07e2007-12-12 07:46:12 +00003420 Result += "\t,{{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003421 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattner31bc07e2007-12-12 07:46:12 +00003422 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003423 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattner31bc07e2007-12-12 07:46:12 +00003424 Result += "\", \"";
3425 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003426 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003427 Result += MethodInternalNames[*MethodBegin];
3428 Result += "}\n";
3429 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3430 Result += "\t ,{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003431 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003432 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003433 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003434 Result += "\", \"";
3435 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003436 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003437 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanian56338352007-11-13 21:02:00 +00003438 Result += "}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003439 }
Chris Lattner31bc07e2007-12-12 07:46:12 +00003440 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003441}
3442
Steve Naroffd9803712009-04-29 16:37:50 +00003443/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner390d39a2008-07-21 21:32:27 +00003444void RewriteObjC::
Daniel Dunbar56df9772010-08-17 22:39:59 +00003445RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, llvm::StringRef prefix,
3446 llvm::StringRef ClassName, std::string &Result) {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003447 static bool objc_protocol_methods = false;
Steve Naroffd9803712009-04-29 16:37:50 +00003448
3449 // Output struct protocol_methods holder of method selector and type.
3450 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3451 /* struct protocol_methods {
3452 SEL _cmd;
3453 char *method_types;
3454 }
3455 */
3456 Result += "\nstruct _protocol_methods {\n";
3457 Result += "\tstruct objc_selector *_cmd;\n";
3458 Result += "\tchar *method_types;\n";
3459 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003460
Steve Naroffd9803712009-04-29 16:37:50 +00003461 objc_protocol_methods = true;
3462 }
3463 // Do not synthesize the protocol more than once.
3464 if (ObjCSynthesizedProtocols.count(PDecl))
3465 return;
Mike Stump11289f42009-09-09 15:08:12 +00003466
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003467 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3468 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3469 PDecl->instmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003470 /* struct _objc_protocol_method_list {
3471 int protocol_method_count;
3472 struct protocol_methods protocols[];
3473 }
Steve Naroff251084d2008-03-12 01:06:30 +00003474 */
Steve Naroffd9803712009-04-29 16:37:50 +00003475 Result += "\nstatic struct {\n";
3476 Result += "\tint protocol_method_count;\n";
3477 Result += "\tstruct _protocol_methods protocol_methods[";
3478 Result += utostr(NumMethods);
3479 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3480 Result += PDecl->getNameAsString();
3481 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3482 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003483
Steve Naroffd9803712009-04-29 16:37:50 +00003484 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003485 for (ObjCProtocolDecl::instmeth_iterator
3486 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003487 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003488 if (I == PDecl->instmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003489 Result += "\t ,{{(struct objc_selector *)\"";
3490 else
3491 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar56df9772010-08-17 22:39:59 +00003492 Result += (*I)->getSelector().getAsString();
Steve Naroffd9803712009-04-29 16:37:50 +00003493 std::string MethodTypeString;
3494 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3495 Result += "\", \"";
3496 Result += MethodTypeString;
3497 Result += "\"}\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003498 }
Steve Naroffd9803712009-04-29 16:37:50 +00003499 Result += "\t }\n};\n";
3500 }
Mike Stump11289f42009-09-09 15:08:12 +00003501
Steve Naroffd9803712009-04-29 16:37:50 +00003502 // Output class methods declared in this protocol.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003503 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3504 PDecl->classmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003505 if (NumMethods > 0) {
3506 /* struct _objc_protocol_method_list {
3507 int protocol_method_count;
3508 struct protocol_methods protocols[];
3509 }
3510 */
3511 Result += "\nstatic struct {\n";
3512 Result += "\tint protocol_method_count;\n";
3513 Result += "\tstruct _protocol_methods protocol_methods[";
3514 Result += utostr(NumMethods);
3515 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3516 Result += PDecl->getNameAsString();
3517 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3518 "{\n\t";
3519 Result += utostr(NumMethods);
3520 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003521
Steve Naroffd9803712009-04-29 16:37:50 +00003522 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003523 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003524 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003525 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003526 if (I == PDecl->classmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003527 Result += "\t ,{{(struct objc_selector *)\"";
3528 else
3529 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar56df9772010-08-17 22:39:59 +00003530 Result += (*I)->getSelector().getAsString();
Steve Naroffd9803712009-04-29 16:37:50 +00003531 std::string MethodTypeString;
3532 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3533 Result += "\", \"";
3534 Result += MethodTypeString;
3535 Result += "\"}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003536 }
Steve Naroffd9803712009-04-29 16:37:50 +00003537 Result += "\t }\n};\n";
3538 }
3539
3540 // Output:
3541 /* struct _objc_protocol {
3542 // Objective-C 1.0 extensions
3543 struct _objc_protocol_extension *isa;
3544 char *protocol_name;
3545 struct _objc_protocol **protocol_list;
3546 struct _objc_protocol_method_list *instance_methods;
3547 struct _objc_protocol_method_list *class_methods;
Mike Stump11289f42009-09-09 15:08:12 +00003548 };
Steve Naroffd9803712009-04-29 16:37:50 +00003549 */
3550 static bool objc_protocol = false;
3551 if (!objc_protocol) {
3552 Result += "\nstruct _objc_protocol {\n";
3553 Result += "\tstruct _objc_protocol_extension *isa;\n";
3554 Result += "\tchar *protocol_name;\n";
3555 Result += "\tstruct _objc_protocol **protocol_list;\n";
3556 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3557 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003558 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003559
Steve Naroffd9803712009-04-29 16:37:50 +00003560 objc_protocol = true;
Chris Lattner388f6e92008-07-21 21:33:21 +00003561 }
Mike Stump11289f42009-09-09 15:08:12 +00003562
Steve Naroffd9803712009-04-29 16:37:50 +00003563 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3564 Result += PDecl->getNameAsString();
3565 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3566 "{\n\t0, \"";
3567 Result += PDecl->getNameAsString();
3568 Result += "\", 0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003569 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003570 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3571 Result += PDecl->getNameAsString();
3572 Result += ", ";
3573 }
3574 else
3575 Result += "0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003576 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003577 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3578 Result += PDecl->getNameAsString();
3579 Result += "\n";
3580 }
3581 else
3582 Result += "0\n";
3583 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003584
Steve Naroffd9803712009-04-29 16:37:50 +00003585 // Mark this protocol as having been generated.
3586 if (!ObjCSynthesizedProtocols.insert(PDecl))
3587 assert(false && "protocol already synthesized");
3588
3589}
3590
3591void RewriteObjC::
3592RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
Daniel Dunbar56df9772010-08-17 22:39:59 +00003593 llvm::StringRef prefix, llvm::StringRef ClassName,
Steve Naroffd9803712009-04-29 16:37:50 +00003594 std::string &Result) {
3595 if (Protocols.empty()) return;
Mike Stump11289f42009-09-09 15:08:12 +00003596
Steve Naroffd9803712009-04-29 16:37:50 +00003597 for (unsigned i = 0; i != Protocols.size(); i++)
3598 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3599
Chris Lattner388f6e92008-07-21 21:33:21 +00003600 // Output the top lovel protocol meta-data for the class.
3601 /* struct _objc_protocol_list {
3602 struct _objc_protocol_list *next;
3603 int protocol_count;
3604 struct _objc_protocol *class_protocols[];
3605 }
3606 */
3607 Result += "\nstatic struct {\n";
3608 Result += "\tstruct _objc_protocol_list *next;\n";
3609 Result += "\tint protocol_count;\n";
3610 Result += "\tstruct _objc_protocol *class_protocols[";
3611 Result += utostr(Protocols.size());
3612 Result += "];\n} _OBJC_";
3613 Result += prefix;
3614 Result += "_PROTOCOLS_";
3615 Result += ClassName;
3616 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3617 "{\n\t0, ";
3618 Result += utostr(Protocols.size());
3619 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003620
Chris Lattner388f6e92008-07-21 21:33:21 +00003621 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003622 Result += Protocols[0]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003623 Result += " \n";
Mike Stump11289f42009-09-09 15:08:12 +00003624
Chris Lattner388f6e92008-07-21 21:33:21 +00003625 for (unsigned i = 1; i != Protocols.size(); i++) {
3626 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003627 Result += Protocols[i]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003628 Result += "\n";
3629 }
3630 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003631}
3632
Steve Naroffd9803712009-04-29 16:37:50 +00003633
Mike Stump11289f42009-09-09 15:08:12 +00003634/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003635/// implementation.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003636void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003637 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003638 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003639 // Find category declaration for this implementation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003640 ObjCCategoryDecl *CDecl;
Mike Stump11289f42009-09-09 15:08:12 +00003641 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003642 CDecl = CDecl->getNextClassCategory())
3643 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3644 break;
Mike Stump11289f42009-09-09 15:08:12 +00003645
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003646 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003647 FullCategoryName += '_';
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003648 FullCategoryName += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003649
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003650 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003651 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003652 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003653
3654 // If any of our property implementations have associated getters or
3655 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003656 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3657 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003658 Prop != PropEnd; ++Prop) {
3659 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3660 continue;
3661 if (!(*Prop)->getPropertyIvarDecl())
3662 continue;
3663 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3664 if (!PD)
3665 continue;
3666 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3667 InstanceMethods.push_back(Getter);
3668 if (PD->isReadOnly())
3669 continue;
3670 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3671 InstanceMethods.push_back(Setter);
3672 }
3673 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003674 true, "CATEGORY_", FullCategoryName.c_str(),
3675 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003676
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003677 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003678 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003679 false, "CATEGORY_", FullCategoryName.c_str(),
3680 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003681
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003682 // Protocols referenced in class declaration?
Fariborz Jahanian989e0392007-11-13 22:09:49 +00003683 // Null CDecl is case of a category implementation with no category interface
3684 if (CDecl)
Steve Naroffd9803712009-04-29 16:37:50 +00003685 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Daniel Dunbar56df9772010-08-17 22:39:59 +00003686 FullCategoryName, Result);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003687 /* struct _objc_category {
3688 char *category_name;
3689 char *class_name;
3690 struct _objc_method_list *instance_methods;
3691 struct _objc_method_list *class_methods;
3692 struct _objc_protocol_list *protocols;
3693 // Objective-C 1.0 extensions
3694 uint32_t size; // sizeof (struct _objc_category)
Mike Stump11289f42009-09-09 15:08:12 +00003695 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003696 // @property decl.
Mike Stump11289f42009-09-09 15:08:12 +00003697 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003698 */
Mike Stump11289f42009-09-09 15:08:12 +00003699
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003700 static bool objc_category = false;
3701 if (!objc_category) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003702 Result += "\nstruct _objc_category {\n";
3703 Result += "\tchar *category_name;\n";
3704 Result += "\tchar *class_name;\n";
3705 Result += "\tstruct _objc_method_list *instance_methods;\n";
3706 Result += "\tstruct _objc_method_list *class_methods;\n";
3707 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003708 Result += "\tunsigned int size;\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003709 Result += "\tstruct _objc_property_list *instance_properties;\n";
3710 Result += "};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003711 objc_category = true;
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003712 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003713 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3714 Result += FullCategoryName;
Steve Naroffb327e492008-03-12 17:18:30 +00003715 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003716 Result += IDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003717 Result += "\"\n\t, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003718 Result += ClassDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003719 Result += "\"\n";
Mike Stump11289f42009-09-09 15:08:12 +00003720
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003721 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003722 Result += "\t, (struct _objc_method_list *)"
3723 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3724 Result += FullCategoryName;
3725 Result += "\n";
3726 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003727 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003728 Result += "\t, 0\n";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003729 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003730 Result += "\t, (struct _objc_method_list *)"
3731 "&_OBJC_CATEGORY_CLASS_METHODS_";
3732 Result += FullCategoryName;
3733 Result += "\n";
3734 }
3735 else
3736 Result += "\t, 0\n";
Mike Stump11289f42009-09-09 15:08:12 +00003737
Chris Lattnerf5b77512009-02-20 18:18:36 +00003738 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump11289f42009-09-09 15:08:12 +00003739 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003740 Result += FullCategoryName;
3741 Result += "\n";
3742 }
3743 else
3744 Result += "\t, 0\n";
3745 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003746}
3747
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003748/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3749/// ivar offset.
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00003750void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003751 std::string &Result) {
Steve Naroffde7d0f62008-07-16 18:22:22 +00003752 if (ivar->isBitField()) {
3753 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3754 // place all bitfields at offset 0.
3755 Result += "0";
3756 } else {
3757 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00003758 Result += ivar->getContainingInterface()->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003759 if (LangOpts.Microsoft)
3760 Result += "_IMPL";
3761 Result += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003762 Result += ivar->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003763 Result += ")";
3764 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003765}
3766
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003767//===----------------------------------------------------------------------===//
3768// Meta Data Emission
3769//===----------------------------------------------------------------------===//
3770
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003771void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003772 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003773 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00003774
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003775 // Explictly declared @interface's are already synthesized.
Steve Naroffaac654a2009-04-20 20:09:33 +00003776 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump11289f42009-09-09 15:08:12 +00003777 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003778 // produce correct synthesis as yet.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003779 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003780 }
Mike Stump11289f42009-09-09 15:08:12 +00003781
Chris Lattner30d23e82007-12-12 07:56:42 +00003782 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003783 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump11289f42009-09-09 15:08:12 +00003784 ? IDecl->ivar_size()
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003785 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003786 if (NumIvars > 0) {
3787 static bool objc_ivar = false;
3788 if (!objc_ivar) {
3789 /* struct _objc_ivar {
3790 char *ivar_name;
3791 char *ivar_type;
3792 int ivar_offset;
Mike Stump11289f42009-09-09 15:08:12 +00003793 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003794 */
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003795 Result += "\nstruct _objc_ivar {\n";
3796 Result += "\tchar *ivar_name;\n";
3797 Result += "\tchar *ivar_type;\n";
3798 Result += "\tint ivar_offset;\n";
3799 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003800
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003801 objc_ivar = true;
3802 }
3803
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003804 /* struct {
3805 int ivar_count;
3806 struct _objc_ivar ivar_list[nIvars];
Mike Stump11289f42009-09-09 15:08:12 +00003807 };
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003808 */
Mike Stump11289f42009-09-09 15:08:12 +00003809 Result += "\nstatic struct {\n";
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003810 Result += "\tint ivar_count;\n";
3811 Result += "\tstruct _objc_ivar ivar_list[";
3812 Result += utostr(NumIvars);
3813 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003814 Result += IDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003815 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003816 "{\n\t";
3817 Result += utostr(NumIvars);
3818 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003819
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003820 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor5f662052009-04-23 03:23:08 +00003821 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003822 if (!IDecl->ivar_empty()) {
Fariborz Jahanianaef66222010-02-19 00:31:17 +00003823 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003824 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor5f662052009-04-23 03:23:08 +00003825 IV != IVEnd; ++IV)
3826 IVars.push_back(*IV);
Fariborz Jahanianaef66222010-02-19 00:31:17 +00003827 IVI = IDecl->ivar_begin();
3828 IVE = IDecl->ivar_end();
Chris Lattner30d23e82007-12-12 07:56:42 +00003829 } else {
3830 IVI = CDecl->ivar_begin();
3831 IVE = CDecl->ivar_end();
3832 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003833 Result += "\t,{{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003834 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003835 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003836 std::string TmpString, StrEncoding;
3837 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3838 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003839 Result += StrEncoding;
3840 Result += "\", ";
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00003841 SynthesizeIvarOffsetComputation(*IVI, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003842 Result += "}\n";
Chris Lattner30d23e82007-12-12 07:56:42 +00003843 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003844 Result += "\t ,{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003845 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003846 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003847 std::string TmpString, StrEncoding;
3848 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3849 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003850 Result += StrEncoding;
3851 Result += "\", ";
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00003852 SynthesizeIvarOffsetComputation((*IVI), Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003853 Result += "}\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003854 }
Mike Stump11289f42009-09-09 15:08:12 +00003855
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003856 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003857 }
Mike Stump11289f42009-09-09 15:08:12 +00003858
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003859 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003860 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003861 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003862
3863 // If any of our property implementations have associated getters or
3864 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003865 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3866 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003867 Prop != PropEnd; ++Prop) {
3868 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3869 continue;
3870 if (!(*Prop)->getPropertyIvarDecl())
3871 continue;
3872 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3873 if (!PD)
3874 continue;
3875 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +00003876 if (!Getter->isDefined())
3877 InstanceMethods.push_back(Getter);
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003878 if (PD->isReadOnly())
3879 continue;
3880 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +00003881 if (!Setter->isDefined())
3882 InstanceMethods.push_back(Setter);
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003883 }
3884 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Daniel Dunbar56df9772010-08-17 22:39:59 +00003885 true, "", IDecl->getName(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003886
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003887 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003888 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Daniel Dunbar56df9772010-08-17 22:39:59 +00003889 false, "", IDecl->getName(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003890
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003891 // Protocols referenced in class declaration?
Steve Naroffd9803712009-04-29 16:37:50 +00003892 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
Daniel Dunbar56df9772010-08-17 22:39:59 +00003893 "CLASS", CDecl->getName(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003894
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003895 // Declaration of class/meta-class metadata
3896 /* struct _objc_class {
3897 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003898 const char *super_class_name;
3899 char *name;
3900 long version;
3901 long info;
3902 long instance_size;
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003903 struct _objc_ivar_list *ivars;
3904 struct _objc_method_list *methods;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003905 struct objc_cache *cache;
3906 struct objc_protocol_list *protocols;
3907 const char *ivar_layout;
3908 struct _objc_class_ext *ext;
Mike Stump11289f42009-09-09 15:08:12 +00003909 };
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003910 */
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003911 static bool objc_class = false;
3912 if (!objc_class) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003913 Result += "\nstruct _objc_class {\n";
3914 Result += "\tstruct _objc_class *isa;\n";
3915 Result += "\tconst char *super_class_name;\n";
3916 Result += "\tchar *name;\n";
3917 Result += "\tlong version;\n";
3918 Result += "\tlong info;\n";
3919 Result += "\tlong instance_size;\n";
3920 Result += "\tstruct _objc_ivar_list *ivars;\n";
3921 Result += "\tstruct _objc_method_list *methods;\n";
3922 Result += "\tstruct objc_cache *cache;\n";
3923 Result += "\tstruct _objc_protocol_list *protocols;\n";
3924 Result += "\tconst char *ivar_layout;\n";
3925 Result += "\tstruct _objc_class_ext *ext;\n";
3926 Result += "};\n";
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003927 objc_class = true;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003928 }
Mike Stump11289f42009-09-09 15:08:12 +00003929
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003930 // Meta-class metadata generation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003931 ObjCInterfaceDecl *RootClass = 0;
3932 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003933 while (SuperClass) {
3934 RootClass = SuperClass;
3935 SuperClass = SuperClass->getSuperClass();
3936 }
3937 SuperClass = CDecl->getSuperClass();
Mike Stump11289f42009-09-09 15:08:12 +00003938
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003939 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003940 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003941 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003942 "{\n\t(struct _objc_class *)\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003943 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003944 Result += "\"";
3945
3946 if (SuperClass) {
3947 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003948 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003949 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003950 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003951 Result += "\"";
3952 }
3953 else {
3954 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003955 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003956 Result += "\"";
3957 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003958 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003959 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003960 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003961 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff0b844f02008-03-11 18:14:26 +00003962 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003963 Result += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003964 Result += "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003965 }
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003966 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003967 Result += ", 0\n";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003968 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003969 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003970 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003971 Result += ",0,0\n";
3972 }
Fariborz Jahanian486f7182007-10-24 20:54:23 +00003973 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003974 Result += "\t,0,0,0,0\n";
3975 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003976
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003977 // class metadata generation.
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003978 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003979 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003980 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003981 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003982 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003983 if (SuperClass) {
3984 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003985 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003986 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003987 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003988 Result += "\"";
3989 }
3990 else {
3991 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003992 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003993 Result += "\"";
3994 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003995 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003996 Result += ", 0,1";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003997 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003998 Result += ",0";
3999 else {
4000 // class has size. Must synthesize its size.
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00004001 Result += ",sizeof(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004002 Result += CDecl->getNameAsString();
Steve Naroff14a07462008-03-10 23:33:22 +00004003 if (LangOpts.Microsoft)
4004 Result += "_IMPL";
Fariborz Jahanian801b6352007-10-26 23:09:28 +00004005 Result += ")";
4006 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004007 if (NumIvars > 0) {
Steve Naroff17978c42008-03-11 17:37:02 +00004008 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004009 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004010 Result += "\n\t";
4011 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00004012 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004013 Result += ",0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004014 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroffc5b9cc72008-03-11 00:12:29 +00004015 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004016 Result += CDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00004017 Result += ", 0\n\t";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004018 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00004019 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004020 Result += ",0,0";
Chris Lattnerf5b77512009-02-20 18:18:36 +00004021 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00004022 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004023 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004024 Result += ", 0,0\n";
4025 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00004026 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004027 Result += ",0,0,0\n";
4028 Result += "};\n";
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00004029}
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00004030
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00004031/// RewriteImplementations - This routine rewrites all method implementations
4032/// and emits meta-data.
4033
Steve Narofff8cfd162008-11-13 20:07:04 +00004034void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004035 int ClsDefCount = ClassImplementation.size();
4036 int CatDefCount = CategoryImplementation.size();
Mike Stump11289f42009-09-09 15:08:12 +00004037
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00004038 // Rewrite implemented methods
4039 for (int i = 0; i < ClsDefCount; i++)
4040 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump11289f42009-09-09 15:08:12 +00004041
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00004042 for (int i = 0; i < CatDefCount; i++)
4043 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofff8cfd162008-11-13 20:07:04 +00004044}
Mike Stump11289f42009-09-09 15:08:12 +00004045
Steve Narofff8cfd162008-11-13 20:07:04 +00004046void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
4047 int ClsDefCount = ClassImplementation.size();
4048 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00004049
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00004050 // For each implemented class, write out all its meta data.
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00004051 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004052 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump11289f42009-09-09 15:08:12 +00004053
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00004054 // For each implemented category, write out all its meta data.
4055 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004056 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroffd9803712009-04-29 16:37:50 +00004057
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004058 // Write objc_symtab metadata
4059 /*
4060 struct _objc_symtab
4061 {
4062 long sel_ref_cnt;
4063 SEL *refs;
4064 short cls_def_cnt;
4065 short cat_def_cnt;
4066 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump11289f42009-09-09 15:08:12 +00004067 };
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004068 */
Mike Stump11289f42009-09-09 15:08:12 +00004069
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004070 Result += "\nstruct _objc_symtab {\n";
4071 Result += "\tlong sel_ref_cnt;\n";
4072 Result += "\tSEL *refs;\n";
4073 Result += "\tshort cls_def_cnt;\n";
4074 Result += "\tshort cat_def_cnt;\n";
4075 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
4076 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00004077
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004078 Result += "static struct _objc_symtab "
Steve Naroffb327e492008-03-12 17:18:30 +00004079 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00004080 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004081 + ", " + utostr(CatDefCount) + "\n";
4082 for (int i = 0; i < ClsDefCount; i++) {
4083 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004084 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004085 Result += "\n";
4086 }
Mike Stump11289f42009-09-09 15:08:12 +00004087
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004088 for (int i = 0; i < CatDefCount; i++) {
4089 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004090 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004091 Result += "_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004092 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004093 Result += "\n";
4094 }
Mike Stump11289f42009-09-09 15:08:12 +00004095
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004096 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00004097
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004098 // Write objc_module metadata
Mike Stump11289f42009-09-09 15:08:12 +00004099
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004100 /*
4101 struct _objc_module {
4102 long version;
4103 long size;
4104 const char *name;
4105 struct _objc_symtab *symtab;
4106 }
4107 */
Mike Stump11289f42009-09-09 15:08:12 +00004108
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004109 Result += "\nstruct _objc_module {\n";
4110 Result += "\tlong version;\n";
4111 Result += "\tlong size;\n";
4112 Result += "\tconst char *name;\n";
4113 Result += "\tstruct _objc_symtab *symtab;\n";
4114 Result += "};\n\n";
4115 Result += "static struct _objc_module "
Steve Naroffb327e492008-03-12 17:18:30 +00004116 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00004117 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00004118 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004119 Result += "};\n\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00004120
4121 if (LangOpts.Microsoft) {
Steve Naroffd9803712009-04-29 16:37:50 +00004122 if (ProtocolExprDecls.size()) {
4123 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
4124 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump11289f42009-09-09 15:08:12 +00004125 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00004126 E = ProtocolExprDecls.end(); I != E; ++I) {
4127 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
4128 Result += (*I)->getNameAsString();
4129 Result += " = &_OBJC_PROTOCOL_";
4130 Result += (*I)->getNameAsString();
4131 Result += ";\n";
4132 }
4133 Result += "#pragma data_seg(pop)\n\n";
4134 }
Steve Naroff945a3b12008-03-10 20:43:59 +00004135 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffcab93d52008-05-07 00:06:16 +00004136 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00004137 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
4138 Result += "&_OBJC_MODULES;\n";
4139 Result += "#pragma data_seg(pop)\n\n";
4140 }
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004141}
Chris Lattnera7c19fe2007-10-16 22:36:42 +00004142
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004143void RewriteObjC::RewriteByRefString(std::string &ResultStr,
4144 const std::string &Name,
4145 ValueDecl *VD) {
4146 assert(BlockByRefDeclNo.count(VD) &&
4147 "RewriteByRefString: ByRef decl missing");
4148 ResultStr += "struct __Block_byref_" + Name +
4149 "_" + utostr(BlockByRefDeclNo[VD]) ;
4150}
4151
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004152static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4153 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4154 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4155 return false;
4156}
4157
Steve Naroff677ab3a2008-10-27 17:20:55 +00004158std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Daniel Dunbar56df9772010-08-17 22:39:59 +00004159 llvm::StringRef funcName,
Steve Naroff677ab3a2008-10-27 17:20:55 +00004160 std::string Tag) {
4161 const FunctionType *AFT = CE->getFunctionType();
4162 QualType RT = AFT->getResultType();
4163 std::string StructRef = "struct " + Tag;
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00004164 std::string S = "static " + RT.getAsString(Context->PrintingPolicy) + " __" +
Daniel Dunbar56df9772010-08-17 22:39:59 +00004165 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00004166
Steve Naroff677ab3a2008-10-27 17:20:55 +00004167 BlockDecl *BD = CE->getBlockDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004168
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004169 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump11289f42009-09-09 15:08:12 +00004170 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Narofff26a1d42009-02-02 17:19:26 +00004171 // block (to reference imported block decl refs).
4172 S += "(" + StructRef + " *__cself)";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004173 } else if (BD->param_empty()) {
4174 S += "(" + StructRef + " *__cself)";
4175 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004176 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004177 assert(FT && "SynthesizeBlockFunc: No function proto");
4178 S += '(';
4179 // first add the implicit argument.
4180 S += StructRef + " *__cself, ";
4181 std::string ParamStr;
4182 for (BlockDecl::param_iterator AI = BD->param_begin(),
4183 E = BD->param_end(); AI != E; ++AI) {
4184 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004185 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004186 QualType QT = (*AI)->getType();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00004187 if (convertBlockPointerToFunctionPointer(QT))
4188 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004189 else
4190 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004191 S += ParamStr;
4192 }
4193 if (FT->isVariadic()) {
4194 if (!BD->param_empty()) S += ", ";
4195 S += "...";
4196 }
4197 S += ')';
4198 }
4199 S += " {\n";
Mike Stump11289f42009-09-09 15:08:12 +00004200
Steve Naroff677ab3a2008-10-27 17:20:55 +00004201 // Create local declarations to avoid rewriting all closure decl ref exprs.
4202 // First, emit a declaration for all "by ref" decls.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004203 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004204 E = BlockByRefDecls.end(); I != E; ++I) {
4205 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004206 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004207 std::string TypeString;
4208 RewriteByRefString(TypeString, Name, (*I));
4209 TypeString += " *";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004210 Name = TypeString + Name;
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004211 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump11289f42009-09-09 15:08:12 +00004212 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004213 // Next, emit a declaration for all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004214 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004215 E = BlockByCopyDecls.end(); I != E; ++I) {
4216 S += " ";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004217 // Handle nested closure invocation. For example:
4218 //
4219 // void (^myImportedClosure)(void);
4220 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004221 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004222 // void (^anotherClosure)(void);
4223 // anotherClosure = ^(void) {
4224 // myImportedClosure(); // import and invoke the closure
4225 // };
4226 //
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00004227 if (isTopLevelBlockPointerType((*I)->getType())) {
4228 RewriteBlockPointerTypeVariable(S, (*I));
4229 S += " = (";
4230 RewriteBlockPointerType(S, (*I)->getType());
4231 S += ")";
4232 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4233 }
4234 else {
Fariborz Jahanianb6a68c02010-02-16 17:26:03 +00004235 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004236 QualType QT = (*I)->getType();
4237 if (HasLocalVariableExternalStorage(*I))
4238 QT = Context->getPointerType(QT);
4239 QT.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00004240 S += Name + " = __cself->" +
4241 (*I)->getNameAsString() + "; // bound by copy\n";
4242 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004243 }
4244 std::string RewrittenStr = RewrittenBlockExprs[CE];
4245 const char *cstr = RewrittenStr.c_str();
4246 while (*cstr++ != '{') ;
4247 S += cstr;
4248 S += "\n";
4249 return S;
4250}
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00004251
Steve Naroff677ab3a2008-10-27 17:20:55 +00004252std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Daniel Dunbar56df9772010-08-17 22:39:59 +00004253 llvm::StringRef funcName,
Steve Naroff677ab3a2008-10-27 17:20:55 +00004254 std::string Tag) {
4255 std::string StructRef = "struct " + Tag;
4256 std::string S = "static void __";
Mike Stump11289f42009-09-09 15:08:12 +00004257
Steve Naroff677ab3a2008-10-27 17:20:55 +00004258 S += funcName;
4259 S += "_block_copy_" + utostr(i);
4260 S += "(" + StructRef;
4261 S += "*dst, " + StructRef;
4262 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00004263 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004264 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00004265 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004266 S += (*I)->getNameAsString();
Steve Naroff5ac4eac2008-12-11 20:51:38 +00004267 S += ", (void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004268 S += (*I)->getNameAsString();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004269 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004270 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00004271 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004272 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004273 }
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00004274 S += "}\n";
4275
Steve Naroff677ab3a2008-10-27 17:20:55 +00004276 S += "\nstatic void __";
4277 S += funcName;
4278 S += "_block_dispose_" + utostr(i);
4279 S += "(" + StructRef;
4280 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00004281 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004282 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00004283 S += "_Block_object_dispose((void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004284 S += (*I)->getNameAsString();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004285 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004286 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00004287 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004288 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004289 }
Mike Stump11289f42009-09-09 15:08:12 +00004290 S += "}\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004291 return S;
4292}
4293
Steve Naroff30484702009-12-06 21:14:13 +00004294std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4295 std::string Desc) {
Steve Naroff295570a2008-10-30 12:09:33 +00004296 std::string S = "\nstruct " + Tag;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004297 std::string Constructor = " " + Tag;
Mike Stump11289f42009-09-09 15:08:12 +00004298
Steve Naroff677ab3a2008-10-27 17:20:55 +00004299 S += " {\n struct __block_impl impl;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004300 S += " struct " + Desc;
4301 S += "* Desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00004302
Steve Naroff30484702009-12-06 21:14:13 +00004303 Constructor += "(void *fp, "; // Invoke function pointer.
4304 Constructor += "struct " + Desc; // Descriptor pointer.
4305 Constructor += " *desc";
Mike Stump11289f42009-09-09 15:08:12 +00004306
Steve Naroff677ab3a2008-10-27 17:20:55 +00004307 if (BlockDeclRefs.size()) {
4308 // Output all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004309 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004310 E = BlockByCopyDecls.end(); I != E; ++I) {
4311 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004312 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004313 std::string ArgName = "_" + FieldName;
4314 // Handle nested closure invocation. For example:
4315 //
4316 // void (^myImportedBlock)(void);
4317 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004318 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004319 // void (^anotherBlock)(void);
4320 // anotherBlock = ^(void) {
4321 // myImportedBlock(); // import and invoke the closure
4322 // };
4323 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00004324 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004325 S += "struct __block_impl *";
4326 Constructor += ", void *" + ArgName;
4327 } else {
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004328 QualType QT = (*I)->getType();
4329 if (HasLocalVariableExternalStorage(*I))
4330 QT = Context->getPointerType(QT);
4331 QT.getAsStringInternal(FieldName, Context->PrintingPolicy);
4332 QT.getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004333 Constructor += ", " + ArgName;
4334 }
4335 S += FieldName + ";\n";
4336 }
4337 // Output all "by ref" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004338 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004339 E = BlockByRefDecls.end(); I != E; ++I) {
4340 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004341 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004342 std::string ArgName = "_" + FieldName;
4343 // Handle nested closure invocation. For example:
4344 //
4345 // void (^myImportedBlock)(void);
4346 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004347 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004348 // void (^anotherBlock)(void);
4349 // anotherBlock = ^(void) {
4350 // myImportedBlock(); // import and invoke the closure
4351 // };
4352 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00004353 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004354 S += "struct __block_impl *";
4355 Constructor += ", void *" + ArgName;
4356 } else {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004357 std::string TypeString;
4358 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004359 TypeString += " *";
4360 FieldName = TypeString + FieldName;
4361 ArgName = TypeString + ArgName;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004362 Constructor += ", " + ArgName;
4363 }
4364 S += FieldName + "; // by ref\n";
4365 }
4366 // Finish writing the constructor.
Fariborz Jahaniane6a4e392010-07-28 23:27:30 +00004367 Constructor += ", int flags=0)";
4368 // Initialize all "by copy" arguments.
4369 bool firsTime = true;
4370 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4371 E = BlockByCopyDecls.end(); I != E; ++I) {
4372 std::string Name = (*I)->getNameAsString();
4373 if (firsTime) {
4374 Constructor += " : ";
4375 firsTime = false;
4376 }
4377 else
4378 Constructor += ", ";
4379 if (isTopLevelBlockPointerType((*I)->getType()))
4380 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4381 else
4382 Constructor += Name + "(_" + Name + ")";
4383 }
4384 // Initialize all "by ref" arguments.
4385 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4386 E = BlockByRefDecls.end(); I != E; ++I) {
4387 std::string Name = (*I)->getNameAsString();
4388 if (firsTime) {
4389 Constructor += " : ";
4390 firsTime = false;
4391 }
4392 else
4393 Constructor += ", ";
4394 if (isTopLevelBlockPointerType((*I)->getType()))
4395 Constructor += Name + "((struct __block_impl *)_"
4396 + Name + "->__forwarding)";
4397 else
4398 Constructor += Name + "(_" + Name + "->__forwarding)";
4399 }
4400
4401 Constructor += " {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00004402 if (GlobalVarDecl)
4403 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4404 else
4405 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004406 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00004407
Steve Naroff30484702009-12-06 21:14:13 +00004408 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004409 } else {
4410 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004411 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00004412 if (GlobalVarDecl)
4413 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4414 else
4415 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004416 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4417 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004418 }
4419 Constructor += " ";
4420 Constructor += "}\n";
4421 S += Constructor;
4422 S += "};\n";
4423 return S;
4424}
4425
Steve Naroff30484702009-12-06 21:14:13 +00004426std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4427 std::string ImplTag, int i,
Daniel Dunbar56df9772010-08-17 22:39:59 +00004428 llvm::StringRef FunName,
Steve Naroff30484702009-12-06 21:14:13 +00004429 unsigned hasCopy) {
4430 std::string S = "\nstatic struct " + DescTag;
4431
4432 S += " {\n unsigned long reserved;\n";
4433 S += " unsigned long Block_size;\n";
4434 if (hasCopy) {
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004435 S += " void (*copy)(struct ";
4436 S += ImplTag; S += "*, struct ";
4437 S += ImplTag; S += "*);\n";
4438
4439 S += " void (*dispose)(struct ";
4440 S += ImplTag; S += "*);\n";
Steve Naroff30484702009-12-06 21:14:13 +00004441 }
4442 S += "} ";
4443
4444 S += DescTag + "_DATA = { 0, sizeof(struct ";
4445 S += ImplTag + ")";
4446 if (hasCopy) {
Daniel Dunbar56df9772010-08-17 22:39:59 +00004447 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4448 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff30484702009-12-06 21:14:13 +00004449 }
4450 S += "};\n";
4451 return S;
4452}
4453
Steve Naroff677ab3a2008-10-27 17:20:55 +00004454void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Daniel Dunbar56df9772010-08-17 22:39:59 +00004455 llvm::StringRef FunName) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004456 // Insert declaration for the function in which block literal is used.
Fariborz Jahanian5c26eee2010-01-15 18:14:52 +00004457 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004458 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00004459 bool RewriteSC = (GlobalVarDecl &&
4460 !Blocks.empty() &&
John McCall8e7d6562010-08-26 03:08:43 +00004461 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00004462 GlobalVarDecl->getType().getCVRQualifiers());
4463 if (RewriteSC) {
4464 std::string SC(" void __");
4465 SC += GlobalVarDecl->getNameAsString();
4466 SC += "() {}";
4467 InsertText(FunLocStart, SC);
4468 }
4469
Steve Naroff677ab3a2008-10-27 17:20:55 +00004470 // Insert closures that were part of the function.
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004471 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4472 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004473 // Need to copy-in the inner copied-in variables not actually used in this
4474 // block.
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004475 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4476 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
4477 ValueDecl *VD = Exp->getDecl();
4478 BlockDeclRefs.push_back(Exp);
4479 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4480 BlockByCopyDeclsPtrSet.insert(VD);
4481 BlockByCopyDecls.push_back(VD);
4482 }
4483 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4484 BlockByRefDeclsPtrSet.insert(VD);
4485 BlockByRefDecls.push_back(VD);
4486 }
Fariborz Jahanianfc8315f2010-10-05 18:05:06 +00004487 // imported objects in the inner blocks not used in the outer
4488 // blocks must be copied/disposed in the outer block as well.
4489 if (Exp->isByRef() ||
4490 VD->getType()->isObjCObjectPointerType() ||
4491 VD->getType()->isBlockPointerType())
4492 ImportedBlockDecls.insert(VD);
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004493 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004494
Daniel Dunbar56df9772010-08-17 22:39:59 +00004495 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4496 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump11289f42009-09-09 15:08:12 +00004497
Steve Naroff30484702009-12-06 21:14:13 +00004498 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004499
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004500 InsertText(FunLocStart, CI);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004501
Steve Naroff30484702009-12-06 21:14:13 +00004502 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump11289f42009-09-09 15:08:12 +00004503
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004504 InsertText(FunLocStart, CF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004505
4506 if (ImportedBlockDecls.size()) {
Steve Naroff30484702009-12-06 21:14:13 +00004507 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004508 InsertText(FunLocStart, HF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004509 }
Steve Naroff30484702009-12-06 21:14:13 +00004510 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4511 ImportedBlockDecls.size() > 0);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004512 InsertText(FunLocStart, BD);
Mike Stump11289f42009-09-09 15:08:12 +00004513
Steve Naroff677ab3a2008-10-27 17:20:55 +00004514 BlockDeclRefs.clear();
4515 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004516 BlockByRefDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004517 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004518 BlockByCopyDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004519 ImportedBlockDecls.clear();
4520 }
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00004521 if (RewriteSC) {
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004522 // Must insert any 'const/volatile/static here. Since it has been
4523 // removed as result of rewriting of block literals.
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004524 std::string SC;
John McCall8e7d6562010-08-26 03:08:43 +00004525 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004526 SC = "static ";
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004527 if (GlobalVarDecl->getType().isConstQualified())
4528 SC += "const ";
4529 if (GlobalVarDecl->getType().isVolatileQualified())
4530 SC += "volatile ";
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00004531 if (GlobalVarDecl->getType().isRestrictQualified())
4532 SC += "restrict ";
4533 InsertText(FunLocStart, SC);
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004534 }
4535
Steve Naroff677ab3a2008-10-27 17:20:55 +00004536 Blocks.clear();
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004537 InnerDeclRefsCount.clear();
4538 InnerDeclRefs.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004539 RewrittenBlockExprs.clear();
4540}
4541
4542void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4543 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Daniel Dunbar56df9772010-08-17 22:39:59 +00004544 llvm::StringRef FuncName = FD->getName();
Mike Stump11289f42009-09-09 15:08:12 +00004545
Steve Naroff677ab3a2008-10-27 17:20:55 +00004546 SynthesizeBlockLiterals(FunLocStart, FuncName);
4547}
4548
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004549static void BuildUniqueMethodName(std::string &Name,
4550 ObjCMethodDecl *MD) {
4551 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar56df9772010-08-17 22:39:59 +00004552 Name = IFace->getName();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004553 Name += "__" + MD->getSelector().getAsString();
4554 // Convert colons to underscores.
4555 std::string::size_type loc = 0;
4556 while ((loc = Name.find(":", loc)) != std::string::npos)
4557 Name.replace(loc, 1, "_");
4558}
4559
Steve Naroff677ab3a2008-10-27 17:20:55 +00004560void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff295570a2008-10-30 12:09:33 +00004561 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4562 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianb5f99c32010-01-29 01:55:49 +00004563 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004564 std::string FuncName;
4565 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar56df9772010-08-17 22:39:59 +00004566 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004567}
4568
4569void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4570 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4571 CI != E; ++CI)
4572 if (*CI) {
4573 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4574 GetBlockDeclRefExprs(CBE->getBody());
4575 else
4576 GetBlockDeclRefExprs(*CI);
4577 }
4578 // Handle specific things.
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004579 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004580 // FIXME: Handle enums.
4581 if (!isa<FunctionDecl>(CDRE->getDecl()))
4582 BlockDeclRefs.push_back(CDRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004583 }
4584 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4585 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
4586 BlockDeclRefExpr *BDRE =
4587 new (Context)BlockDeclRefExpr(DRE->getDecl(), DRE->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00004588 VK_LValue, DRE->getLocation(), false);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004589 BlockDeclRefs.push_back(BDRE);
4590 }
4591
Steve Naroff677ab3a2008-10-27 17:20:55 +00004592 return;
4593}
4594
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004595void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4596 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004597 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004598 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4599 CI != E; ++CI)
4600 if (*CI) {
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004601 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4602 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004603 GetInnerBlockDeclRefExprs(CBE->getBody(),
4604 InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004605 InnerContexts);
4606 }
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004607 else
4608 GetInnerBlockDeclRefExprs(*CI,
4609 InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004610 InnerContexts);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004611
4612 }
4613 // Handle specific things.
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004614 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004615 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004616 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004617 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004618 }
4619 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4620 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4621 if (Var->isFunctionOrMethodVarDecl())
4622 ImportedLocalExternalDecls.insert(Var);
4623 }
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004624
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004625 return;
4626}
4627
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004628/// convertFunctionTypeOfBlocks - This routine converts a function type
4629/// whose result type may be a block pointer or whose argument type(s)
4630/// might be block pointers to an equivalent funtion type replacing
4631/// all block pointers to function pointers.
4632QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4633 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4634 // FTP will be null for closures that don't take arguments.
4635 // Generate a funky cast.
4636 llvm::SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004637 QualType Res = FT->getResultType();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00004638 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004639
4640 if (FTP) {
4641 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4642 E = FTP->arg_type_end(); I && (I != E); ++I) {
4643 QualType t = *I;
4644 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00004645 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004646 HasBlockType = true;
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004647 ArgTypes.push_back(t);
4648 }
4649 }
4650 QualType FuncType;
4651 // FIXME. Does this work if block takes no argument but has a return type
4652 // which is of block type?
4653 if (HasBlockType)
4654 FuncType = Context->getFunctionType(Res,
4655 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0,
4656 false, false, 0, 0, FunctionType::ExtInfo());
4657 else FuncType = QualType(FT, 0);
4658 return FuncType;
4659}
4660
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004661Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004662 // Navigate to relevant type information.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004663 const BlockPointerType *CPT = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004664
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004665 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004666 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004667 } else if (const BlockDeclRefExpr *CDRE =
4668 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004669 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004670 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004671 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004672 }
4673 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4674 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4675 }
4676 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4677 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4678 else if (const ConditionalOperator *CEXPR =
4679 dyn_cast<ConditionalOperator>(BlockExp)) {
4680 Expr *LHSExp = CEXPR->getLHS();
4681 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4682 Expr *RHSExp = CEXPR->getRHS();
4683 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4684 Expr *CONDExp = CEXPR->getCond();
4685 ConditionalOperator *CondExpr =
4686 new (Context) ConditionalOperator(CONDExp,
4687 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00004688 SourceLocation(), cast<Expr>(RHSStmt),
4689 (Expr*)0,
John McCall4bc41ae2010-11-18 19:01:18 +00004690 Exp->getType(), VK_RValue, OK_Ordinary);
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004691 return CondExpr;
Fariborz Jahanian6ab7ed42009-12-18 01:15:21 +00004692 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4693 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004694 } else {
4695 assert(1 && "RewriteBlockClass: Bad type");
4696 }
4697 assert(CPT && "RewriteBlockClass: Bad type");
John McCall9dd450b2009-09-21 23:43:11 +00004698 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004699 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004700 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004701 // FTP will be null for closures that don't take arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004702
Abramo Bagnara6150c882010-05-11 21:36:43 +00004703 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Steve Naroff350b6652008-10-30 10:07:53 +00004704 SourceLocation(),
4705 &Context->Idents.get("__block_impl"));
4706 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff677ab3a2008-10-27 17:20:55 +00004707
Steve Naroff350b6652008-10-30 10:07:53 +00004708 // Generate a funky cast.
4709 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00004710
Steve Naroff350b6652008-10-30 10:07:53 +00004711 // Push the block argument type.
4712 ArgTypes.push_back(PtrBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004713 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004714 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff350b6652008-10-30 10:07:53 +00004715 E = FTP->arg_type_end(); I && (I != E); ++I) {
4716 QualType t = *I;
4717 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian90d2e572010-11-05 18:34:46 +00004718 if (!convertBlockPointerToFunctionPointer(t))
4719 convertToUnqualifiedObjCType(t);
Steve Naroff350b6652008-10-30 10:07:53 +00004720 ArgTypes.push_back(t);
4721 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004722 }
Steve Naroff350b6652008-10-30 10:07:53 +00004723 // Now do the pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00004724 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00004725 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0,
4726 false, false, 0, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004727 FunctionType::ExtInfo());
Mike Stump11289f42009-09-09 15:08:12 +00004728
Steve Naroff350b6652008-10-30 10:07:53 +00004729 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump11289f42009-09-09 15:08:12 +00004730
John McCall97513962010-01-15 18:39:57 +00004731 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCallf608deb2010-11-15 09:46:46 +00004732 CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00004733 const_cast<Expr*>(BlockExp));
Steve Naroff350b6652008-10-30 10:07:53 +00004734 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00004735 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4736 BlkCast);
Steve Naroff350b6652008-10-30 10:07:53 +00004737 //PE->dump();
Mike Stump11289f42009-09-09 15:08:12 +00004738
Douglas Gregor91f84212008-12-11 16:49:14 +00004739 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004740 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004741 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek5a201952009-02-07 01:47:29 +00004742 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
John McCall7decc9e2010-11-18 06:31:45 +00004743 FD->getType(), VK_LValue,
4744 OK_Ordinary);
Mike Stump11289f42009-09-09 15:08:12 +00004745
Fariborz Jahanian90d2e572010-11-05 18:34:46 +00004746
John McCall97513962010-01-15 18:39:57 +00004747 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCallf608deb2010-11-15 09:46:46 +00004748 CK_BitCast, ME);
Ted Kremenek5a201952009-02-07 01:47:29 +00004749 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump11289f42009-09-09 15:08:12 +00004750
Steve Naroff350b6652008-10-30 10:07:53 +00004751 llvm::SmallVector<Expr*, 8> BlkExprs;
4752 // Add the implicit argument.
4753 BlkExprs.push_back(BlkCast);
4754 // Add the user arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004755 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004756 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00004757 BlkExprs.push_back(*I);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004758 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004759 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4760 BlkExprs.size(),
John McCall7decc9e2010-11-18 06:31:45 +00004761 Exp->getType(), VK_RValue,
4762 SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004763 return CE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004764}
4765
Steve Naroffd9803712009-04-29 16:37:50 +00004766// We need to return the rewritten expression to handle cases where the
4767// BlockDeclRefExpr is embedded in another expression being rewritten.
4768// For example:
4769//
4770// int main() {
4771// __block Foo *f;
4772// __block int i;
Mike Stump11289f42009-09-09 15:08:12 +00004773//
Steve Naroffd9803712009-04-29 16:37:50 +00004774// void (^myblock)() = ^() {
4775// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4776// i = 77;
4777// };
4778//}
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004779Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanian25c07fa2009-12-23 19:26:34 +00004780 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004781 // for each DeclRefExp where BYREFVAR is name of the variable.
4782 ValueDecl *VD;
4783 bool isArrow = true;
4784 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4785 VD = BDRE->getDecl();
4786 else {
4787 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4788 isArrow = false;
4789 }
4790
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004791 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4792 &Context->Idents.get("__forwarding"),
4793 Context->VoidPtrTy, 0,
4794 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004795 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4796 FD, SourceLocation(),
John McCall7decc9e2010-11-18 06:31:45 +00004797 FD->getType(), VK_LValue,
4798 OK_Ordinary);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004799
Daniel Dunbar56df9772010-08-17 22:39:59 +00004800 llvm::StringRef Name = VD->getName();
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004801 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4802 &Context->Idents.get(Name),
4803 Context->VoidPtrTy, 0,
4804 /*BitWidth=*/0, /*Mutable=*/true);
4805 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
John McCall7decc9e2010-11-18 06:31:45 +00004806 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004807
4808
4809
Steve Narofff26a1d42009-02-02 17:19:26 +00004810 // Need parens to enforce precedence.
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004811 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4812 ME);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004813 ReplaceStmt(DeclRefExp, PE);
Steve Naroffd9803712009-04-29 16:37:50 +00004814 return PE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004815}
4816
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004817// Rewrites the imported local variable V with external storage
4818// (static, extern, etc.) as *V
4819//
4820Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4821 ValueDecl *VD = DRE->getDecl();
4822 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4823 if (!ImportedLocalExternalDecls.count(Var))
4824 return DRE;
John McCall7decc9e2010-11-18 06:31:45 +00004825 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4826 VK_LValue, OK_Ordinary,
4827 DRE->getLocation());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004828 // Need parens to enforce precedence.
4829 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4830 Exp);
4831 ReplaceStmt(DRE, PE);
4832 return PE;
4833}
4834
Steve Naroffc989a7b2008-11-03 23:29:32 +00004835void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4836 SourceLocation LocStart = CE->getLParenLoc();
4837 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofff4b992a2008-10-28 20:29:00 +00004838
4839 // Need to avoid trying to rewrite synthesized casts.
4840 if (LocStart.isInvalid())
4841 return;
Steve Naroff3e7ced12008-11-03 11:20:24 +00004842 // Need to avoid trying to rewrite casts contained in macros.
4843 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4844 return;
Mike Stump11289f42009-09-09 15:08:12 +00004845
Steve Naroff677ab3a2008-10-27 17:20:55 +00004846 const char *startBuf = SM->getCharacterData(LocStart);
4847 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004848 QualType QT = CE->getType();
4849 const Type* TypePtr = QT->getAs<Type>();
4850 if (isa<TypeOfExprType>(TypePtr)) {
4851 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4852 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4853 std::string TypeAsString = "(";
Fariborz Jahanianf5067912010-02-18 01:20:22 +00004854 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004855 TypeAsString += ")";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004856 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004857 return;
4858 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004859 // advance the location to startArgList.
4860 const char *argPtr = startBuf;
Mike Stump11289f42009-09-09 15:08:12 +00004861
Steve Naroff677ab3a2008-10-27 17:20:55 +00004862 while (*argPtr++ && (argPtr < endBuf)) {
4863 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004864 case '^':
4865 // Replace the '^' with '*'.
4866 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004867 ReplaceText(LocStart, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00004868 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004869 }
4870 }
4871 return;
4872}
4873
4874void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4875 SourceLocation DeclLoc = FD->getLocation();
4876 unsigned parenCount = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004877
Steve Naroff677ab3a2008-10-27 17:20:55 +00004878 // We have 1 or more arguments that have closure pointers.
4879 const char *startBuf = SM->getCharacterData(DeclLoc);
4880 const char *startArgList = strchr(startBuf, '(');
Mike Stump11289f42009-09-09 15:08:12 +00004881
Steve Naroff677ab3a2008-10-27 17:20:55 +00004882 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004883
Steve Naroff677ab3a2008-10-27 17:20:55 +00004884 parenCount++;
4885 // advance the location to startArgList.
4886 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4887 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump11289f42009-09-09 15:08:12 +00004888
Steve Naroff677ab3a2008-10-27 17:20:55 +00004889 const char *argPtr = startArgList;
Mike Stump11289f42009-09-09 15:08:12 +00004890
Steve Naroff677ab3a2008-10-27 17:20:55 +00004891 while (*argPtr++ && parenCount) {
4892 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004893 case '^':
4894 // Replace the '^' with '*'.
4895 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004896 ReplaceText(DeclLoc, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00004897 break;
4898 case '(':
4899 parenCount++;
4900 break;
4901 case ')':
4902 parenCount--;
4903 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004904 }
4905 }
4906 return;
4907}
4908
4909bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004910 const FunctionProtoType *FTP;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004911 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004912 if (PT) {
John McCall9dd450b2009-09-21 23:43:11 +00004913 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004914 } else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004915 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004916 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall9dd450b2009-09-21 23:43:11 +00004917 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004918 }
4919 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004920 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004921 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +00004922 if (isTopLevelBlockPointerType(*I))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004923 return true;
4924 }
4925 return false;
4926}
4927
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004928bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4929 const FunctionProtoType *FTP;
4930 const PointerType *PT = QT->getAs<PointerType>();
4931 if (PT) {
4932 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4933 } else {
4934 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4935 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4936 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4937 }
4938 if (FTP) {
4939 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Fariborz Jahanian733dde62010-11-03 23:50:34 +00004940 E = FTP->arg_type_end(); I != E; ++I) {
4941 if ((*I)->isObjCQualifiedIdType())
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004942 return true;
Fariborz Jahanian733dde62010-11-03 23:50:34 +00004943 if ((*I)->isObjCObjectPointerType() &&
4944 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4945 return true;
4946 }
4947
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004948 }
4949 return false;
4950}
4951
Ted Kremenek5a201952009-02-07 01:47:29 +00004952void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4953 const char *&RParen) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004954 const char *argPtr = strchr(Name, '(');
4955 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004956
Steve Naroff677ab3a2008-10-27 17:20:55 +00004957 LParen = argPtr; // output the start.
4958 argPtr++; // skip past the left paren.
4959 unsigned parenCount = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004960
Steve Naroff677ab3a2008-10-27 17:20:55 +00004961 while (*argPtr && parenCount) {
4962 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004963 case '(': parenCount++; break;
4964 case ')': parenCount--; break;
4965 default: break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004966 }
4967 if (parenCount) argPtr++;
4968 }
4969 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4970 RParen = argPtr; // output the end
4971}
4972
4973void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4974 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4975 RewriteBlockPointerFunctionArgs(FD);
4976 return;
Mike Stump11289f42009-09-09 15:08:12 +00004977 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004978 // Handle Variables and Typedefs.
4979 SourceLocation DeclLoc = ND->getLocation();
4980 QualType DeclT;
4981 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4982 DeclT = VD->getType();
4983 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4984 DeclT = TDD->getUnderlyingType();
4985 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4986 DeclT = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004987 else
Steve Naroff677ab3a2008-10-27 17:20:55 +00004988 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump11289f42009-09-09 15:08:12 +00004989
Steve Naroff677ab3a2008-10-27 17:20:55 +00004990 const char *startBuf = SM->getCharacterData(DeclLoc);
4991 const char *endBuf = startBuf;
4992 // scan backward (from the decl location) for the end of the previous decl.
4993 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4994 startBuf--;
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004995 SourceLocation Start = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4996 std::string buf;
4997 unsigned OrigLength=0;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004998 // *startBuf != '^' if we are dealing with a pointer to function that
4999 // may take block argument types (which will be handled below).
5000 if (*startBuf == '^') {
5001 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00005002 buf = '*';
5003 startBuf++;
5004 OrigLength++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00005005 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00005006 while (*startBuf != ')') {
5007 buf += *startBuf;
5008 startBuf++;
5009 OrigLength++;
5010 }
5011 buf += ')';
5012 OrigLength++;
5013
5014 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
5015 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00005016 // Replace the '^' with '*' for arguments.
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00005017 // Replace id<P> with id/*<>*/
Steve Naroff677ab3a2008-10-27 17:20:55 +00005018 DeclLoc = ND->getLocation();
5019 startBuf = SM->getCharacterData(DeclLoc);
5020 const char *argListBegin, *argListEnd;
5021 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
5022 while (argListBegin < argListEnd) {
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00005023 if (*argListBegin == '^')
5024 buf += '*';
5025 else if (*argListBegin == '<') {
5026 buf += "/*";
5027 buf += *argListBegin++;
5028 OrigLength++;;
5029 while (*argListBegin != '>') {
5030 buf += *argListBegin++;
5031 OrigLength++;
5032 }
5033 buf += *argListBegin;
5034 buf += "*/";
Steve Naroff677ab3a2008-10-27 17:20:55 +00005035 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00005036 else
5037 buf += *argListBegin;
Steve Naroff677ab3a2008-10-27 17:20:55 +00005038 argListBegin++;
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00005039 OrigLength++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00005040 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00005041 buf += ')';
5042 OrigLength++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00005043 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00005044 ReplaceText(Start, OrigLength, buf);
5045
Steve Naroff677ab3a2008-10-27 17:20:55 +00005046 return;
5047}
5048
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005049
5050/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5051/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5052/// struct Block_byref_id_object *src) {
5053/// _Block_object_assign (&_dest->object, _src->object,
5054/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5055/// [|BLOCK_FIELD_IS_WEAK]) // object
5056/// _Block_object_assign(&_dest->object, _src->object,
5057/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5058/// [|BLOCK_FIELD_IS_WEAK]) // block
5059/// }
5060/// And:
5061/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5062/// _Block_object_dispose(_src->object,
5063/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5064/// [|BLOCK_FIELD_IS_WEAK]) // object
5065/// _Block_object_dispose(_src->object,
5066/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5067/// [|BLOCK_FIELD_IS_WEAK]) // block
5068/// }
5069
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005070std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5071 int flag) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005072 std::string S;
Benjamin Kramere056cea2010-01-10 19:57:50 +00005073 if (CopyDestroyCache.count(flag))
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005074 return S;
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005075 CopyDestroyCache.insert(flag);
5076 S = "static void __Block_byref_id_object_copy_";
5077 S += utostr(flag);
5078 S += "(void *dst, void *src) {\n";
5079
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005080 // offset into the object pointer is computed as:
5081 // void * + void* + int + int + void* + void *
5082 unsigned IntSize =
5083 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5084 unsigned VoidPtrSize =
5085 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5086
5087 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
5088 S += " _Block_object_assign((char*)dst + ";
5089 S += utostr(offset);
5090 S += ", *(void * *) ((char*)src + ";
5091 S += utostr(offset);
5092 S += "), ";
5093 S += utostr(flag);
5094 S += ");\n}\n";
5095
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005096 S += "static void __Block_byref_id_object_dispose_";
5097 S += utostr(flag);
5098 S += "(void *src) {\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005099 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5100 S += utostr(offset);
5101 S += "), ";
5102 S += utostr(flag);
5103 S += ");\n}\n";
5104 return S;
5105}
5106
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005107/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5108/// the declaration into:
5109/// struct __Block_byref_ND {
5110/// void *__isa; // NULL for everything except __weak pointers
5111/// struct __Block_byref_ND *__forwarding;
5112/// int32_t __flags;
5113/// int32_t __size;
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005114/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5115/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005116/// typex ND;
5117/// };
5118///
5119/// It then replaces declaration of ND variable with:
5120/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5121/// __size=sizeof(struct __Block_byref_ND),
5122/// ND=initializer-if-any};
5123///
5124///
5125void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005126 // Insert declaration for the function in which block literal is
5127 // used.
5128 if (CurFunctionDeclToDeclareForBlock)
5129 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00005130 int flag = 0;
5131 int isa = 0;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005132 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahanian6005bd82010-02-26 22:49:11 +00005133 if (DeclLoc.isInvalid())
5134 // If type location is missing, it is because of missing type (a warning).
5135 // Use variable's location which is good for this case.
5136 DeclLoc = ND->getLocation();
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005137 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian92368a12009-12-30 20:38:08 +00005138 SourceLocation X = ND->getLocEnd();
5139 X = SM->getInstantiationLoc(X);
5140 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005141 std::string Name(ND->getNameAsString());
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005142 std::string ByrefType;
5143 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005144 ByrefType += " {\n";
5145 ByrefType += " void *__isa;\n";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005146 RewriteByRefString(ByrefType, Name, ND);
5147 ByrefType += " *__forwarding;\n";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005148 ByrefType += " int __flags;\n";
5149 ByrefType += " int __size;\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005150 // Add void *__Block_byref_id_object_copy;
5151 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005152 QualType Ty = ND->getType();
5153 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
5154 if (HasCopyAndDispose) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005155 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5156 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005157 }
5158
5159 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005160 ByrefType += " " + Name + ";\n";
5161 ByrefType += "};\n";
5162 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00005163 SourceLocation FunLocStart;
5164 if (CurFunctionDef)
5165 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
5166 else {
5167 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5168 FunLocStart = CurMethodDef->getLocStart();
5169 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005170 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00005171 if (Ty.isObjCGCWeak()) {
5172 flag |= BLOCK_FIELD_IS_WEAK;
5173 isa = 1;
5174 }
5175
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005176 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005177 flag = BLOCK_BYREF_CALLER;
5178 QualType Ty = ND->getType();
5179 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5180 if (Ty->isBlockPointerType())
5181 flag |= BLOCK_FIELD_IS_BLOCK;
5182 else
5183 flag |= BLOCK_FIELD_IS_OBJECT;
5184 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005185 if (!HF.empty())
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005186 InsertText(FunLocStart, HF);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005187 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005188
5189 // struct __Block_byref_ND ND =
5190 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5191 // initializer-if-any};
5192 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanianf7945432010-01-05 18:15:57 +00005193 unsigned flags = 0;
5194 if (HasCopyAndDispose)
5195 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005196 Name = ND->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005197 ByrefType.clear();
5198 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005199 std::string ForwardingCastType("(");
5200 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005201 if (!hasInit) {
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00005202 ByrefType += " " + Name + " = {(void*)";
5203 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005204 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005205 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005206 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005207 ByrefType += "sizeof(";
5208 RewriteByRefString(ByrefType, Name, ND);
5209 ByrefType += ")";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005210 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005211 ByrefType += ", __Block_byref_id_object_copy_";
5212 ByrefType += utostr(flag);
5213 ByrefType += ", __Block_byref_id_object_dispose_";
5214 ByrefType += utostr(flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005215 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005216 ByrefType += "};\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005217 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(), ByrefType);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005218 }
5219 else {
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00005220 SourceLocation startLoc;
5221 Expr *E = ND->getInit();
5222 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5223 startLoc = ECE->getLParenLoc();
5224 else
5225 startLoc = E->getLocStart();
Fariborz Jahanianb8646ed2010-01-05 23:06:29 +00005226 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00005227 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005228 ByrefType += " " + Name;
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00005229 ByrefType += " = {(void*)";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00005230 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005231 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005232 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005233 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005234 ByrefType += "sizeof(";
5235 RewriteByRefString(ByrefType, Name, ND);
5236 ByrefType += "), ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005237 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005238 ByrefType += "__Block_byref_id_object_copy_";
5239 ByrefType += utostr(flag);
5240 ByrefType += ", __Block_byref_id_object_dispose_";
5241 ByrefType += utostr(flag);
5242 ByrefType += ", ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005243 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005244 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroff13468372009-12-23 17:24:33 +00005245
5246 // Complete the newly synthesized compound expression by inserting a right
5247 // curly brace before the end of the declaration.
5248 // FIXME: This approach avoids rewriting the initializer expression. It
5249 // also assumes there is only one declarator. For example, the following
5250 // isn't currently supported by this routine (in general):
5251 //
5252 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
5253 //
Fariborz Jahanian34c85982010-07-21 17:36:39 +00005254 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5255 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroff13468372009-12-23 17:24:33 +00005256 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
5257 SourceLocation semiLoc =
Fariborz Jahanian34c85982010-07-21 17:36:39 +00005258 startLoc.getFileLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroff13468372009-12-23 17:24:33 +00005259
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005260 InsertText(semiLoc, "}");
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005261 }
Fariborz Jahanian81203462009-12-22 00:48:54 +00005262 return;
5263}
5264
Mike Stump11289f42009-09-09 15:08:12 +00005265void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00005266 // Add initializers for any closure decl refs.
5267 GetBlockDeclRefExprs(Exp->getBody());
5268 if (BlockDeclRefs.size()) {
5269 // Unique all "by copy" declarations.
5270 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005271 if (!BlockDeclRefs[i]->isByRef()) {
5272 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5273 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5274 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5275 }
5276 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00005277 // Unique all "by ref" declarations.
5278 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5279 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005280 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5281 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5282 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5283 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00005284 }
5285 // Find any imported blocks...they will need special attention.
5286 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00005287 if (BlockDeclRefs[i]->isByRef() ||
5288 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian9bbc1482010-02-26 21:46:27 +00005289 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff677ab3a2008-10-27 17:20:55 +00005290 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff677ab3a2008-10-27 17:20:55 +00005291 }
5292}
5293
Daniel Dunbar56df9772010-08-17 22:39:59 +00005294FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(llvm::StringRef name) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005295 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005296 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump11289f42009-09-09 15:08:12 +00005297 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
John McCall8e7d6562010-08-26 03:08:43 +00005298 ID, FType, 0, SC_Extern,
5299 SC_None, false, false);
Steve Narofff4b992a2008-10-28 20:29:00 +00005300}
5301
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005302Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
5303 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005304 Blocks.push_back(Exp);
5305
5306 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005307
5308 // Add inner imported variables now used in current block.
5309 int countOfInnerDecls = 0;
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00005310 if (!InnerBlockDeclRefs.empty()) {
5311 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5312 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
5313 ValueDecl *VD = Exp->getDecl();
5314 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005315 // We need to save the copied-in variables in nested
5316 // blocks because it is needed at the end for some of the API generations.
5317 // See SynthesizeBlockLiterals routine.
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00005318 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5319 BlockDeclRefs.push_back(Exp);
5320 BlockByCopyDeclsPtrSet.insert(VD);
5321 BlockByCopyDecls.push_back(VD);
5322 }
5323 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
5324 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5325 BlockDeclRefs.push_back(Exp);
5326 BlockByRefDeclsPtrSet.insert(VD);
5327 BlockByRefDecls.push_back(VD);
5328 }
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005329 }
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00005330 // Find any imported blocks...they will need special attention.
5331 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5332 if (InnerBlockDeclRefs[i]->isByRef() ||
5333 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5334 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5335 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005336 }
5337 InnerDeclRefsCount.push_back(countOfInnerDecls);
5338
Steve Narofff4b992a2008-10-28 20:29:00 +00005339 std::string FuncName;
Mike Stump11289f42009-09-09 15:08:12 +00005340
Steve Narofff4b992a2008-10-28 20:29:00 +00005341 if (CurFunctionDef)
Chris Lattnere4b95692008-11-24 03:33:13 +00005342 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00005343 else if (CurMethodDef)
5344 BuildUniqueMethodName(FuncName, CurMethodDef);
5345 else if (GlobalVarDecl)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005346 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +00005347
Steve Narofff4b992a2008-10-28 20:29:00 +00005348 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump11289f42009-09-09 15:08:12 +00005349
Steve Narofff4b992a2008-10-28 20:29:00 +00005350 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
5351 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump11289f42009-09-09 15:08:12 +00005352
Steve Narofff4b992a2008-10-28 20:29:00 +00005353 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian19c62402010-05-25 15:56:08 +00005354 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5355 QualType FType = Context->getPointerType(BFT);
Steve Narofff4b992a2008-10-28 20:29:00 +00005356
5357 FunctionDecl *FD;
5358 Expr *NewRep;
Mike Stump11289f42009-09-09 15:08:12 +00005359
Steve Narofff4b992a2008-10-28 20:29:00 +00005360 // Simulate a contructor call...
Daniel Dunbar56df9772010-08-17 22:39:59 +00005361 FD = SynthBlockInitFunctionDecl(Tag);
John McCall7decc9e2010-11-18 06:31:45 +00005362 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, VK_RValue,
5363 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00005364
Steve Narofff4b992a2008-10-28 20:29:00 +00005365 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00005366
Steve Naroffe2514232008-10-29 21:23:59 +00005367 // Initialize the block function.
Daniel Dunbar56df9772010-08-17 22:39:59 +00005368 FD = SynthBlockInitFunctionDecl(Func);
John McCall7decc9e2010-11-18 06:31:45 +00005369 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
Ted Kremenek5a201952009-02-07 01:47:29 +00005370 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00005371 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCallf608deb2010-11-15 09:46:46 +00005372 CK_BitCast, Arg);
Mike Stump11289f42009-09-09 15:08:12 +00005373 InitExprs.push_back(castExpr);
5374
Steve Naroff30484702009-12-06 21:14:13 +00005375 // Initialize the block descriptor.
5376 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump11289f42009-09-09 15:08:12 +00005377
Steve Naroff30484702009-12-06 21:14:13 +00005378 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
5379 &Context->Idents.get(DescData.c_str()),
5380 Context->VoidPtrTy, 0,
John McCall8e7d6562010-08-26 03:08:43 +00005381 SC_Static, SC_None);
John McCall7decc9e2010-11-18 06:31:45 +00005382 UnaryOperator *DescRefExpr =
5383 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD,
5384 Context->VoidPtrTy,
5385 VK_LValue,
5386 SourceLocation()),
5387 UO_AddrOf,
5388 Context->getPointerType(Context->VoidPtrTy),
5389 VK_RValue, OK_Ordinary,
5390 SourceLocation());
Steve Naroff30484702009-12-06 21:14:13 +00005391 InitExprs.push_back(DescRefExpr);
5392
Steve Narofff4b992a2008-10-28 20:29:00 +00005393 // Add initializers for any closure decl refs.
5394 if (BlockDeclRefs.size()) {
Steve Naroffe2514232008-10-29 21:23:59 +00005395 Expr *Exp;
Steve Narofff4b992a2008-10-28 20:29:00 +00005396 // Output all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005397 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00005398 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005399 if (isObjCType((*I)->getType())) {
Steve Naroffe2514232008-10-29 21:23:59 +00005400 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar56df9772010-08-17 22:39:59 +00005401 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall7decc9e2010-11-18 06:31:45 +00005402 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5403 SourceLocation());
Fariborz Jahanian36680dd2010-05-24 18:32:56 +00005404 if (HasLocalVariableExternalStorage(*I)) {
5405 QualType QT = (*I)->getType();
5406 QT = Context->getPointerType(QT);
John McCall7decc9e2010-11-18 06:31:45 +00005407 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5408 OK_Ordinary, SourceLocation());
Fariborz Jahanian36680dd2010-05-24 18:32:56 +00005409 }
Steve Naroffa5c0db82008-12-11 21:05:33 +00005410 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar56df9772010-08-17 22:39:59 +00005411 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall7decc9e2010-11-18 06:31:45 +00005412 Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5413 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00005414 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCallf608deb2010-11-15 09:46:46 +00005415 CK_BitCast, Arg);
Steve Narofff4b992a2008-10-28 20:29:00 +00005416 } else {
Daniel Dunbar56df9772010-08-17 22:39:59 +00005417 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall7decc9e2010-11-18 06:31:45 +00005418 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5419 SourceLocation());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005420 if (HasLocalVariableExternalStorage(*I)) {
5421 QualType QT = (*I)->getType();
5422 QT = Context->getPointerType(QT);
John McCall7decc9e2010-11-18 06:31:45 +00005423 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5424 OK_Ordinary, SourceLocation());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005425 }
5426
Steve Narofff4b992a2008-10-28 20:29:00 +00005427 }
Mike Stump11289f42009-09-09 15:08:12 +00005428 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00005429 }
5430 // Output all "by ref" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005431 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00005432 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005433 ValueDecl *ND = (*I);
5434 std::string Name(ND->getNameAsString());
5435 std::string RecName;
5436 RewriteByRefString(RecName, Name, ND);
5437 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5438 + sizeof("struct"));
Abramo Bagnara6150c882010-05-11 21:36:43 +00005439 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005440 SourceLocation(), II);
5441 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5442 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5443
Daniel Dunbar56df9772010-08-17 22:39:59 +00005444 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall7decc9e2010-11-18 06:31:45 +00005445 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5446 SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00005447 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
John McCall7decc9e2010-11-18 06:31:45 +00005448 Context->getPointerType(Exp->getType()),
5449 VK_RValue, OK_Ordinary, SourceLocation());
John McCallf608deb2010-11-15 09:46:46 +00005450 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump11289f42009-09-09 15:08:12 +00005451 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00005452 }
5453 }
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00005454 if (ImportedBlockDecls.size()) {
5455 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5456 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff30484702009-12-06 21:14:13 +00005457 unsigned IntSize =
5458 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00005459 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5460 Context->IntTy, SourceLocation());
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00005461 InitExprs.push_back(FlagExp);
Steve Naroff30484702009-12-06 21:14:13 +00005462 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00005463 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
John McCall7decc9e2010-11-18 06:31:45 +00005464 FType, VK_LValue, SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00005465 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00005466 Context->getPointerType(NewRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00005467 VK_RValue, OK_Ordinary, SourceLocation());
John McCallf608deb2010-11-15 09:46:46 +00005468 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00005469 NewRep);
Steve Narofff4b992a2008-10-28 20:29:00 +00005470 BlockDeclRefs.clear();
5471 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005472 BlockByRefDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00005473 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005474 BlockByCopyDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00005475 ImportedBlockDecls.clear();
5476 return NewRep;
5477}
5478
5479//===----------------------------------------------------------------------===//
5480// Function Body / Expression rewriting
5481//===----------------------------------------------------------------------===//
5482
Steve Naroff4588d0f2008-12-04 16:24:46 +00005483// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
5484// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
5485// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
5486// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
5487// Since the rewriter isn't capable of rewriting rewritten code, it's important
5488// we get this right.
5489void RewriteObjC::CollectPropertySetters(Stmt *S) {
5490 // Perform a bottom up traversal of all children.
5491 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5492 CI != E; ++CI)
5493 if (*CI)
5494 CollectPropertySetters(*CI);
5495
5496 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
5497 if (BinOp->isAssignmentOp()) {
Fariborz Jahanianfef5d162010-10-11 22:21:03 +00005498 if (isa<ObjCPropertyRefExpr>(BinOp->getLHS()) ||
5499 isa<ObjCImplicitSetterGetterRefExpr>(BinOp->getLHS()))
5500 PropSetters[BinOp->getLHS()] = BinOp;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005501 }
5502 }
5503}
5504
Steve Narofff4b992a2008-10-28 20:29:00 +00005505Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump11289f42009-09-09 15:08:12 +00005506 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00005507 isa<DoStmt>(S) || isa<ForStmt>(S))
5508 Stmts.push_back(S);
5509 else if (isa<ObjCForCollectionStmt>(S)) {
5510 Stmts.push_back(S);
Chris Lattnerb71980f2010-01-09 21:45:57 +00005511 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofff4b992a2008-10-28 20:29:00 +00005512 }
Mike Stump11289f42009-09-09 15:08:12 +00005513
Steve Narofff4b992a2008-10-28 20:29:00 +00005514 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005515
Steve Narofff4b992a2008-10-28 20:29:00 +00005516 // Perform a bottom up rewrite of all children.
5517 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5518 CI != E; ++CI)
5519 if (*CI) {
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00005520 Stmt *newStmt;
5521 Stmt *S = (*CI);
5522 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5523 Expr *OldBase = IvarRefExpr->getBase();
5524 bool replaced = false;
5525 newStmt = RewriteObjCNestedIvarRefExpr(S, replaced);
5526 if (replaced) {
5527 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
5528 ReplaceStmt(OldBase, IRE->getBase());
5529 else
5530 ReplaceStmt(S, newStmt);
5531 }
5532 }
5533 else
5534 newStmt = RewriteFunctionBodyOrGlobalInitializer(S);
Mike Stump11289f42009-09-09 15:08:12 +00005535 if (newStmt)
Steve Narofff4b992a2008-10-28 20:29:00 +00005536 *CI = newStmt;
Fariborz Jahanian163488f2010-10-08 21:12:22 +00005537 // If dealing with an assignment with LHS being a property reference
5538 // expression, the entire assignment tree is rewritten into a property
5539 // setter messaging. This involvs the RHS too. Do not attempt to rewrite
5540 // RHS again.
Fariborz Jahanianfef5d162010-10-11 22:21:03 +00005541 if (Expr *Exp = dyn_cast<Expr>(S))
5542 if (isa<ObjCPropertyRefExpr>(Exp) ||
5543 isa<ObjCImplicitSetterGetterRefExpr>(Exp)) {
5544 if (PropSetters[Exp]) {
5545 ++CI;
5546 continue;
5547 }
Fariborz Jahanian163488f2010-10-08 21:12:22 +00005548 }
Nick Lewycky508ef2c2010-10-31 21:07:24 +00005549 }
Mike Stump11289f42009-09-09 15:08:12 +00005550
Steve Narofff4b992a2008-10-28 20:29:00 +00005551 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005552 llvm::SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00005553 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5554 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005555 ImportedLocalExternalDecls.clear();
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005556 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00005557 InnerBlockDeclRefs, InnerContexts);
Steve Narofff4b992a2008-10-28 20:29:00 +00005558 // Rewrite the block body in place.
Fariborz Jahanian086a24a2010-11-08 18:37:50 +00005559 Stmt *SaveCurrentBody = CurrentBody;
5560 CurrentBody = BE->getBody();
5561 PropParentMap = 0;
Steve Narofff4b992a2008-10-28 20:29:00 +00005562 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanian086a24a2010-11-08 18:37:50 +00005563 CurrentBody = SaveCurrentBody;
5564 PropParentMap = 0;
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005565 ImportedLocalExternalDecls.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00005566 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenekdb2ef372010-01-07 18:00:35 +00005567 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroffd8907b72008-10-29 18:15:37 +00005568 RewrittenBlockExprs[BE] = Str;
Mike Stump11289f42009-09-09 15:08:12 +00005569
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005570 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5571
Steve Narofff4b992a2008-10-28 20:29:00 +00005572 //blockTranscribed->dump();
Steve Naroffd8907b72008-10-29 18:15:37 +00005573 ReplaceStmt(S, blockTranscribed);
Steve Narofff4b992a2008-10-28 20:29:00 +00005574 return blockTranscribed;
5575 }
5576 // Handle specific things.
5577 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5578 return RewriteAtEncode(AtEncode);
Mike Stump11289f42009-09-09 15:08:12 +00005579
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00005580 if (isa<ObjCPropertyRefExpr>(S) || isa<ObjCImplicitSetterGetterRefExpr>(S)) {
5581 Expr *PropOrImplicitRefExpr = dyn_cast<Expr>(S);
5582 assert(PropOrImplicitRefExpr && "Property or implicit setter/getter is null");
5583
5584 BinaryOperator *BinOp = PropSetters[PropOrImplicitRefExpr];
Steve Naroff4588d0f2008-12-04 16:24:46 +00005585 if (BinOp) {
5586 // Because the rewriter doesn't allow us to rewrite rewritten code,
5587 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroff08628db2008-12-09 12:56:34 +00005588 DisableReplaceStmt = true;
5589 // Save the source range. Even if we disable the replacement, the
5590 // rewritten node will have been inserted into the tree. If the synthesized
5591 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump11289f42009-09-09 15:08:12 +00005592 // self.errorHandler = handler ? handler :
Steve Naroff08628db2008-12-09 12:56:34 +00005593 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5594 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroff4588d0f2008-12-04 16:24:46 +00005595 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Fariborz Jahanian9c07e172010-10-14 23:31:39 +00005596 // Need to rewrite the ivar access expression if need be.
5597 if (isa<ObjCIvarRefExpr>(newStmt)) {
5598 bool replaced = false;
5599 newStmt = RewriteObjCNestedIvarRefExpr(newStmt, replaced);
5600 }
5601
Steve Naroff08628db2008-12-09 12:56:34 +00005602 DisableReplaceStmt = false;
Steve Naroff22216db2008-12-04 23:50:32 +00005603 //
5604 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
5605 // we changed the RHS of BinOp, the rewriter would fail (since it needs
5606 // to see the original expression). Consider this example:
5607 //
5608 // Foo *obj1, *obj2;
5609 //
5610 // obj1.i = [obj2 rrrr];
5611 //
5612 // 'BinOp' for the previous expression looks like:
5613 //
5614 // (BinaryOperator 0x231ccf0 'int' '='
5615 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5616 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5617 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5618 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5619 //
5620 // 'newStmt' represents the rewritten message expression. For example:
5621 //
5622 // (CallExpr 0x231d300 'id':'struct objc_object *'
5623 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5624 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5625 // (CStyleCastExpr 0x231d220 'void *'
5626 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5627 //
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00005628 // Note that 'newStmt' is passed to RewritePropertyOrImplicitSetter so that it
Steve Naroff22216db2008-12-04 23:50:32 +00005629 // can be used as the setter argument. ReplaceStmt() will still 'see'
5630 // the original RHS (since we haven't altered BinOp).
5631 //
Mike Stump11289f42009-09-09 15:08:12 +00005632 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff22216db2008-12-04 23:50:32 +00005633 // node. As a result, we now leak the original AST nodes.
5634 //
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00005635 return RewritePropertyOrImplicitSetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroff4588d0f2008-12-04 16:24:46 +00005636 } else {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00005637 return RewritePropertyOrImplicitGetter(PropOrImplicitRefExpr);
Steve Narofff326f402008-12-03 00:56:33 +00005638 }
5639 }
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00005640
Steve Narofff4b992a2008-10-28 20:29:00 +00005641 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5642 return RewriteAtSelector(AtSelector);
Mike Stump11289f42009-09-09 15:08:12 +00005643
Steve Narofff4b992a2008-10-28 20:29:00 +00005644 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5645 return RewriteObjCStringLiteral(AtString);
Mike Stump11289f42009-09-09 15:08:12 +00005646
Steve Narofff4b992a2008-10-28 20:29:00 +00005647 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00005648#if 0
Steve Narofff4b992a2008-10-28 20:29:00 +00005649 // Before we rewrite it, put the original message expression in a comment.
5650 SourceLocation startLoc = MessExpr->getLocStart();
5651 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00005652
Steve Narofff4b992a2008-10-28 20:29:00 +00005653 const char *startBuf = SM->getCharacterData(startLoc);
5654 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump11289f42009-09-09 15:08:12 +00005655
Steve Narofff4b992a2008-10-28 20:29:00 +00005656 std::string messString;
5657 messString += "// ";
5658 messString.append(startBuf, endBuf-startBuf+1);
5659 messString += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00005660
5661 // FIXME: Missing definition of
Steve Narofff4b992a2008-10-28 20:29:00 +00005662 // InsertText(clang::SourceLocation, char const*, unsigned int).
5663 // InsertText(startLoc, messString.c_str(), messString.size());
5664 // Tried this, but it didn't work either...
5665 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff4588d0f2008-12-04 16:24:46 +00005666#endif
Steve Narofff4b992a2008-10-28 20:29:00 +00005667 return RewriteMessageExpr(MessExpr);
5668 }
Mike Stump11289f42009-09-09 15:08:12 +00005669
Steve Narofff4b992a2008-10-28 20:29:00 +00005670 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5671 return RewriteObjCTryStmt(StmtTry);
5672
5673 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5674 return RewriteObjCSynchronizedStmt(StmtTry);
5675
5676 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5677 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump11289f42009-09-09 15:08:12 +00005678
Steve Narofff4b992a2008-10-28 20:29:00 +00005679 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5680 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump11289f42009-09-09 15:08:12 +00005681
5682 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofff4b992a2008-10-28 20:29:00 +00005683 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump11289f42009-09-09 15:08:12 +00005684 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofff4b992a2008-10-28 20:29:00 +00005685 OrigStmtRange.getEnd());
5686 if (BreakStmt *StmtBreakStmt =
5687 dyn_cast<BreakStmt>(S))
5688 return RewriteBreakStmt(StmtBreakStmt);
5689 if (ContinueStmt *StmtContinueStmt =
5690 dyn_cast<ContinueStmt>(S))
5691 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump11289f42009-09-09 15:08:12 +00005692
5693 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofff4b992a2008-10-28 20:29:00 +00005694 // and cast exprs.
5695 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5696 // FIXME: What we're doing here is modifying the type-specifier that
5697 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump11289f42009-09-09 15:08:12 +00005698 // a separate type-specifier that we can rewrite.
Steve Naroffe70a52a2009-12-05 15:55:59 +00005699 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5700 // the context of an ObjCForCollectionStmt. For example:
5701 // NSArray *someArray;
5702 // for (id <FooProtocol> index in someArray) ;
5703 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5704 // and it depends on the original text locations/positions.
Benjamin Krameracc5fa12009-12-05 22:16:51 +00005705 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroffe70a52a2009-12-05 15:55:59 +00005706 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump11289f42009-09-09 15:08:12 +00005707
Steve Narofff4b992a2008-10-28 20:29:00 +00005708 // Blocks rewrite rules.
5709 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5710 DI != DE; ++DI) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +00005711 Decl *SD = *DI;
Steve Narofff4b992a2008-10-28 20:29:00 +00005712 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005713 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005714 RewriteBlockPointerDecl(ND);
Mike Stump11289f42009-09-09 15:08:12 +00005715 else if (ND->getType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005716 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00005717 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005718 if (VD->hasAttr<BlocksAttr>()) {
5719 static unsigned uniqueByrefDeclCount = 0;
5720 assert(!BlockByRefDeclNo.count(ND) &&
5721 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5722 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005723 RewriteByRefVar(VD);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005724 }
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00005725 else
5726 RewriteTypeOfDecl(VD);
5727 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005728 }
5729 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005730 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005731 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005732 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005733 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5734 }
5735 }
5736 }
Mike Stump11289f42009-09-09 15:08:12 +00005737
Steve Narofff4b992a2008-10-28 20:29:00 +00005738 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5739 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump11289f42009-09-09 15:08:12 +00005740
5741 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00005742 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5743 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump11289f42009-09-09 15:08:12 +00005744 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5745 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005746 && "Statement stack mismatch");
5747 Stmts.pop_back();
5748 }
5749 // Handle blocks rewriting.
5750 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5751 if (BDRE->isByRef())
Steve Naroffd9803712009-04-29 16:37:50 +00005752 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofff4b992a2008-10-28 20:29:00 +00005753 }
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005754 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5755 ValueDecl *VD = DRE->getDecl();
5756 if (VD->hasAttr<BlocksAttr>())
5757 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005758 if (HasLocalVariableExternalStorage(VD))
5759 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005760 }
5761
Steve Narofff4b992a2008-10-28 20:29:00 +00005762 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff350b6652008-10-30 10:07:53 +00005763 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00005764 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00005765 ReplaceStmt(S, BlockCall);
5766 return BlockCall;
5767 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005768 }
Steve Naroffc989a7b2008-11-03 23:29:32 +00005769 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005770 RewriteCastExpr(CE);
5771 }
5772#if 0
5773 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005774 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5775 ICE->getSubExpr(),
5776 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00005777 // Get the new text.
5778 std::string SStr;
5779 llvm::raw_string_ostream Buf(SStr);
Eli Friedman0905f142009-05-30 05:19:26 +00005780 Replacement->printPretty(Buf, *Context);
Steve Narofff4b992a2008-10-28 20:29:00 +00005781 const std::string &Str = Buf.str();
5782
5783 printf("CAST = %s\n", &Str[0]);
5784 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5785 delete S;
5786 return Replacement;
5787 }
5788#endif
5789 // Return this stmt unmodified.
5790 return S;
5791}
5792
Steve Naroffe70a52a2009-12-05 15:55:59 +00005793void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5794 for (RecordDecl::field_iterator i = RD->field_begin(),
5795 e = RD->field_end(); i != e; ++i) {
5796 FieldDecl *FD = *i;
5797 if (isTopLevelBlockPointerType(FD->getType()))
5798 RewriteBlockPointerDecl(FD);
5799 if (FD->getType()->isObjCQualifiedIdType() ||
5800 FD->getType()->isObjCQualifiedInterfaceType())
5801 RewriteObjCQualifiedInterfaceTypes(FD);
5802 }
5803}
5804
Steve Narofff4b992a2008-10-28 20:29:00 +00005805/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5806/// main file of the input.
5807void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5808 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffb1368882008-12-17 00:20:22 +00005809 if (FD->isOverloadedOperator())
5810 return;
Mike Stump11289f42009-09-09 15:08:12 +00005811
Steve Narofff4b992a2008-10-28 20:29:00 +00005812 // Since function prototypes don't have ParmDecl's, we check the function
5813 // prototype. This enables us to rewrite function declarations and
5814 // definitions using the same code.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005815 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005816
Sebastian Redla7b98a72009-04-26 20:35:05 +00005817 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis568bc842010-07-07 11:31:34 +00005818 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005819 CurFunctionDef = FD;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005820 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005821 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005822 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005823 Body =
5824 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5825 FD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005826 CurrentBody = 0;
5827 if (PropParentMap) {
5828 delete PropParentMap;
5829 PropParentMap = 0;
5830 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005831 // This synthesizes and inserts the block "impl" struct, invoke function,
5832 // and any copy/dispose helper functions.
5833 InsertBlockLiteralsWithinFunction(FD);
5834 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005835 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005836 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005837 return;
5838 }
5839 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005840 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005841 CurMethodDef = MD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005842 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005843 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005844 Body =
5845 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5846 MD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005847 CurrentBody = 0;
5848 if (PropParentMap) {
5849 delete PropParentMap;
5850 PropParentMap = 0;
5851 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005852 InsertBlockLiteralsWithinMethod(MD);
5853 CurMethodDef = 0;
5854 }
5855 }
5856 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5857 ClassImplementation.push_back(CI);
5858 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5859 CategoryImplementation.push_back(CI);
5860 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5861 RewriteForwardClassDecl(CD);
5862 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5863 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroffa5c0db82008-12-11 21:05:33 +00005864 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005865 RewriteBlockPointerDecl(VD);
Steve Naroffd8907b72008-10-29 18:15:37 +00005866 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005867 CheckFunctionPointerDecl(VD->getType(), VD);
5868 if (VD->getInit()) {
Steve Naroffc989a7b2008-11-03 23:29:32 +00005869 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005870 RewriteCastExpr(CE);
5871 }
5872 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00005873 } else if (VD->getType()->isRecordType()) {
5874 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5875 if (RD->isDefinition())
5876 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005877 }
Steve Naroffd8907b72008-10-29 18:15:37 +00005878 if (VD->getInit()) {
5879 GlobalVarDecl = VD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005880 CollectPropertySetters(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005881 CurrentBody = VD->getInit();
Steve Naroffd8907b72008-10-29 18:15:37 +00005882 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005883 CurrentBody = 0;
5884 if (PropParentMap) {
5885 delete PropParentMap;
5886 PropParentMap = 0;
5887 }
Mike Stump11289f42009-09-09 15:08:12 +00005888 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Daniel Dunbar56df9772010-08-17 22:39:59 +00005889 VD->getName());
Steve Naroffd8907b72008-10-29 18:15:37 +00005890 GlobalVarDecl = 0;
5891
5892 // This is needed for blocks.
Steve Naroffc989a7b2008-11-03 23:29:32 +00005893 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroffd8907b72008-10-29 18:15:37 +00005894 RewriteCastExpr(CE);
5895 }
5896 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005897 return;
5898 }
5899 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005900 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005901 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005902 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005903 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5904 return;
5905 }
5906 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroffe70a52a2009-12-05 15:55:59 +00005907 if (RD->isDefinition())
5908 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005909 return;
5910 }
5911 // Nothing yet.
5912}
5913
Chris Lattnercf169832009-03-28 04:11:33 +00005914void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005915 if (Diags.hasErrorOccurred())
5916 return;
Mike Stump11289f42009-09-09 15:08:12 +00005917
Steve Narofff4b992a2008-10-28 20:29:00 +00005918 RewriteInclude();
Mike Stump11289f42009-09-09 15:08:12 +00005919
Steve Naroffd9803712009-04-29 16:37:50 +00005920 // Here's a great place to add any extra declarations that may be needed.
5921 // Write out meta data for each @protocol(<expr>).
Mike Stump11289f42009-09-09 15:08:12 +00005922 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00005923 E = ProtocolExprDecls.end(); I != E; ++I)
5924 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5925
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005926 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005927 if (ClassImplementation.size() || CategoryImplementation.size())
5928 RewriteImplementations();
Steve Naroffd9803712009-04-29 16:37:50 +00005929
Steve Narofff4b992a2008-10-28 20:29:00 +00005930 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5931 // we are done.
Mike Stump11289f42009-09-09 15:08:12 +00005932 if (const RewriteBuffer *RewriteBuf =
Steve Narofff4b992a2008-10-28 20:29:00 +00005933 Rewrite.getRewriteBufferFor(MainFileID)) {
5934 //printf("Changed:\n");
5935 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5936 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005937 llvm::errs() << "No changes\n";
Steve Narofff4b992a2008-10-28 20:29:00 +00005938 }
Steve Narofff8cfd162008-11-13 20:07:04 +00005939
Steve Naroffd9803712009-04-29 16:37:50 +00005940 if (ClassImplementation.size() || CategoryImplementation.size() ||
5941 ProtocolExprDecls.size()) {
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005942 // Rewrite Objective-c meta data*
5943 std::string ResultStr;
5944 SynthesizeMetaDataIntoBuffer(ResultStr);
5945 // Emit metadata.
5946 *OutFile << ResultStr;
5947 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005948 OutFile->flush();
5949}