blob: cf11dc64c69cb67aa748087be76d9aa4125c52b3 [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,
Fariborz Jahanianee504a02011-01-27 23:18:15 +0000255 ValueDecl *VD, bool def=false);
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 }
John McCalldb40c7f2010-12-14 08:05:40 +0000453
454 QualType getSimpleFunctionType(QualType result,
455 const QualType *args,
456 unsigned numArgs,
457 bool variadic = false) {
458 FunctionProtoType::ExtProtoInfo fpi;
459 fpi.Variadic = variadic;
460 return Context->getFunctionType(result, args, numArgs, fpi);
461 }
Chris Lattnere99c8322007-10-11 00:43:27 +0000462 };
John McCall97513962010-01-15 18:39:57 +0000463
464 // Helper function: create a CStyleCastExpr with trivial type source info.
465 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +0000466 CastKind Kind, Expr *E) {
John McCall97513962010-01-15 18:39:57 +0000467 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
John McCall7decc9e2010-11-18 06:31:45 +0000468 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
John McCallcf142162010-08-07 06:22:56 +0000469 SourceLocation(), SourceLocation());
John McCall97513962010-01-15 18:39:57 +0000470 }
Chris Lattnere99c8322007-10-11 00:43:27 +0000471}
472
Mike Stump11289f42009-09-09 15:08:12 +0000473void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
474 NamedDecl *D) {
John McCall424cec92011-01-19 06:33:43 +0000475 if (const FunctionProtoType *fproto
Abramo Bagnara6d810632010-12-14 22:11:44 +0000476 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Mike Stump11289f42009-09-09 15:08:12 +0000477 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +0000478 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +0000479 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +0000480 // All the args are checked/rewritten. Don't call twice!
481 RewriteBlockPointerDecl(D);
482 break;
483 }
484 }
485}
486
487void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000488 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +0000489 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000490 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000491}
492
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000493static bool IsHeaderFile(const std::string &Filename) {
494 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump11289f42009-09-09 15:08:12 +0000495
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000496 if (DotPos == std::string::npos) {
497 // no file extension
Mike Stump11289f42009-09-09 15:08:12 +0000498 return false;
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000499 }
Mike Stump11289f42009-09-09 15:08:12 +0000500
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000501 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
502 // C header: .h
503 // C++ header: .hh or .H;
504 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump11289f42009-09-09 15:08:12 +0000505}
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000506
Eli Friedman94cf21e2009-05-18 22:20:00 +0000507RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000508 Diagnostic &D, const LangOptions &LOpts,
509 bool silenceMacroWarn)
510 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
511 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Narofff9e7c902008-03-28 22:26:09 +0000512 IsHeader = IsHeaderFile(inFile);
Mike Stump11289f42009-09-09 15:08:12 +0000513 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Narofff9e7c902008-03-28 22:26:09 +0000514 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump11289f42009-09-09 15:08:12 +0000515 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek5a201952009-02-07 01:47:29 +0000516 "rewriter doesn't support user-specified control flow semantics "
517 "for @try/@finally (code may not execute properly)");
Steve Narofff9e7c902008-03-28 22:26:09 +0000518}
519
Eli Friedmana63ab2d2009-05-18 22:29:17 +0000520ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
521 llvm::raw_ostream* OS,
Mike Stump11289f42009-09-09 15:08:12 +0000522 Diagnostic &Diags,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000523 const LangOptions &LOpts,
524 bool SilenceRewriteMacroWarning) {
525 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere9c810c2007-11-30 22:25:36 +0000526}
Chris Lattnere99c8322007-10-11 00:43:27 +0000527
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000528void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner187f6262008-01-31 19:38:44 +0000529 Context = &context;
530 SM = &Context->getSourceManager();
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +0000531 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner187f6262008-01-31 19:38:44 +0000532 MsgSendFunctionDecl = 0;
533 MsgSendSuperFunctionDecl = 0;
534 MsgSendStretFunctionDecl = 0;
535 MsgSendSuperStretFunctionDecl = 0;
536 MsgSendFpretFunctionDecl = 0;
537 GetClassFunctionDecl = 0;
538 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +0000539 GetSuperClassFunctionDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000540 SelGetUidFunctionDecl = 0;
541 CFStringFunctionDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000542 ConstantStringClassReference = 0;
543 NSStringRecord = 0;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000544 CurMethodDef = 0;
545 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000546 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000547 GlobalVarDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000548 SuperStructDecl = 0;
Steve Naroffd9803712009-04-29 16:37:50 +0000549 ProtocolTypeDecl = 0;
Steve Naroff60a9ef62008-03-27 22:59:54 +0000550 ConstantStringDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000551 BcLabelCount = 0;
Steve Naroff17978c42008-03-11 17:37:02 +0000552 SuperContructorFunctionDecl = 0;
Steve Naroffce8e8862008-03-15 00:55:56 +0000553 NumObjCStringLiterals = 0;
Steve Narofff1ab6002008-12-08 20:01:41 +0000554 PropParentMap = 0;
555 CurrentBody = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000556 DisableReplaceStmt = false;
Fariborz Jahanianbc6811c2010-01-07 22:51:18 +0000557 objc_impl_method = false;
Mike Stump11289f42009-09-09 15:08:12 +0000558
Chris Lattner187f6262008-01-31 19:38:44 +0000559 // Get the ID and start/end of the main file.
560 MainFileID = SM->getMainFileID();
561 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
562 MainFileStart = MainBuf->getBufferStart();
563 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000564
Chris Lattner184e65d2009-04-14 23:22:57 +0000565 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump11289f42009-09-09 15:08:12 +0000566
Chris Lattner187f6262008-01-31 19:38:44 +0000567 // declaring objc_selector outside the parameter list removes a silly
568 // scope related warning...
Steve Naroff00a31762008-03-27 22:29:16 +0000569 if (IsHeader)
Steve Narofffcc6fd52009-02-03 20:39:18 +0000570 Preamble = "#pragma once\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000571 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff6ab6dc72008-12-23 20:11:22 +0000572 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroff00a31762008-03-27 22:29:16 +0000573 Preamble += "struct objc_object *superClass; ";
Steve Naroff17978c42008-03-11 17:37:02 +0000574 if (LangOpts.Microsoft) {
575 // Add a constructor for creating temporary objects.
Ted Kremenek5a201952009-02-07 01:47:29 +0000576 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
577 ": ";
Steve Naroff00a31762008-03-27 22:29:16 +0000578 Preamble += "object(o), superClass(s) {} ";
Steve Naroff17978c42008-03-11 17:37:02 +0000579 }
Steve Naroff00a31762008-03-27 22:29:16 +0000580 Preamble += "};\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000581 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
582 Preamble += "typedef struct objc_object Protocol;\n";
583 Preamble += "#define _REWRITER_typedef_Protocol\n";
584 Preamble += "#endif\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000585 if (LangOpts.Microsoft) {
586 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
587 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
588 } else
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000589 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000590 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroff00a31762008-03-27 22:29:16 +0000591 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000592 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroff00a31762008-03-27 22:29:16 +0000593 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000594 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000595 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000596 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000597 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000598 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroff00a31762008-03-27 22:29:16 +0000599 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000600 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000601 Preamble += "(const char *);\n";
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +0000602 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
603 Preamble += "(struct objc_class *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000604 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000605 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000606 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
607 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
608 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
609 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
610 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroffd30f8c52008-05-09 21:17:56 +0000611 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff8dd15252008-07-16 18:58:11 +0000612 // @synchronized hooks.
Steve Narofff122ff02008-12-08 17:30:33 +0000613 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
614 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
615 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000616 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
617 Preamble += "struct __objcFastEnumerationState {\n\t";
618 Preamble += "unsigned long state;\n\t";
Steve Naroff4dbab8a2008-04-04 22:58:22 +0000619 Preamble += "void **itemsPtr;\n\t";
Steve Naroff00a31762008-03-27 22:29:16 +0000620 Preamble += "unsigned long *mutationsPtr;\n\t";
621 Preamble += "unsigned long extra[5];\n};\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000622 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000623 Preamble += "#define __FASTENUMERATIONSTATE\n";
624 Preamble += "#endif\n";
625 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
626 Preamble += "struct __NSConstantStringImpl {\n";
627 Preamble += " int *isa;\n";
628 Preamble += " int flags;\n";
629 Preamble += " char *str;\n";
630 Preamble += " long length;\n";
631 Preamble += "};\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000632 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
633 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
634 Preamble += "#else\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000635 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000636 Preamble += "#endif\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000637 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
638 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000639 // Blocks preamble.
640 Preamble += "#ifndef BLOCK_IMPL\n";
641 Preamble += "#define BLOCK_IMPL\n";
642 Preamble += "struct __block_impl {\n";
643 Preamble += " void *isa;\n";
644 Preamble += " int Flags;\n";
Steve Naroff30484702009-12-06 21:14:13 +0000645 Preamble += " int Reserved;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000646 Preamble += " void *FuncPtr;\n";
647 Preamble += "};\n";
Steve Naroff61d879e2008-12-16 15:50:30 +0000648 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroff287a2bf2009-12-06 01:52:22 +0000649 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000650 Preamble += "extern \"C\" __declspec(dllexport) "
651 "void _Block_object_assign(void *, const void *, const int);\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000652 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
653 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
654 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
655 Preamble += "#else\n";
Steve Naroff7bf01ea2010-01-05 18:09:31 +0000656 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
657 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000658 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
659 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
660 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000661 Preamble += "#endif\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000662 if (LangOpts.Microsoft) {
Steve Narofff122ff02008-12-08 17:30:33 +0000663 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
664 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Chris Lattner8d269dc2010-04-13 17:33:56 +0000665 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
Steve Naroffcb04e882008-10-27 18:50:14 +0000666 Preamble += "#define __attribute__(X)\n";
Chris Lattner8d269dc2010-04-13 17:33:56 +0000667 Preamble += "#endif\n";
Fariborz Jahanianf0462ff2010-01-15 22:29:39 +0000668 Preamble += "#define __weak\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000669 }
Fariborz Jahanian7fac6552010-01-05 19:21:35 +0000670 else {
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000671 Preamble += "#define __block\n";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +0000672 Preamble += "#define __weak\n";
673 }
Fariborz Jahaniandb217c42010-03-02 01:19:04 +0000674 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
675 // as this avoids warning in any 64bit/32bit compilation model.
676 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
Chris Lattner187f6262008-01-31 19:38:44 +0000677}
678
679
Chris Lattner3c799d72007-10-24 17:06:59 +0000680//===----------------------------------------------------------------------===//
681// Top Level Driver Code
682//===----------------------------------------------------------------------===//
683
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000684void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremenek31e7f0f2010-02-05 21:28:51 +0000685 if (Diags.hasErrorOccurred())
686 return;
687
Chris Lattner0bd1c972007-10-16 21:07:07 +0000688 // Two cases: either the decl could be in the main file, or it could be in a
689 // #included file. If the former, rewrite it now. If the later, check to see
690 // if we rewrote the #include/#import.
691 SourceLocation Loc = D->getLocation();
Chris Lattner8a425862009-01-16 07:36:28 +0000692 Loc = SM->getInstantiationLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000693
Chris Lattner0bd1c972007-10-16 21:07:07 +0000694 // If this is for a builtin, ignore it.
695 if (Loc.isInvalid()) return;
696
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000697 // Look for built-in declarations that we need to refer during the rewrite.
698 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000699 RewriteFunctionDecl(FD);
Steve Naroff08899ff2008-04-15 22:42:06 +0000700 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000701 // declared in <Foundation/NSString.h>
Daniel Dunbar56df9772010-08-17 22:39:59 +0000702 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffa397efd2007-11-03 11:27:19 +0000703 ConstantStringClassReference = FVD;
704 return;
705 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000706 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff161a92b2007-10-26 20:53:56 +0000707 RewriteInterfaceDecl(MD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000708 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000709 RewriteCategoryDecl(CD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000710 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff921385f2007-10-30 16:42:30 +0000711 RewriteProtocolDecl(PD);
Mike Stump11289f42009-09-09 15:08:12 +0000712 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000713 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000714 RewriteForwardProtocolDecl(FP);
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000715 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
716 // Recurse into linkage specifications
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000717 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
718 DIEnd = LSD->decls_end();
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000719 DI != DIEnd; ++DI)
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000720 HandleTopLevelSingleDecl(*DI);
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000721 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000722 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekd61ed3b2008-04-14 21:24:13 +0000723 if (SM->isFromMainFile(Loc))
Chris Lattner0bd1c972007-10-16 21:07:07 +0000724 return HandleDeclInMainFile(D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000725}
726
Chris Lattner3c799d72007-10-24 17:06:59 +0000727//===----------------------------------------------------------------------===//
728// Syntactic (non-AST) Rewriting Code
729//===----------------------------------------------------------------------===//
730
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000731void RewriteObjC::RewriteInclude() {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000732 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000733 llvm::StringRef MainBuf = SM->getBufferData(MainFileID);
734 const char *MainBufStart = MainBuf.begin();
735 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian80258362008-01-19 00:30:35 +0000736 size_t ImportLen = strlen("import");
Mike Stump11289f42009-09-09 15:08:12 +0000737
Fariborz Jahanian137d6932008-01-19 01:03:17 +0000738 // Loop over the whole file, looking for includes.
Fariborz Jahanian80258362008-01-19 00:30:35 +0000739 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
740 if (*BufPtr == '#') {
741 if (++BufPtr == MainBufEnd)
742 return;
743 while (*BufPtr == ' ' || *BufPtr == '\t')
744 if (++BufPtr == MainBufEnd)
745 return;
746 if (!strncmp(BufPtr, "import", ImportLen)) {
747 // replace import with include
Mike Stump11289f42009-09-09 15:08:12 +0000748 SourceLocation ImportLoc =
Fariborz Jahanian80258362008-01-19 00:30:35 +0000749 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000750 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian80258362008-01-19 00:30:35 +0000751 BufPtr += ImportLen;
752 }
753 }
754 }
Chris Lattner0bd1c972007-10-16 21:07:07 +0000755}
756
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000757static std::string getIvarAccessString(ObjCIvarDecl *OID) {
758 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroff9af94912008-12-02 15:48:25 +0000759 std::string S;
760 S = "((struct ";
761 S += ClassDecl->getIdentifier()->getName();
762 S += "_IMPL *)self)->";
Daniel Dunbar70e7ead2009-10-18 20:26:27 +0000763 S += OID->getName();
Steve Naroff9af94912008-12-02 15:48:25 +0000764 return S;
765}
766
Steve Naroffc038b3a2008-12-02 17:36:43 +0000767void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
768 ObjCImplementationDecl *IMD,
769 ObjCCategoryImplDecl *CID) {
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000770 static bool objcGetPropertyDefined = false;
771 static bool objcSetPropertyDefined = false;
Steve Naroffe1908e32008-12-01 20:33:01 +0000772 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000773 InsertText(startLoc, "// ");
Steve Naroff9af94912008-12-02 15:48:25 +0000774 const char *startBuf = SM->getCharacterData(startLoc);
775 assert((*startBuf == '@') && "bogus @synthesize location");
776 const char *semiBuf = strchr(startBuf, ';');
777 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek5a201952009-02-07 01:47:29 +0000778 SourceLocation onePastSemiLoc =
779 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroff9af94912008-12-02 15:48:25 +0000780
781 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
782 return; // FIXME: is this correct?
Mike Stump11289f42009-09-09 15:08:12 +0000783
Steve Naroff9af94912008-12-02 15:48:25 +0000784 // Generate the 'getter' function.
Steve Naroff9af94912008-12-02 15:48:25 +0000785 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroff9af94912008-12-02 15:48:25 +0000786 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000787
Steve Naroff003d00e2008-12-02 16:05:55 +0000788 if (!OID)
789 return;
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000790 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000791 if (!PD->getGetterMethodDecl()->isDefined()) {
792 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
793 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
794 ObjCPropertyDecl::OBJC_PR_copy));
795 std::string Getr;
796 if (GenGetProperty && !objcGetPropertyDefined) {
797 objcGetPropertyDefined = true;
798 // FIXME. Is this attribute correct in all cases?
799 Getr = "\nextern \"C\" __declspec(dllimport) "
800 "id objc_getProperty(id, SEL, long, bool);\n";
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000801 }
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000802 RewriteObjCMethodDecl(OID->getContainingInterface(),
803 PD->getGetterMethodDecl(), Getr);
804 Getr += "{ ";
805 // Synthesize an explicit cast to gain access to the ivar.
806 // See objc-act.c:objc_synthesize_new_getter() for details.
807 if (GenGetProperty) {
808 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
809 Getr += "typedef ";
810 const FunctionType *FPRetType = 0;
811 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
812 FPRetType);
813 Getr += " _TYPE";
814 if (FPRetType) {
815 Getr += ")"; // close the precedence "scope" for "*".
816
817 // Now, emit the argument types (if any).
818 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
819 Getr += "(";
820 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
821 if (i) Getr += ", ";
822 std::string ParamStr = FT->getArgType(i).getAsString(
823 Context->PrintingPolicy);
824 Getr += ParamStr;
825 }
826 if (FT->isVariadic()) {
827 if (FT->getNumArgs()) Getr += ", ";
828 Getr += "...";
829 }
830 Getr += ")";
831 } else
832 Getr += "()";
833 }
834 Getr += ";\n";
835 Getr += "return (_TYPE)";
836 Getr += "objc_getProperty(self, _cmd, ";
837 SynthesizeIvarOffsetComputation(OID, Getr);
838 Getr += ", 1)";
839 }
840 else
841 Getr += "return " + getIvarAccessString(OID);
842 Getr += "; }";
843 InsertText(onePastSemiLoc, Getr);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000844 }
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000845
846 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
Steve Naroff9af94912008-12-02 15:48:25 +0000847 return;
Mike Stump11289f42009-09-09 15:08:12 +0000848
Steve Naroff9af94912008-12-02 15:48:25 +0000849 // Generate the 'setter' function.
850 std::string Setr;
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000851 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
852 ObjCPropertyDecl::OBJC_PR_copy);
853 if (GenSetProperty && !objcSetPropertyDefined) {
854 objcSetPropertyDefined = true;
855 // FIXME. Is this attribute correct in all cases?
856 Setr = "\nextern \"C\" __declspec(dllimport) "
857 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
858 }
859
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000860 RewriteObjCMethodDecl(OID->getContainingInterface(),
861 PD->getSetterMethodDecl(), Setr);
Steve Naroff9af94912008-12-02 15:48:25 +0000862 Setr += "{ ";
Steve Naroff003d00e2008-12-02 16:05:55 +0000863 // Synthesize an explicit cast to initialize the ivar.
Steve Narofff326f402008-12-03 00:56:33 +0000864 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000865 if (GenSetProperty) {
866 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000867 SynthesizeIvarOffsetComputation(OID, Setr);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000868 Setr += ", (id)";
Daniel Dunbar56df9772010-08-17 22:39:59 +0000869 Setr += PD->getName();
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000870 Setr += ", ";
871 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
872 Setr += "0, ";
873 else
874 Setr += "1, ";
875 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
876 Setr += "1)";
877 else
878 Setr += "0)";
879 }
880 else {
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000881 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar56df9772010-08-17 22:39:59 +0000882 Setr += PD->getName();
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000883 }
Steve Naroff003d00e2008-12-02 16:05:55 +0000884 Setr += "; }";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000885 InsertText(onePastSemiLoc, Setr);
Steve Naroffe1908e32008-12-01 20:33:01 +0000886}
Chris Lattner16a0de42007-10-11 18:38:32 +0000887
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000888void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattner3c799d72007-10-24 17:06:59 +0000889 // Get the start location and compute the semi location.
890 SourceLocation startLoc = ClassDecl->getLocation();
891 const char *startBuf = SM->getCharacterData(startLoc);
892 const char *semiPtr = strchr(startBuf, ';');
Mike Stump11289f42009-09-09 15:08:12 +0000893
Chris Lattner3c799d72007-10-24 17:06:59 +0000894 // Translate to typedef's that forward reference structs with the same name
895 // as the class. As a convenience, we include the original declaration
896 // as a comment.
897 std::string typedefString;
Fariborz Jahanian1c2cb6d2010-01-11 22:48:40 +0000898 typedefString += "// @class ";
899 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
900 I != E; ++I) {
901 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
902 typedefString += ForwardDecl->getNameAsString();
903 if (I+1 != E)
904 typedefString += ", ";
905 else
906 typedefString += ";\n";
907 }
908
Chris Lattner9ee23b72009-02-20 18:04:31 +0000909 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
910 I != E; ++I) {
Ted Kremenek9b124e12009-11-18 00:28:11 +0000911 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff1b232132007-11-09 12:50:28 +0000912 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000913 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000914 typedefString += "\n";
915 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000916 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000917 typedefString += "\n";
Steve Naroff98eb8d12007-11-05 14:36:37 +0000918 typedefString += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000919 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000920 typedefString += ";\n#endif\n";
Steve Naroff574440f2007-10-24 22:48:43 +0000921 }
Mike Stump11289f42009-09-09 15:08:12 +0000922
Steve Naroff574440f2007-10-24 22:48:43 +0000923 // Replace the @class with typedefs corresponding to the classes.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000924 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
Chris Lattner3c799d72007-10-24 17:06:59 +0000925}
926
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000927void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000928 // When method is a synthesized one, such as a getter/setter there is
929 // nothing to rewrite.
930 if (Method->isSynthesized())
931 return;
Steve Naroff3ce37a62007-12-14 23:37:57 +0000932 SourceLocation LocStart = Method->getLocStart();
933 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000934
Chris Lattner88ea93e2009-02-04 01:06:56 +0000935 if (SM->getInstantiationLineNumber(LocEnd) >
936 SM->getInstantiationLineNumber(LocStart)) {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000937 InsertText(LocStart, "#if 0\n");
938 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff3ce37a62007-12-14 23:37:57 +0000939 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000940 InsertText(LocStart, "// ");
Steve Naroff5448cf62007-10-30 13:30:57 +0000941 }
942}
943
Mike Stump11289f42009-09-09 15:08:12 +0000944void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000945 SourceLocation Loc = prop->getAtLoc();
Mike Stump11289f42009-09-09 15:08:12 +0000946
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000947 ReplaceText(Loc, 0, "// ");
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000948 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahaniane8a30162007-11-07 00:09:37 +0000949}
950
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000951void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000952 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000953
Steve Naroff5448cf62007-10-30 13:30:57 +0000954 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000955 ReplaceText(LocStart, 0, "// ");
Mike Stump11289f42009-09-09 15:08:12 +0000956
Fariborz Jahanian68ebe632010-02-10 01:15:09 +0000957 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
958 E = CatDecl->prop_end(); I != E; ++I)
959 RewriteProperty(*I);
960
Mike Stump11289f42009-09-09 15:08:12 +0000961 for (ObjCCategoryDecl::instmeth_iterator
962 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000963 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000964 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +0000965 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000966 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000967 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000968 RewriteMethodDeclaration(*I);
969
Steve Naroff5448cf62007-10-30 13:30:57 +0000970 // Lastly, comment out the @end.
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +0000971 ReplaceText(CatDecl->getAtEndRange().getBegin(),
972 strlen("@end"), "/* @end */");
Steve Naroff5448cf62007-10-30 13:30:57 +0000973}
974
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000975void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Narofff921385f2007-10-30 16:42:30 +0000976 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000977
Steve Narofff921385f2007-10-30 16:42:30 +0000978 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000979 ReplaceText(LocStart, 0, "// ");
Mike Stump11289f42009-09-09 15:08:12 +0000980
981 for (ObjCProtocolDecl::instmeth_iterator
982 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000983 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000984 RewriteMethodDeclaration(*I);
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000985 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000986 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000987 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000988 RewriteMethodDeclaration(*I);
989
Fariborz Jahanianaa0f2b32010-09-24 18:36:58 +0000990 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
991 E = PDecl->prop_end(); I != E; ++I)
992 RewriteProperty(*I);
993
Steve Narofff921385f2007-10-30 16:42:30 +0000994 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +0000995 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +0000996 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroffa509f042007-11-14 15:03:57 +0000997
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000998 // Must comment out @optional/@required
999 const char *startBuf = SM->getCharacterData(LocStart);
1000 const char *endBuf = SM->getCharacterData(LocEnd);
1001 for (const char *p = startBuf; p < endBuf; p++) {
1002 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Steve Naroffa509f042007-11-14 15:03:57 +00001003 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001004 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump11289f42009-09-09 15:08:12 +00001005
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +00001006 }
1007 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Steve Naroffa509f042007-11-14 15:03:57 +00001008 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001009 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump11289f42009-09-09 15:08:12 +00001010
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +00001011 }
1012 }
Steve Narofff921385f2007-10-30 16:42:30 +00001013}
1014
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001015void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanianda6165c2007-11-14 00:42:16 +00001016 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffc17b0562007-11-14 03:37:28 +00001017 if (LocStart.isInvalid())
1018 assert(false && "Invalid SourceLocation");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +00001019 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001020 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +00001021}
1022
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001023void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1024 const FunctionType *&FPRetType) {
1025 if (T->isObjCQualifiedIdType())
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +00001026 ResultStr += "id";
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001027 else if (T->isFunctionPointerType() ||
1028 T->isBlockPointerType()) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001029 // needs special handling, since pointer-to-functions have special
1030 // syntax (where a decaration models use).
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001031 QualType retType = T;
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001032 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001033 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001034 PointeeTy = PT->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001035 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001036 PointeeTy = BPT->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00001037 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001038 ResultStr += FPRetType->getResultType().getAsString(
1039 Context->PrintingPolicy);
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001040 ResultStr += "(*";
Steve Naroffb067bbd2008-07-16 14:40:40 +00001041 }
1042 } else
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001043 ResultStr += T.getAsString(Context->PrintingPolicy);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001044}
1045
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001046void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1047 ObjCMethodDecl *OMD,
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001048 std::string &ResultStr) {
1049 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1050 const FunctionType *FPRetType = 0;
1051 ResultStr += "\nstatic ";
1052 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001053 ResultStr += " ";
Mike Stump11289f42009-09-09 15:08:12 +00001054
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001055 // Unique method name
Fariborz Jahanian56338352007-11-13 21:02:00 +00001056 std::string NameStr;
Mike Stump11289f42009-09-09 15:08:12 +00001057
Douglas Gregorffca3a22009-01-09 17:18:27 +00001058 if (OMD->isInstanceMethod())
Fariborz Jahanian56338352007-11-13 21:02:00 +00001059 NameStr += "_I_";
1060 else
1061 NameStr += "_C_";
Mike Stump11289f42009-09-09 15:08:12 +00001062
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001063 NameStr += IDecl->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +00001064 NameStr += "_";
Mike Stump11289f42009-09-09 15:08:12 +00001065
1066 if (ObjCCategoryImplDecl *CID =
Steve Naroff11b387f2009-01-08 19:41:02 +00001067 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001068 NameStr += CID->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +00001069 NameStr += "_";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001070 }
Mike Stump11289f42009-09-09 15:08:12 +00001071 // Append selector names, replacing ':' with '_'
Chris Lattnere4b95692008-11-24 03:33:13 +00001072 {
1073 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001074 int len = selString.size();
1075 for (int i = 0; i < len; i++)
1076 if (selString[i] == ':')
1077 selString[i] = '_';
Fariborz Jahanian56338352007-11-13 21:02:00 +00001078 NameStr += selString;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001079 }
Fariborz Jahanian56338352007-11-13 21:02:00 +00001080 // Remember this name for metadata emission
1081 MethodInternalNames[OMD] = NameStr;
1082 ResultStr += NameStr;
Mike Stump11289f42009-09-09 15:08:12 +00001083
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001084 // Rewrite arguments
1085 ResultStr += "(";
Mike Stump11289f42009-09-09 15:08:12 +00001086
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001087 // invisible arguments
Douglas Gregorffca3a22009-01-09 17:18:27 +00001088 if (OMD->isInstanceMethod()) {
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001089 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001090 selfTy = Context->getPointerType(selfTy);
Steve Naroffdc5b6b22008-03-12 00:25:36 +00001091 if (!LangOpts.Microsoft) {
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001092 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroffdc5b6b22008-03-12 00:25:36 +00001093 ResultStr += "struct ";
1094 }
1095 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001096 ResultStr += IDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00001097 ResultStr += " *";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001098 }
1099 else
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001100 ResultStr += Context->getObjCClassType().getAsString(
1101 Context->PrintingPolicy);
Mike Stump11289f42009-09-09 15:08:12 +00001102
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001103 ResultStr += " self, ";
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001104 ResultStr += Context->getObjCSelType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001105 ResultStr += " _cmd";
Mike Stump11289f42009-09-09 15:08:12 +00001106
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001107 // Method arguments.
Chris Lattnera4997152009-02-20 18:43:26 +00001108 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1109 E = OMD->param_end(); PI != E; ++PI) {
1110 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001111 ResultStr += ", ";
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001112 if (PDecl->getType()->isObjCQualifiedIdType()) {
1113 ResultStr += "id ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001114 ResultStr += PDecl->getNameAsString();
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001115 } else {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001116 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00001117 QualType QT = PDecl->getType();
1118 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1119 if (convertBlockPointerToFunctionPointer(QT))
1120 QT.getAsStringInternal(Name, Context->PrintingPolicy);
1121 else
Douglas Gregor7de59662009-05-29 20:38:28 +00001122 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001123 ResultStr += Name;
1124 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001125 }
Fariborz Jahanianeab81cd2008-01-21 20:14:23 +00001126 if (OMD->isVariadic())
1127 ResultStr += ", ...";
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001128 ResultStr += ") ";
Mike Stump11289f42009-09-09 15:08:12 +00001129
Steve Naroffb067bbd2008-07-16 14:40:40 +00001130 if (FPRetType) {
1131 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump11289f42009-09-09 15:08:12 +00001132
Steve Naroffb067bbd2008-07-16 14:40:40 +00001133 // Now, emit the argument types (if any).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001134 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001135 ResultStr += "(";
1136 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1137 if (i) ResultStr += ", ";
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001138 std::string ParamStr = FT->getArgType(i).getAsString(
1139 Context->PrintingPolicy);
Steve Naroffb067bbd2008-07-16 14:40:40 +00001140 ResultStr += ParamStr;
1141 }
1142 if (FT->isVariadic()) {
1143 if (FT->getNumArgs()) ResultStr += ", ";
1144 ResultStr += "...";
1145 }
1146 ResultStr += ")";
1147 } else {
1148 ResultStr += "()";
1149 }
1150 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001151}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001152void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001153 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1154 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump11289f42009-09-09 15:08:12 +00001155
Fariborz Jahanian02d964b2010-02-15 21:11:41 +00001156 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump11289f42009-09-09 15:08:12 +00001157
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001158 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001159 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1160 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001161 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001162 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001163 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001164 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001165 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001166 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redla7b98a72009-04-26 20:35:05 +00001167
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001168 const char *startBuf = SM->getCharacterData(LocStart);
1169 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001170 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001171 }
Mike Stump11289f42009-09-09 15:08:12 +00001172
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001173 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001174 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1175 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001176 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001177 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001178 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001179 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001180 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001181 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +00001182
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001183 const char *startBuf = SM->getCharacterData(LocStart);
1184 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001185 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001186 }
Steve Naroffe1908e32008-12-01 20:33:01 +00001187 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001188 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001189 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001190 I != E; ++I) {
Steve Naroffc038b3a2008-12-02 17:36:43 +00001191 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffe1908e32008-12-01 20:33:01 +00001192 }
1193
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001194 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001195}
1196
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001197void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffc5484042007-10-30 02:23:23 +00001198 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001199 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff2f55b982007-11-01 03:35:41 +00001200 // we haven't seen a forward decl - generate a typedef.
Steve Naroff03f27672007-11-14 23:02:56 +00001201 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001202 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001203 ResultStr += "\n";
1204 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001205 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001206 ResultStr += "\n";
Steve Naroffa1e115e2008-03-10 23:16:54 +00001207 ResultStr += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001208 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001209 ResultStr += ";\n#endif\n";
Steve Naroff2f55b982007-11-01 03:35:41 +00001210 // Mark this typedef as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001211 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff2f55b982007-11-01 03:35:41 +00001212 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001213 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump11289f42009-09-09 15:08:12 +00001214
1215 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001216 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff0c0f5ba2009-01-11 01:06:09 +00001217 RewriteProperty(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001218 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001219 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001220 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001221 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001222 for (ObjCInterfaceDecl::classmeth_iterator
1223 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001224 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001225 RewriteMethodDeclaration(*I);
1226
Steve Naroff4cd61ac2007-10-30 03:43:13 +00001227 // Lastly, comment out the @end.
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +00001228 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1229 "/* @end */");
Steve Naroff161a92b2007-10-26 20:53:56 +00001230}
1231
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001232Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroff08628db2008-12-09 12:56:34 +00001233 SourceRange SrcRange) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001234 ObjCMethodDecl *OMD = 0;
1235 QualType Ty;
1236 Selector Sel;
Duncan Sands3a02f3e2010-10-20 08:21:16 +00001237 Stmt *Receiver = 0;
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001238 bool Super = false;
1239 QualType SuperTy;
1240 SourceLocation SuperLocation;
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00001241 SourceLocation SelectorLoc;
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001242 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ObjCImplicitSetterGetterRefExpr.
Steve Naroff4588d0f2008-12-04 16:24:46 +00001243 // This allows us to reuse all the fun and games in SynthMessageExpr().
John McCallb7bd14f2010-12-02 01:19:52 +00001244 if (ObjCPropertyRefExpr *PropRefExpr =
1245 dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS())) {
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00001246 SelectorLoc = PropRefExpr->getLocation();
John McCallb7bd14f2010-12-02 01:19:52 +00001247 if (PropRefExpr->isExplicitProperty()) {
1248 ObjCPropertyDecl *PDecl = PropRefExpr->getExplicitProperty();
1249 OMD = PDecl->getSetterMethodDecl();
1250 Ty = PDecl->getType();
1251 Sel = PDecl->getSetterName();
1252 } else {
1253 OMD = PropRefExpr->getImplicitPropertySetter();
1254 Sel = OMD->getSelector();
1255 Ty = PropRefExpr->getType();
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001256 }
John McCallb7bd14f2010-12-02 01:19:52 +00001257 Super = PropRefExpr->isSuperReceiver();
1258 if (!Super) {
1259 Receiver = PropRefExpr->getBase();
1260 } else {
1261 SuperTy = PropRefExpr->getSuperReceiverType();
1262 SuperLocation = PropRefExpr->getReceiverLocation();
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001263 }
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001264 }
1265
1266 assert(OMD && "RewritePropertyOrImplicitSetter - null OMD");
Steve Naroff4588d0f2008-12-04 16:24:46 +00001267 llvm::SmallVector<Expr *, 1> ExprVec;
1268 ExprVec.push_back(newStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001269
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001270 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001271 if (Super)
Douglas Gregor9a129192010-04-21 00:45:42 +00001272 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001273 Ty.getNonReferenceType(),
John McCall7decc9e2010-11-18 06:31:45 +00001274 Expr::getValueKindForType(Ty),
Douglas Gregor9a129192010-04-21 00:45:42 +00001275 /*FIXME?*/SourceLocation(),
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001276 SuperLocation,
Douglas Gregor9a129192010-04-21 00:45:42 +00001277 /*IsInstanceSuper=*/true,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001278 SuperTy,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00001279 Sel, SelectorLoc, OMD,
Douglas Gregor9a129192010-04-21 00:45:42 +00001280 &ExprVec[0], 1,
1281 /*FIXME:*/SourceLocation());
Fariborz Jahanianbb40ea42010-10-20 16:07:20 +00001282 else {
1283 // FIXME. Refactor this into common code with that in
1284 // RewritePropertyOrImplicitGetter
1285 assert(Receiver && "RewritePropertyOrImplicitSetter - null Receiver");
1286 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1287 if (PropGetters[Exp])
1288 // This allows us to handle chain/nested property/implicit getters.
1289 Receiver = PropGetters[Exp];
1290
Douglas Gregor9a129192010-04-21 00:45:42 +00001291 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001292 Ty.getNonReferenceType(),
John McCall7decc9e2010-11-18 06:31:45 +00001293 Expr::getValueKindForType(Ty),
Douglas Gregor9a129192010-04-21 00:45:42 +00001294 /*FIXME: */SourceLocation(),
1295 cast<Expr>(Receiver),
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00001296 Sel, SelectorLoc, OMD,
Douglas Gregor9a129192010-04-21 00:45:42 +00001297 &ExprVec[0], 1,
1298 /*FIXME:*/SourceLocation());
Fariborz Jahanianbb40ea42010-10-20 16:07:20 +00001299 }
Steve Naroff4588d0f2008-12-04 16:24:46 +00001300 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001301
Steve Naroff4588d0f2008-12-04 16:24:46 +00001302 // Now do the actual rewrite.
Steve Naroff08628db2008-12-09 12:56:34 +00001303 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffdf705772008-12-10 14:53:27 +00001304 //delete BinOp;
Ted Kremenek5a201952009-02-07 01:47:29 +00001305 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1306 // to things that stay around.
1307 Context->Deallocate(MsgExpr);
Steve Naroff4588d0f2008-12-04 16:24:46 +00001308 return ReplacingStmt;
Steve Narofff326f402008-12-03 00:56:33 +00001309}
1310
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001311Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(Expr *PropOrGetterRefExpr) {
1312 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ImplicitGetter.
Steve Narofff326f402008-12-03 00:56:33 +00001313 // This allows us to reuse all the fun and games in SynthMessageExpr().
Ted Kremenekc81155e2010-10-19 23:10:22 +00001314 Stmt *Receiver = 0;
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001315 ObjCMethodDecl *OMD = 0;
1316 QualType Ty;
1317 Selector Sel;
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001318 bool Super = false;
1319 QualType SuperTy;
1320 SourceLocation SuperLocation;
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00001321 SourceLocation SelectorLoc;
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001322 if (ObjCPropertyRefExpr *PropRefExpr =
1323 dyn_cast<ObjCPropertyRefExpr>(PropOrGetterRefExpr)) {
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00001324 SelectorLoc = PropRefExpr->getLocation();
John McCallb7bd14f2010-12-02 01:19:52 +00001325 if (PropRefExpr->isExplicitProperty()) {
1326 ObjCPropertyDecl *PDecl = PropRefExpr->getExplicitProperty();
1327 OMD = PDecl->getGetterMethodDecl();
1328 Ty = PDecl->getType();
1329 Sel = PDecl->getGetterName();
1330 } else {
1331 OMD = PropRefExpr->getImplicitPropertyGetter();
1332 Sel = OMD->getSelector();
1333 Ty = PropRefExpr->getType();
1334 }
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001335 Super = PropRefExpr->isSuperReceiver();
1336 if (!Super)
1337 Receiver = PropRefExpr->getBase();
1338 else {
John McCallb7bd14f2010-12-02 01:19:52 +00001339 SuperTy = PropRefExpr->getSuperReceiverType();
1340 SuperLocation = PropRefExpr->getReceiverLocation();
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001341 }
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001342 }
1343
1344 assert (OMD && "RewritePropertyOrImplicitGetter - OMD is null");
1345
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001346 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001347 if (Super)
Douglas Gregor9a129192010-04-21 00:45:42 +00001348 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001349 Ty.getNonReferenceType(),
John McCall7decc9e2010-11-18 06:31:45 +00001350 Expr::getValueKindForType(Ty),
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001351 /*FIXME?*/SourceLocation(),
1352 SuperLocation,
Douglas Gregor9a129192010-04-21 00:45:42 +00001353 /*IsInstanceSuper=*/true,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001354 SuperTy,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00001355 Sel, SelectorLoc, OMD,
Douglas Gregor9a129192010-04-21 00:45:42 +00001356 0, 0,
1357 /*FIXME:*/SourceLocation());
Fariborz Jahanianbb40ea42010-10-20 16:07:20 +00001358 else {
1359 assert (Receiver && "RewritePropertyOrImplicitGetter - Receiver is null");
1360 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1361 if (PropGetters[Exp])
1362 // This allows us to handle chain/nested property/implicit getters.
1363 Receiver = PropGetters[Exp];
Douglas Gregor9a129192010-04-21 00:45:42 +00001364 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001365 Ty.getNonReferenceType(),
John McCall7decc9e2010-11-18 06:31:45 +00001366 Expr::getValueKindForType(Ty),
Douglas Gregor9a129192010-04-21 00:45:42 +00001367 /*FIXME:*/SourceLocation(),
1368 cast<Expr>(Receiver),
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00001369 Sel, SelectorLoc, OMD,
Douglas Gregor9a129192010-04-21 00:45:42 +00001370 0, 0,
1371 /*FIXME:*/SourceLocation());
Fariborz Jahanianbb40ea42010-10-20 16:07:20 +00001372 }
Steve Narofff326f402008-12-03 00:56:33 +00001373
Steve Naroff22216db2008-12-04 23:50:32 +00001374 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001375
1376 if (!PropParentMap)
1377 PropParentMap = new ParentMap(CurrentBody);
Fariborz Jahanian83e7d5a2010-12-04 21:22:13 +00001378 bool NestedPropertyRef = false;
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001379 Stmt *Parent = PropParentMap->getParent(PropOrGetterRefExpr);
Fariborz Jahanian83e7d5a2010-12-04 21:22:13 +00001380 ImplicitCastExpr*ICE=0;
1381 if (Parent)
1382 if ((ICE = dyn_cast<ImplicitCastExpr>(Parent))) {
1383 assert((ICE->getCastKind() == CK_GetObjCProperty)
1384 && "RewritePropertyOrImplicitGetter");
1385 Parent = PropParentMap->getParent(Parent);
1386 NestedPropertyRef = (Parent && isa<ObjCPropertyRefExpr>(Parent));
1387 }
1388 if (NestedPropertyRef) {
Steve Naroff1042ff32008-12-08 16:43:47 +00001389 // We stash away the ReplacingStmt since actually doing the
1390 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
Fariborz Jahanian83e7d5a2010-12-04 21:22:13 +00001391 PropGetters[ICE] = ReplacingStmt;
Ted Kremenek5a201952009-02-07 01:47:29 +00001392 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1393 // to things that stay around.
1394 Context->Deallocate(MsgExpr);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001395 return PropOrGetterRefExpr; // return the original...
Steve Naroff1042ff32008-12-08 16:43:47 +00001396 } else {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001397 ReplaceStmt(PropOrGetterRefExpr, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001398 // delete PropRefExpr; elsewhere...
Ted Kremenek5a201952009-02-07 01:47:29 +00001399 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1400 // to things that stay around.
1401 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001402 return ReplacingStmt;
1403 }
Steve Narofff326f402008-12-03 00:56:33 +00001404}
1405
Mike Stump11289f42009-09-09 15:08:12 +00001406Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001407 SourceLocation OrigStart,
1408 bool &replaced) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001409 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001410 const Expr *BaseExpr = IV->getBase();
Steve Naroff677ab3a2008-10-27 17:20:55 +00001411 if (CurMethodDef) {
Fariborz Jahanianf9e8c2b2010-01-26 18:28:51 +00001412 if (BaseExpr->getType()->isObjCObjectPointerType()) {
John McCall424cec92011-01-19 06:33:43 +00001413 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001414 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianf0ed69c2010-01-26 20:37:44 +00001415 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Naroffb1c02372008-05-08 17:52:16 +00001416 // lookup which class implements the instance variable.
1417 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001418 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001419 clsDeclared);
Steve Naroffb1c02372008-05-08 17:52:16 +00001420 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001421
Steve Naroffb1c02372008-05-08 17:52:16 +00001422 // Synthesize an explicit cast to gain access to the ivar.
1423 std::string RecName = clsDeclared->getIdentifier()->getName();
1424 RecName += "_IMPL";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001425 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara6150c882010-05-11 21:36:43 +00001426 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001427 SourceLocation(), II);
Steve Naroffb1c02372008-05-08 17:52:16 +00001428 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1429 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall97513962010-01-15 18:39:57 +00001430 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCallf608deb2010-11-15 09:46:46 +00001431 CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00001432 IV->getBase());
Steve Naroffb1c02372008-05-08 17:52:16 +00001433 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001434 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
John McCall7decc9e2010-11-18 06:31:45 +00001435 IV->getBase()->getLocEnd(),
1436 castExpr);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001437 replaced = true;
Mike Stump11289f42009-09-09 15:08:12 +00001438 if (IV->isFreeIvar() &&
Steve Naroff677ab3a2008-10-27 17:20:55 +00001439 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001440 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
John McCall7decc9e2010-11-18 06:31:45 +00001441 IV->getLocation(),
1442 D->getType(),
1443 VK_LValue, OK_Ordinary);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001444 // delete IV; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffb1c02372008-05-08 17:52:16 +00001445 return ME;
Steve Naroff05caa482007-11-15 11:33:00 +00001446 }
Fariborz Jahanian81310812010-01-28 01:41:20 +00001447 // Get the new text
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001448 // Cannot delete IV->getBase(), since PE points to it.
1449 // Replace the old base with the cast. This is important when doing
1450 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001451 IV->setBase(PE);
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001452 return IV;
Steve Naroff05caa482007-11-15 11:33:00 +00001453 }
Steve Naroff24840f62008-04-18 21:55:08 +00001454 } else { // we are outside a method.
Steve Naroff29ce4e52008-05-06 23:20:07 +00001455 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump11289f42009-09-09 15:08:12 +00001456
Steve Naroff29ce4e52008-05-06 23:20:07 +00001457 // Explicit ivar refs need to have a cast inserted.
1458 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian12e2e862010-01-12 17:31:23 +00001459 if (BaseExpr->getType()->isObjCObjectPointerType()) {
John McCall424cec92011-01-19 06:33:43 +00001460 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian9146e442010-01-11 17:50:35 +00001461 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001462 // lookup which class implements the instance variable.
1463 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001464 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001465 clsDeclared);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001466 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001467
Steve Naroff29ce4e52008-05-06 23:20:07 +00001468 // Synthesize an explicit cast to gain access to the ivar.
1469 std::string RecName = clsDeclared->getIdentifier()->getName();
1470 RecName += "_IMPL";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001471 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara6150c882010-05-11 21:36:43 +00001472 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001473 SourceLocation(), II);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001474 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1475 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall97513962010-01-15 18:39:57 +00001476 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCallf608deb2010-11-15 09:46:46 +00001477 CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00001478 IV->getBase());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001479 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001480 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner34873d22008-05-28 16:38:23 +00001481 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001482 replaced = true;
Steve Naroff29ce4e52008-05-06 23:20:07 +00001483 // Cannot delete IV->getBase(), since PE points to it.
1484 // Replace the old base with the cast. This is important when doing
1485 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001486 IV->setBase(PE);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001487 return IV;
1488 }
Steve Naroff05caa482007-11-15 11:33:00 +00001489 }
Steve Naroff24840f62008-04-18 21:55:08 +00001490 return IV;
Steve Narofff60782b2007-11-15 02:58:25 +00001491}
1492
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001493Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
1494 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1495 CI != E; ++CI) {
1496 if (*CI) {
1497 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1498 if (newStmt)
1499 *CI = newStmt;
1500 }
1501 }
1502 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1503 SourceRange OrigStmtRange = S->getSourceRange();
1504 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1505 replaced);
1506 return newStmt;
Fariborz Jahanian31433382010-02-05 17:48:10 +00001507 }
1508 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1509 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1510 return newStmt;
1511 }
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001512 return S;
1513}
1514
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001515/// SynthCountByEnumWithState - To print:
1516/// ((unsigned int (*)
1517/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001518/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001519/// sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001520/// "countByEnumeratingWithState:objects:count:"),
1521/// &enumState,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001522/// (id *)items, (unsigned int)16)
1523///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001524void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001525 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1526 "id *, unsigned int))(void *)objc_msgSend)";
1527 buf += "\n\t\t";
1528 buf += "((id)l_collection,\n\t\t";
1529 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1530 buf += "\n\t\t";
1531 buf += "&enumState, "
1532 "(id *)items, (unsigned int)16)";
1533}
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001534
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001535/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1536/// statement to exit to its outer synthesized loop.
1537///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001538Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001539 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1540 return S;
1541 // replace break with goto __break_label
1542 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001543
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001544 SourceLocation startLoc = S->getLocStart();
1545 buf = "goto __break_label_";
1546 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001547 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001548
1549 return 0;
1550}
1551
1552/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1553/// statement to continue with its inner synthesized loop.
1554///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001555Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001556 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1557 return S;
1558 // replace continue with goto __continue_label
1559 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001560
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001561 SourceLocation startLoc = S->getLocStart();
1562 buf = "goto __continue_label_";
1563 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001564 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump11289f42009-09-09 15:08:12 +00001565
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001566 return 0;
1567}
1568
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001569/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001570/// It rewrites:
1571/// for ( type elem in collection) { stmts; }
Mike Stump11289f42009-09-09 15:08:12 +00001572
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001573/// Into:
1574/// {
Mike Stump11289f42009-09-09 15:08:12 +00001575/// type elem;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001576/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001577/// id items[16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001578/// id l_collection = (id)collection;
Mike Stump11289f42009-09-09 15:08:12 +00001579/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001580/// objects:items count:16];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001581/// if (limit) {
1582/// unsigned long startMutations = *enumState.mutationsPtr;
1583/// do {
1584/// unsigned long counter = 0;
1585/// do {
Mike Stump11289f42009-09-09 15:08:12 +00001586/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001587/// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001588/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001589/// stmts;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001590/// __continue_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001591/// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001592/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001593/// objects:items count:16]);
1594/// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001595/// __break_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001596/// }
1597/// else
1598/// elem = nil;
1599/// }
1600///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001601Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattnera779d692008-01-31 05:10:40 +00001602 SourceLocation OrigEnd) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001603 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001604 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001605 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump11289f42009-09-09 15:08:12 +00001606 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001607 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001608
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001609 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001610 const char *startBuf = SM->getCharacterData(startLoc);
Daniel Dunbar56df9772010-08-17 22:39:59 +00001611 llvm::StringRef elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001612 std::string elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001613 std::string buf;
1614 buf = "\n{\n\t";
1615 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1616 // type elem;
Chris Lattner529efc72009-03-28 06:33:19 +00001617 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek292b3842008-10-06 22:16:13 +00001618 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001619 if (ElementType->isObjCQualifiedIdType() ||
1620 ElementType->isObjCQualifiedInterfaceType())
1621 // Simply use 'id' for all qualified types.
1622 elementTypeAsString = "id";
1623 else
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001624 elementTypeAsString = ElementType.getAsString(Context->PrintingPolicy);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001625 buf += elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001626 buf += " ";
Daniel Dunbar56df9772010-08-17 22:39:59 +00001627 elementName = D->getName();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001628 buf += elementName;
1629 buf += ";\n\t";
1630 }
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001631 else {
1632 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar56df9772010-08-17 22:39:59 +00001633 elementName = DR->getDecl()->getName();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001634 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1635 if (VD->getType()->isObjCQualifiedIdType() ||
1636 VD->getType()->isObjCQualifiedInterfaceType())
1637 // Simply use 'id' for all qualified types.
1638 elementTypeAsString = "id";
1639 else
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001640 elementTypeAsString = VD->getType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001641 }
Mike Stump11289f42009-09-09 15:08:12 +00001642
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001643 // struct __objcFastEnumerationState enumState = { 0 };
1644 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1645 // id items[16];
1646 buf += "id items[16];\n\t";
1647 // id l_collection = (id)
1648 buf += "id l_collection = (id)";
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001649 // Find start location of 'collection' the hard way!
1650 const char *startCollectionBuf = startBuf;
1651 startCollectionBuf += 3; // skip 'for'
1652 startCollectionBuf = strchr(startCollectionBuf, '(');
1653 startCollectionBuf++; // skip '('
1654 // find 'in' and skip it.
1655 while (*startCollectionBuf != ' ' ||
1656 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1657 (*(startCollectionBuf+3) != ' ' &&
1658 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1659 startCollectionBuf++;
1660 startCollectionBuf += 3;
Mike Stump11289f42009-09-09 15:08:12 +00001661
1662 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001663 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001664 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001665 SourceLocation rightParenLoc = S->getRParenLoc();
1666 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1667 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001668 buf = ";\n\t";
Mike Stump11289f42009-09-09 15:08:12 +00001669
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001670 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1671 // objects:items count:16];
1672 // which is synthesized into:
Mike Stump11289f42009-09-09 15:08:12 +00001673 // unsigned int limit =
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001674 // ((unsigned int (*)
1675 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001676 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001677 // sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001678 // "countByEnumeratingWithState:objects:count:"),
1679 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001680 // (id *)items, (unsigned int)16);
1681 buf += "unsigned long limit =\n\t\t";
1682 SynthCountByEnumWithState(buf);
1683 buf += ";\n\t";
1684 /// if (limit) {
1685 /// unsigned long startMutations = *enumState.mutationsPtr;
1686 /// do {
1687 /// unsigned long counter = 0;
1688 /// do {
Mike Stump11289f42009-09-09 15:08:12 +00001689 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001690 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001691 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001692 buf += "if (limit) {\n\t";
1693 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1694 buf += "do {\n\t\t";
1695 buf += "unsigned long counter = 0;\n\t\t";
1696 buf += "do {\n\t\t\t";
1697 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1698 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1699 buf += elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001700 buf += " = (";
1701 buf += elementTypeAsString;
1702 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001703 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001704 ReplaceText(lparenLoc, 1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001705
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001706 /// __continue_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001707 /// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001708 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001709 /// objects:items count:16]);
1710 /// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001711 /// __break_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001712 /// }
1713 /// else
1714 /// elem = nil;
1715 /// }
Mike Stump11289f42009-09-09 15:08:12 +00001716 ///
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001717 buf = ";\n\t";
1718 buf += "__continue_label_";
1719 buf += utostr(ObjCBcLabelNo.back());
1720 buf += ": ;";
1721 buf += "\n\t\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001722 buf += "} while (counter < limit);\n\t";
1723 buf += "} while (limit = ";
1724 SynthCountByEnumWithState(buf);
1725 buf += ");\n\t";
1726 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001727 buf += " = ((";
1728 buf += elementTypeAsString;
1729 buf += ")0);\n\t";
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001730 buf += "__break_label_";
1731 buf += utostr(ObjCBcLabelNo.back());
1732 buf += ": ;\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001733 buf += "}\n\t";
1734 buf += "else\n\t\t";
1735 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001736 buf += " = ((";
1737 buf += elementTypeAsString;
1738 buf += ")0);\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001739 buf += "}\n";
Mike Stump11289f42009-09-09 15:08:12 +00001740
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001741 // Insert all these *after* the statement body.
Sebastian Redla7b98a72009-04-26 20:35:05 +00001742 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Narofff0ff8792008-07-21 18:26:02 +00001743 if (isa<CompoundStmt>(S->getBody())) {
1744 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001745 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001746 } else {
1747 /* Need to treat single statements specially. For example:
1748 *
1749 * for (A *a in b) if (stuff()) break;
1750 * for (A *a in b) xxxyy;
1751 *
1752 * The following code simply scans ahead to the semi to find the actual end.
1753 */
1754 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1755 const char *semiBuf = strchr(stmtBuf, ';');
1756 assert(semiBuf && "Can't find ';'");
1757 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001758 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001759 }
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001760 Stmts.pop_back();
1761 ObjCBcLabelNo.pop_back();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001762 return 0;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001763}
1764
Mike Stump11289f42009-09-09 15:08:12 +00001765/// RewriteObjCSynchronizedStmt -
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001766/// This routine rewrites @synchronized(expr) stmt;
1767/// into:
1768/// objc_sync_enter(expr);
1769/// @try stmt @finally { objc_sync_exit(expr); }
1770///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001771Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001772 // Get the start location and compute the semi location.
1773 SourceLocation startLoc = S->getLocStart();
1774 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001775
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001776 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump11289f42009-09-09 15:08:12 +00001777
1778 std::string buf;
Steve Naroffb2fc0522008-08-21 13:03:03 +00001779 buf = "objc_sync_enter((id)";
1780 const char *lparenBuf = startBuf;
1781 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001782 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001783 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1784 // the sync expression is typically a message expression that's already
Steve Naroffad7013b2008-08-19 13:04:19 +00001785 // been rewritten! (which implies the SourceLocation's are invalid).
1786 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001787 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffad7013b2008-08-19 13:04:19 +00001788 while (*endBuf != ')') endBuf--;
1789 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001790 buf = ");\n";
1791 // declare a new scope with two variables, _stack and _rethrow.
1792 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1793 buf += "int buf[18/*32-bit i386*/];\n";
1794 buf += "char *pointers[4];} _stack;\n";
1795 buf += "id volatile _rethrow = 0;\n";
1796 buf += "objc_exception_try_enter(&_stack);\n";
1797 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001798 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001799 startLoc = S->getSynchBody()->getLocEnd();
1800 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001801
Steve Naroffad7013b2008-08-19 13:04:19 +00001802 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001803 SourceLocation lastCurlyLoc = startLoc;
1804 buf = "}\nelse {\n";
1805 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroffd9803712009-04-29 16:37:50 +00001806 buf += "}\n";
1807 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001808 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffec60b432009-12-05 21:43:12 +00001809
1810 std::string syncBuf;
1811 syncBuf += " objc_sync_exit(";
John McCall97513962010-01-15 18:39:57 +00001812 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00001813 CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00001814 S->getSynchExpr());
Ted Kremenek2d470fc2008-09-13 05:16:45 +00001815 std::string syncExprBufS;
1816 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00001817 syncExpr->printPretty(syncExprBuf, *Context, 0,
1818 PrintingPolicy(LangOpts));
Steve Naroffec60b432009-12-05 21:43:12 +00001819 syncBuf += syncExprBuf.str();
1820 syncBuf += ");";
1821
1822 buf += syncBuf;
1823 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001824 buf += "}\n";
1825 buf += "}";
Mike Stump11289f42009-09-09 15:08:12 +00001826
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001827 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00001828
1829 bool hasReturns = false;
1830 HasReturnStmts(S->getSynchBody(), hasReturns);
1831 if (hasReturns)
1832 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1833
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001834 return 0;
1835}
1836
Steve Naroffec60b432009-12-05 21:43:12 +00001837void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1838{
Steve Naroff6d6da252008-12-05 17:03:39 +00001839 // Perform a bottom up traversal of all children.
1840 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1841 CI != E; ++CI)
1842 if (*CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001843 WarnAboutReturnGotoStmts(*CI);
Steve Naroff6d6da252008-12-05 17:03:39 +00001844
Steve Naroffec60b432009-12-05 21:43:12 +00001845 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump11289f42009-09-09 15:08:12 +00001846 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff6d6da252008-12-05 17:03:39 +00001847 TryFinallyContainsReturnDiag);
1848 }
1849 return;
1850}
1851
Steve Naroffec60b432009-12-05 21:43:12 +00001852void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1853{
1854 // Perform a bottom up traversal of all children.
1855 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1856 CI != E; ++CI)
1857 if (*CI)
1858 HasReturnStmts(*CI, hasReturns);
1859
1860 if (isa<ReturnStmt>(S))
1861 hasReturns = true;
1862 return;
1863}
1864
1865void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1866 // Perform a bottom up traversal of all children.
1867 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1868 CI != E; ++CI)
1869 if (*CI) {
1870 RewriteTryReturnStmts(*CI);
1871 }
1872 if (isa<ReturnStmt>(S)) {
1873 SourceLocation startLoc = S->getLocStart();
1874 const char *startBuf = SM->getCharacterData(startLoc);
1875
1876 const char *semiBuf = strchr(startBuf, ';');
1877 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1878 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1879
1880 std::string buf;
1881 buf = "{ objc_exception_try_exit(&_stack); return";
1882
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001883 ReplaceText(startLoc, 6, buf);
1884 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001885 }
1886 return;
1887}
1888
1889void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1890 // Perform a bottom up traversal of all children.
1891 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1892 CI != E; ++CI)
1893 if (*CI) {
1894 RewriteSyncReturnStmts(*CI, syncExitBuf);
1895 }
1896 if (isa<ReturnStmt>(S)) {
1897 SourceLocation startLoc = S->getLocStart();
1898 const char *startBuf = SM->getCharacterData(startLoc);
1899
1900 const char *semiBuf = strchr(startBuf, ';');
1901 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1902 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1903
1904 std::string buf;
1905 buf = "{ objc_exception_try_exit(&_stack);";
1906 buf += syncExitBuf;
1907 buf += " return";
1908
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001909 ReplaceText(startLoc, 6, buf);
1910 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001911 }
1912 return;
1913}
1914
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001915Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001916 // Get the start location and compute the semi location.
1917 SourceLocation startLoc = S->getLocStart();
1918 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001919
Steve Naroffbf478ec2007-11-07 04:08:17 +00001920 assert((*startBuf == '@') && "bogus @try location");
1921
1922 std::string buf;
1923 // declare a new scope with two variables, _stack and _rethrow.
1924 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1925 buf += "int buf[18/*32-bit i386*/];\n";
1926 buf += "char *pointers[4];} _stack;\n";
1927 buf += "id volatile _rethrow = 0;\n";
1928 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff16018582007-11-07 18:43:40 +00001929 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffbf478ec2007-11-07 04:08:17 +00001930
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001931 ReplaceText(startLoc, 4, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001932
Steve Naroffbf478ec2007-11-07 04:08:17 +00001933 startLoc = S->getTryBody()->getLocEnd();
1934 startBuf = SM->getCharacterData(startLoc);
1935
1936 assert((*startBuf == '}') && "bogus @try block");
Mike Stump11289f42009-09-09 15:08:12 +00001937
Steve Naroffbf478ec2007-11-07 04:08:17 +00001938 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor96c79492010-04-23 22:50:49 +00001939 if (S->getNumCatchStmts()) {
Steve Naroffce2dca12008-07-16 15:31:30 +00001940 startLoc = startLoc.getFileLocWithOffset(1);
1941 buf = " /* @catch begin */ else {\n";
1942 buf += " id _caught = objc_exception_extract(&_stack);\n";
1943 buf += " objc_exception_try_enter (&_stack);\n";
1944 buf += " if (_setjmp(_stack.buf))\n";
1945 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1946 buf += " else { /* @catch continue */";
Mike Stump11289f42009-09-09 15:08:12 +00001947
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001948 InsertText(startLoc, buf);
Steve Narofffac18fe2008-09-09 19:59:12 +00001949 } else { /* no catch list */
1950 buf = "}\nelse {\n";
1951 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1952 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001953 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffce2dca12008-07-16 15:31:30 +00001954 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001955 Stmt *lastCatchBody = 0;
Douglas Gregor96c79492010-04-23 22:50:49 +00001956 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1957 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregor46a572b2010-04-26 16:46:50 +00001958 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001959
Douglas Gregor96c79492010-04-23 22:50:49 +00001960 if (I == 0)
Steve Naroffbf478ec2007-11-07 04:08:17 +00001961 buf = "if ("; // we are generating code for the first catch clause
1962 else
1963 buf = "else if (";
Douglas Gregor96c79492010-04-23 22:50:49 +00001964 startLoc = Catch->getLocStart();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001965 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001966
Steve Naroffbf478ec2007-11-07 04:08:17 +00001967 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump11289f42009-09-09 15:08:12 +00001968
Steve Naroffbf478ec2007-11-07 04:08:17 +00001969 const char *lParenLoc = strchr(startBuf, '(');
1970
Douglas Gregor96c79492010-04-23 22:50:49 +00001971 if (Catch->hasEllipsis()) {
Steve Naroffedb5bc62008-02-01 20:02:07 +00001972 // Now rewrite the body...
Douglas Gregor96c79492010-04-23 22:50:49 +00001973 lastCatchBody = Catch->getCatchBody();
Steve Naroffedb5bc62008-02-01 20:02:07 +00001974 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1975 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor96c79492010-04-23 22:50:49 +00001976 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001977 "bogus @catch paren location");
Steve Naroffedb5bc62008-02-01 20:02:07 +00001978 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001979
Steve Naroffedb5bc62008-02-01 20:02:07 +00001980 buf += "1) { id _tmp = _caught;";
Daniel Dunbardec484a2009-08-19 19:10:30 +00001981 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff371b8fb2009-03-03 19:52:17 +00001982 } else if (catchDecl) {
1983 QualType t = catchDecl->getType();
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001984 if (t == Context->getObjCIdType()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001985 buf += "1) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001986 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
John McCall96fa4842010-05-17 21:00:27 +00001987 } else if (const ObjCObjectPointerType *Ptr =
1988 t->getAs<ObjCObjectPointerType>()) {
1989 // Should be a pointer to a class.
1990 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1991 if (IDecl) {
Steve Naroff16018582007-11-07 18:43:40 +00001992 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall96fa4842010-05-17 21:00:27 +00001993 buf += IDecl->getNameAsString();
Steve Naroff16018582007-11-07 18:43:40 +00001994 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001995 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroffbf478ec2007-11-07 04:08:17 +00001996 }
1997 }
1998 // Now rewrite the body...
Douglas Gregor96c79492010-04-23 22:50:49 +00001999 lastCatchBody = Catch->getCatchBody();
2000 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroffbf478ec2007-11-07 04:08:17 +00002001 SourceLocation bodyLoc = lastCatchBody->getLocStart();
2002 const char *bodyBuf = SM->getCharacterData(bodyLoc);
2003 const char *rParenBuf = SM->getCharacterData(rParenLoc);
2004 assert((*rParenBuf == ')') && "bogus @catch paren location");
2005 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00002006
Mike Stump11289f42009-09-09 15:08:12 +00002007 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroffbf478ec2007-11-07 04:08:17 +00002008 // declares the @catch parameter).
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002009 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff371b8fb2009-03-03 19:52:17 +00002010 } else {
Steve Naroffbf478ec2007-11-07 04:08:17 +00002011 assert(false && "@catch rewrite bug");
Steve Naroffa733c7f2007-11-07 15:32:26 +00002012 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00002013 }
2014 // Complete the catch list...
2015 if (lastCatchBody) {
2016 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00002017 assert(*SM->getCharacterData(bodyLoc) == '}' &&
2018 "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00002019
Steve Naroff4adbe312008-09-11 15:29:03 +00002020 // Insert the last (implicit) else clause *before* the right curly brace.
2021 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
2022 buf = "} /* last catch end */\n";
2023 buf += "else {\n";
2024 buf += " _rethrow = _caught;\n";
2025 buf += " objc_exception_try_exit(&_stack);\n";
2026 buf += "} } /* @catch end */\n";
2027 if (!S->getFinallyStmt())
2028 buf += "}\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002029 InsertText(bodyLoc, buf);
Mike Stump11289f42009-09-09 15:08:12 +00002030
Steve Naroffbf478ec2007-11-07 04:08:17 +00002031 // Set lastCurlyLoc
2032 lastCurlyLoc = lastCatchBody->getLocEnd();
2033 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002034 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00002035 startLoc = finalStmt->getLocStart();
2036 startBuf = SM->getCharacterData(startLoc);
2037 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump11289f42009-09-09 15:08:12 +00002038
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002039 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump11289f42009-09-09 15:08:12 +00002040
Steve Naroffbf478ec2007-11-07 04:08:17 +00002041 Stmt *body = finalStmt->getFinallyBody();
2042 SourceLocation startLoc = body->getLocStart();
2043 SourceLocation endLoc = body->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00002044 assert(*SM->getCharacterData(startLoc) == '{' &&
2045 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00002046 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00002047 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00002048
Steve Naroffbf478ec2007-11-07 04:08:17 +00002049 startLoc = startLoc.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002050 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Steve Naroffbf478ec2007-11-07 04:08:17 +00002051 endLoc = endLoc.getFileLocWithOffset(-1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002052 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump11289f42009-09-09 15:08:12 +00002053
Steve Naroffbf478ec2007-11-07 04:08:17 +00002054 // Set lastCurlyLoc
2055 lastCurlyLoc = body->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00002056
Steve Naroff6d6da252008-12-05 17:03:39 +00002057 // Now check for any return/continue/go statements within the @try.
Steve Naroffec60b432009-12-05 21:43:12 +00002058 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff4adbe312008-09-11 15:29:03 +00002059 } else { /* no finally clause - make sure we synthesize an implicit one */
2060 buf = "{ /* implicit finally clause */\n";
2061 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
2062 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
2063 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002064 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00002065
2066 // Now check for any return/continue/go statements within the @try.
2067 // The implicit finally clause won't called if the @try contains any
2068 // jump statements.
2069 bool hasReturns = false;
2070 HasReturnStmts(S->getTryBody(), hasReturns);
2071 if (hasReturns)
2072 RewriteTryReturnStmts(S->getTryBody());
Steve Naroffbf478ec2007-11-07 04:08:17 +00002073 }
2074 // Now emit the final closing curly brace...
2075 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002076 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00002077 return 0;
2078}
2079
Mike Stump11289f42009-09-09 15:08:12 +00002080// This can't be done with ReplaceStmt(S, ThrowExpr), since
2081// the throw expression is typically a message expression that's already
Steve Naroffa733c7f2007-11-07 15:32:26 +00002082// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002083Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroffa733c7f2007-11-07 15:32:26 +00002084 // Get the start location and compute the semi location.
2085 SourceLocation startLoc = S->getLocStart();
2086 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002087
Steve Naroffa733c7f2007-11-07 15:32:26 +00002088 assert((*startBuf == '@') && "bogus @throw location");
2089
2090 std::string buf;
2091 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffc7d2df22008-01-19 00:42:38 +00002092 if (S->getThrowExpr())
2093 buf = "objc_exception_throw(";
2094 else // add an implicit argument
2095 buf = "objc_exception_throw(_caught";
Mike Stump11289f42009-09-09 15:08:12 +00002096
Steve Naroff29788342008-07-25 15:41:30 +00002097 // handle "@ throw" correctly.
2098 const char *wBuf = strchr(startBuf, 'w');
2099 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002100 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00002101
Steve Naroffa733c7f2007-11-07 15:32:26 +00002102 const char *semiBuf = strchr(startBuf, ';');
2103 assert((*semiBuf == ';') && "@throw: can't find ';'");
2104 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002105 ReplaceText(semiLoc, 1, ");");
Steve Naroffa733c7f2007-11-07 15:32:26 +00002106 return 0;
2107}
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00002108
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002109Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerc6d91c02007-10-17 22:35:30 +00002110 // Create a new string expression.
2111 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlssond8499822007-10-29 05:01:08 +00002112 std::string StrEncoding;
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00002113 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002114 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
2115 StrEncoding.length(), false,StrType,
2116 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002117 ReplaceStmt(Exp, Replacement);
Mike Stump11289f42009-09-09 15:08:12 +00002118
Chris Lattner4431a1b2007-11-30 22:53:43 +00002119 // Replace this subexpr in the parent.
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002120 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattner69534692007-10-24 16:57:36 +00002121 return Replacement;
Chris Lattnera7c19fe2007-10-16 22:36:42 +00002122}
2123
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002124Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff2654e182008-12-22 22:16:07 +00002125 if (!SelGetUidFunctionDecl)
2126 SynthSelGetUidFunctionDecl();
Steve Naroffe4f9b232007-11-05 14:50:49 +00002127 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2128 // Create a call to sel_registerName("selName").
2129 llvm::SmallVector<Expr*, 8> SelExprs;
2130 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002131 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002132 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002133 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002134 false, argType, SourceLocation()));
Steve Naroffe4f9b232007-11-05 14:50:49 +00002135 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2136 &SelExprs[0], SelExprs.size());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002137 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002138 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffe4f9b232007-11-05 14:50:49 +00002139 return SelExp;
2140}
2141
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002142CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002143 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2144 SourceLocation EndLoc) {
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002145 // Get the type, we will need to reference it in a couple spots.
Steve Naroff574440f2007-10-24 22:48:43 +00002146 QualType msgSendType = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002147
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002148 // Create a reference to the objc_msgSend() declaration.
John McCall7decc9e2010-11-18 06:31:45 +00002149 DeclRefExpr *DRE =
2150 new (Context) DeclRefExpr(FD, msgSendType, VK_LValue, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002151
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002152 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattner3c799d72007-10-24 17:06:59 +00002153 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson975979382010-04-23 22:18:37 +00002154 ImplicitCastExpr *ICE =
John McCallf608deb2010-11-15 09:46:46 +00002155 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00002156 DRE, 0, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00002157
John McCall9dd450b2009-09-21 23:43:11 +00002158 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00002159
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002160 CallExpr *Exp =
Douglas Gregor603d81b2010-07-13 08:18:22 +00002161 new (Context) CallExpr(*Context, ICE, args, nargs,
John McCall7decc9e2010-11-18 06:31:45 +00002162 FT->getCallResultType(*Context),
2163 VK_RValue, EndLoc);
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002164 return Exp;
Steve Naroff574440f2007-10-24 22:48:43 +00002165}
2166
Steve Naroff50d42052007-11-01 13:24:47 +00002167static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2168 const char *&startRef, const char *&endRef) {
2169 while (startBuf < endBuf) {
2170 if (*startBuf == '<')
2171 startRef = startBuf; // mark the start.
2172 if (*startBuf == '>') {
Steve Naroff1b232132007-11-09 12:50:28 +00002173 if (startRef && *startRef == '<') {
2174 endRef = startBuf; // mark the end.
2175 return true;
2176 }
2177 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002178 }
2179 startBuf++;
2180 }
2181 return false;
2182}
2183
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002184static void scanToNextArgument(const char *&argRef) {
2185 int angle = 0;
2186 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2187 if (*argRef == '<')
2188 angle++;
2189 else if (*argRef == '>')
2190 angle--;
2191 argRef++;
2192 }
2193 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2194}
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002195
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002196bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian80c54b02010-02-03 21:29:28 +00002197 if (T->isObjCQualifiedIdType())
2198 return true;
Fariborz Jahanian06769f92010-02-02 18:35:07 +00002199 if (const PointerType *PT = T->getAs<PointerType>()) {
2200 if (PT->getPointeeType()->isObjCQualifiedIdType())
2201 return true;
2202 }
2203 if (T->isObjCObjectPointerType()) {
2204 T = T->getPointeeType();
2205 return T->isObjCQualifiedInterfaceType();
2206 }
Fariborz Jahanian7bf13c42010-09-30 20:41:32 +00002207 if (T->isArrayType()) {
2208 QualType ElemTy = Context->getBaseElementType(T);
2209 return needToScanForQualifiers(ElemTy);
2210 }
Fariborz Jahanian06769f92010-02-02 18:35:07 +00002211 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002212}
2213
Steve Naroff873bd842008-07-29 18:15:38 +00002214void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2215 QualType Type = E->getType();
2216 if (needToScanForQualifiers(Type)) {
Steve Naroffdbfc6932008-11-19 21:15:47 +00002217 SourceLocation Loc, EndLoc;
Mike Stump11289f42009-09-09 15:08:12 +00002218
Steve Naroffdbfc6932008-11-19 21:15:47 +00002219 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2220 Loc = ECE->getLParenLoc();
2221 EndLoc = ECE->getRParenLoc();
2222 } else {
2223 Loc = E->getLocStart();
2224 EndLoc = E->getLocEnd();
2225 }
2226 // This will defend against trying to rewrite synthesized expressions.
2227 if (Loc.isInvalid() || EndLoc.isInvalid())
2228 return;
2229
Steve Naroff873bd842008-07-29 18:15:38 +00002230 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffdbfc6932008-11-19 21:15:47 +00002231 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff873bd842008-07-29 18:15:38 +00002232 const char *startRef = 0, *endRef = 0;
2233 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2234 // Get the locations of the startRef, endRef.
2235 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2236 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2237 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002238 InsertText(LessLoc, "/*");
2239 InsertText(GreaterLoc, "*/");
Steve Naroff873bd842008-07-29 18:15:38 +00002240 }
2241 }
2242}
2243
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002244void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002245 SourceLocation Loc;
2246 QualType Type;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002247 const FunctionProtoType *proto = 0;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002248 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2249 Loc = VD->getLocation();
2250 Type = VD->getType();
2251 }
2252 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2253 Loc = FD->getLocation();
2254 // Check for ObjC 'id' and class types that have been adorned with protocol
2255 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall9dd450b2009-09-21 23:43:11 +00002256 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002257 assert(funcType && "missing function type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002258 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002259 if (!proto)
2260 return;
2261 Type = proto->getResultType();
2262 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00002263 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2264 Loc = FD->getLocation();
2265 Type = FD->getType();
2266 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002267 else
2268 return;
Mike Stump11289f42009-09-09 15:08:12 +00002269
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002270 if (needToScanForQualifiers(Type)) {
Steve Naroff50d42052007-11-01 13:24:47 +00002271 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002272
Steve Naroff50d42052007-11-01 13:24:47 +00002273 const char *endBuf = SM->getCharacterData(Loc);
2274 const char *startBuf = endBuf;
Steve Naroff930e0992008-05-31 05:02:17 +00002275 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroff50d42052007-11-01 13:24:47 +00002276 startBuf--; // scan backward (from the decl location) for return type.
2277 const char *startRef = 0, *endRef = 0;
2278 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2279 // Get the locations of the startRef, endRef.
2280 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2281 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2282 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002283 InsertText(LessLoc, "/*");
2284 InsertText(GreaterLoc, "*/");
Steve Naroff37e011c2007-10-31 04:38:33 +00002285 }
2286 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002287 if (!proto)
2288 return; // most likely, was a variable
Steve Naroff50d42052007-11-01 13:24:47 +00002289 // Now check arguments.
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002290 const char *startBuf = SM->getCharacterData(Loc);
2291 const char *startFuncBuf = startBuf;
Steve Naroff50d42052007-11-01 13:24:47 +00002292 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2293 if (needToScanForQualifiers(proto->getArgType(i))) {
2294 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002295
Steve Naroff50d42052007-11-01 13:24:47 +00002296 const char *endBuf = startBuf;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002297 // scan forward (from the decl location) for argument types.
2298 scanToNextArgument(endBuf);
Steve Naroff50d42052007-11-01 13:24:47 +00002299 const char *startRef = 0, *endRef = 0;
2300 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2301 // Get the locations of the startRef, endRef.
Mike Stump11289f42009-09-09 15:08:12 +00002302 SourceLocation LessLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002303 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump11289f42009-09-09 15:08:12 +00002304 SourceLocation GreaterLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002305 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002306 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002307 InsertText(LessLoc, "/*");
2308 InsertText(GreaterLoc, "*/");
Steve Naroff50d42052007-11-01 13:24:47 +00002309 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002310 startBuf = ++endBuf;
2311 }
2312 else {
Steve Naroffc884aa82008-08-06 15:58:23 +00002313 // If the function name is derived from a macro expansion, then the
2314 // argument buffer will not follow the name. Need to speak with Chris.
2315 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002316 startBuf++; // scan forward (from the decl location) for argument types.
2317 startBuf++;
2318 }
Steve Naroff50d42052007-11-01 13:24:47 +00002319 }
Steve Naroff37e011c2007-10-31 04:38:33 +00002320}
2321
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002322void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2323 QualType QT = ND->getType();
2324 const Type* TypePtr = QT->getAs<Type>();
2325 if (!isa<TypeOfExprType>(TypePtr))
2326 return;
2327 while (isa<TypeOfExprType>(TypePtr)) {
2328 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2329 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2330 TypePtr = QT->getAs<Type>();
2331 }
2332 // FIXME. This will not work for multiple declarators; as in:
2333 // __typeof__(a) b,c,d;
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002334 std::string TypeAsString(QT.getAsString(Context->PrintingPolicy));
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002335 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2336 const char *startBuf = SM->getCharacterData(DeclLoc);
2337 if (ND->getInit()) {
2338 std::string Name(ND->getNameAsString());
2339 TypeAsString += " " + Name + " = ";
2340 Expr *E = ND->getInit();
2341 SourceLocation startLoc;
2342 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2343 startLoc = ECE->getLParenLoc();
2344 else
2345 startLoc = E->getLocStart();
2346 startLoc = SM->getInstantiationLoc(startLoc);
2347 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002348 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002349 }
2350 else {
2351 SourceLocation X = ND->getLocEnd();
2352 X = SM->getInstantiationLoc(X);
2353 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002354 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002355 }
2356}
2357
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002358// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002359void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002360 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2361 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002362 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalldb40c7f2010-12-14 08:05:40 +00002363 QualType getFuncType =
2364 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002365 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002366 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002367 SelGetUidIdent, getFuncType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002368 SC_Extern,
2369 SC_None, false);
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002370}
2371
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002372void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002373 // declared in <objc/objc.h>
Douglas Gregor1e21c192009-01-09 01:47:02 +00002374 if (FD->getIdentifier() &&
Daniel Dunbar56df9772010-08-17 22:39:59 +00002375 FD->getName() == "sel_registerName") {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002376 SelGetUidFunctionDecl = FD;
Steve Naroff37e011c2007-10-31 04:38:33 +00002377 return;
2378 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002379 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002380}
2381
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002382void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2383 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002384 const char *argPtr = TypeString.c_str();
2385 if (!strchr(argPtr, '^')) {
2386 Str += TypeString;
2387 return;
2388 }
2389 while (*argPtr) {
2390 Str += (*argPtr == '^' ? '*' : *argPtr);
2391 argPtr++;
2392 }
2393}
2394
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002395// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002396void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2397 ValueDecl *VD) {
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002398 QualType Type = VD->getType();
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002399 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002400 const char *argPtr = TypeString.c_str();
2401 int paren = 0;
2402 while (*argPtr) {
2403 switch (*argPtr) {
2404 case '(':
2405 Str += *argPtr;
2406 paren++;
2407 break;
2408 case ')':
2409 Str += *argPtr;
2410 paren--;
2411 break;
2412 case '^':
2413 Str += '*';
2414 if (paren == 1)
2415 Str += VD->getNameAsString();
2416 break;
2417 default:
2418 Str += *argPtr;
2419 break;
2420 }
2421 argPtr++;
2422 }
2423}
2424
2425
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002426void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2427 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2428 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2429 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2430 if (!proto)
2431 return;
2432 QualType Type = proto->getResultType();
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002433 std::string FdStr = Type.getAsString(Context->PrintingPolicy);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002434 FdStr += " ";
Daniel Dunbar56df9772010-08-17 22:39:59 +00002435 FdStr += FD->getName();
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002436 FdStr += "(";
2437 unsigned numArgs = proto->getNumArgs();
2438 for (unsigned i = 0; i < numArgs; i++) {
2439 QualType ArgType = proto->getArgType(i);
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002440 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002441 if (i+1 < numArgs)
2442 FdStr += ", ";
2443 }
2444 FdStr += ");\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002445 InsertText(FunLocStart, FdStr);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002446 CurFunctionDeclToDeclareForBlock = 0;
2447}
2448
Steve Naroff17978c42008-03-11 17:37:02 +00002449// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002450void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroff17978c42008-03-11 17:37:02 +00002451 if (SuperContructorFunctionDecl)
2452 return;
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002453 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroff17978c42008-03-11 17:37:02 +00002454 llvm::SmallVector<QualType, 16> ArgTys;
2455 QualType argT = Context->getObjCIdType();
2456 assert(!argT.isNull() && "Can't find 'id' type");
2457 ArgTys.push_back(argT);
2458 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002459 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2460 &ArgTys[0], ArgTys.size());
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);
John McCalldb40c7f2010-12-14 08:05:40 +00002478 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2479 &ArgTys[0], ArgTys.size(),
2480 true /*isVariadic*/);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002481 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002482 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002483 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002484 SC_Extern,
2485 SC_None, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002486}
2487
Steve Naroff7fa2f042007-11-15 10:28:18 +00002488// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002489void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002490 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2491 llvm::SmallVector<QualType, 16> ArgTys;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002492 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002493 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002494 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002495 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2496 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2497 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002498 argT = Context->getObjCSelType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002499 assert(!argT.isNull() && "Can't find 'SEL' type");
2500 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002501 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2502 &ArgTys[0], ArgTys.size(),
2503 true /*isVariadic*/);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002504 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002505 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002506 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002507 SC_Extern,
2508 SC_None, false);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002509}
2510
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002511// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002512void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002513 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2514 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002515 QualType argT = Context->getObjCIdType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002516 assert(!argT.isNull() && "Can't find 'id' type");
2517 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002518 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002519 assert(!argT.isNull() && "Can't find 'SEL' type");
2520 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002521 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2522 &ArgTys[0], ArgTys.size(),
2523 true /*isVariadic*/);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002524 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002525 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002526 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002527 SC_Extern,
2528 SC_None, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002529}
2530
Mike Stump11289f42009-09-09 15:08:12 +00002531// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002532// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002533void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump11289f42009-09-09 15:08:12 +00002534 IdentifierInfo *msgSendIdent =
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002535 &Context->Idents.get("objc_msgSendSuper_stret");
2536 llvm::SmallVector<QualType, 16> ArgTys;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002537 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002538 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002539 &Context->Idents.get("objc_super"));
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002540 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2541 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2542 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002543 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002544 assert(!argT.isNull() && "Can't find 'SEL' type");
2545 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002546 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2547 &ArgTys[0], ArgTys.size(),
2548 true /*isVariadic*/);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002549 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002550 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002551 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002552 SC_Extern,
2553 SC_None, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002554}
2555
Steve Naroff2e4e3852008-05-08 22:02:18 +00002556// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002557void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002558 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2559 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002560 QualType argT = Context->getObjCIdType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002561 assert(!argT.isNull() && "Can't find 'id' type");
2562 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002563 argT = Context->getObjCSelType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002564 assert(!argT.isNull() && "Can't find 'SEL' type");
2565 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002566 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2567 &ArgTys[0], ArgTys.size(),
2568 true /*isVariadic*/);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002569 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002570 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002571 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002572 SC_Extern,
2573 SC_None, false);
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002574}
2575
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002576// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002577void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002578 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2579 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002580 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalldb40c7f2010-12-14 08:05:40 +00002581 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2582 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002583 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002584 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002585 getClassIdent, getClassType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002586 SC_Extern,
2587 SC_None, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002588}
2589
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002590// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2591void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2592 IdentifierInfo *getSuperClassIdent =
2593 &Context->Idents.get("class_getSuperclass");
2594 llvm::SmallVector<QualType, 16> ArgTys;
2595 ArgTys.push_back(Context->getObjCClassType());
John McCalldb40c7f2010-12-14 08:05:40 +00002596 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2597 &ArgTys[0], ArgTys.size());
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002598 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002599 SourceLocation(),
2600 getSuperClassIdent,
2601 getClassType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002602 SC_Extern,
2603 SC_None,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002604 false);
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002605}
2606
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002607// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002608void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002609 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2610 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002611 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalldb40c7f2010-12-14 08:05:40 +00002612 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2613 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002614 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002615 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002616 getClassIdent, getClassType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002617 SC_Extern,
2618 SC_None, false);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002619}
2620
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002621Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffce8e8862008-03-15 00:55:56 +00002622 QualType strType = getConstantStringStructType();
2623
2624 std::string S = "__NSConstantStringImpl_";
Steve Naroffa6141f02008-05-31 03:35:42 +00002625
2626 std::string tmpName = InFileName;
2627 unsigned i;
2628 for (i=0; i < tmpName.length(); i++) {
2629 char c = tmpName.at(i);
2630 // replace any non alphanumeric characters with '_'.
2631 if (!isalpha(c) && (c < '0' || c > '9'))
2632 tmpName[i] = '_';
2633 }
2634 S += tmpName;
2635 S += "_";
Steve Naroffce8e8862008-03-15 00:55:56 +00002636 S += utostr(NumObjCStringLiterals++);
2637
Steve Naroff00a31762008-03-27 22:29:16 +00002638 Preamble += "static __NSConstantStringImpl " + S;
2639 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2640 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffce8e8862008-03-15 00:55:56 +00002641 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek2d470fc2008-09-13 05:16:45 +00002642 std::string prettyBufS;
2643 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00002644 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2645 PrintingPolicy(LangOpts));
Steve Naroff00a31762008-03-27 22:29:16 +00002646 Preamble += prettyBuf.str();
2647 Preamble += ",";
Steve Naroff94ed6dc2009-12-06 01:48:44 +00002648 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002649
2650 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002651 &Context->Idents.get(S), strType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002652 SC_Static, SC_None);
John McCall7decc9e2010-11-18 06:31:45 +00002653 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, VK_LValue,
2654 SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00002655 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002656 Context->getPointerType(DRE->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002657 VK_RValue, OK_Ordinary,
2658 SourceLocation());
Steve Naroff265a6b92007-11-08 14:30:50 +00002659 // cast to NSConstantString *
John McCall97513962010-01-15 18:39:57 +00002660 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCallf608deb2010-11-15 09:46:46 +00002661 CK_BitCast, Unop);
Chris Lattner2e0d2602008-01-31 19:37:57 +00002662 ReplaceStmt(Exp, cast);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002663 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff265a6b92007-11-08 14:30:50 +00002664 return cast;
Steve Naroffa397efd2007-11-03 11:27:19 +00002665}
2666
Steve Naroff7fa2f042007-11-15 10:28:18 +00002667// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002668QualType RewriteObjC::getSuperStructType() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002669 if (!SuperStructDecl) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00002670 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002671 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002672 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002673 QualType FieldTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002674
Steve Naroff7fa2f042007-11-15 10:28:18 +00002675 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002676 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002677 // struct objc_class *super;
Mike Stump11289f42009-09-09 15:08:12 +00002678 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor91f84212008-12-11 16:49:14 +00002679
Steve Naroff7fa2f042007-11-15 10:28:18 +00002680 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002681 for (unsigned i = 0; i < 2; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002682 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2683 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002684 FieldTypes[i], 0,
2685 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002686 /*Mutable=*/false));
Douglas Gregor91f84212008-12-11 16:49:14 +00002687 }
Mike Stump11289f42009-09-09 15:08:12 +00002688
Douglas Gregord5058122010-02-11 01:19:42 +00002689 SuperStructDecl->completeDefinition();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002690 }
2691 return Context->getTagDeclType(SuperStructDecl);
2692}
2693
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002694QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffce8e8862008-03-15 00:55:56 +00002695 if (!ConstantStringDecl) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00002696 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002697 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002698 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffce8e8862008-03-15 00:55:56 +00002699 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002700
Steve Naroffce8e8862008-03-15 00:55:56 +00002701 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002702 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffce8e8862008-03-15 00:55:56 +00002703 // int flags;
Mike Stump11289f42009-09-09 15:08:12 +00002704 FieldTypes[1] = Context->IntTy;
Steve Naroffce8e8862008-03-15 00:55:56 +00002705 // char *str;
Mike Stump11289f42009-09-09 15:08:12 +00002706 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffce8e8862008-03-15 00:55:56 +00002707 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002708 FieldTypes[3] = Context->LongTy;
Douglas Gregor91f84212008-12-11 16:49:14 +00002709
Steve Naroffce8e8862008-03-15 00:55:56 +00002710 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002711 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002712 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2713 ConstantStringDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002714 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002715 FieldTypes[i], 0,
Douglas Gregor91f84212008-12-11 16:49:14 +00002716 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002717 /*Mutable=*/true));
Douglas Gregor91f84212008-12-11 16:49:14 +00002718 }
2719
Douglas Gregord5058122010-02-11 01:19:42 +00002720 ConstantStringDecl->completeDefinition();
Steve Naroffce8e8862008-03-15 00:55:56 +00002721 }
2722 return Context->getTagDeclType(ConstantStringDecl);
2723}
2724
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002725Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2726 SourceLocation StartLoc,
2727 SourceLocation EndLoc) {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002728 if (!SelGetUidFunctionDecl)
2729 SynthSelGetUidFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002730 if (!MsgSendFunctionDecl)
2731 SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002732 if (!MsgSendSuperFunctionDecl)
2733 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002734 if (!MsgSendStretFunctionDecl)
2735 SynthMsgSendStretFunctionDecl();
2736 if (!MsgSendSuperStretFunctionDecl)
2737 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002738 if (!MsgSendFpretFunctionDecl)
2739 SynthMsgSendFpretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002740 if (!GetClassFunctionDecl)
2741 SynthGetClassFunctionDecl();
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002742 if (!GetSuperClassFunctionDecl)
2743 SynthGetSuperClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002744 if (!GetMetaClassFunctionDecl)
2745 SynthGetMetaClassFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002746
Steve Naroff7fa2f042007-11-15 10:28:18 +00002747 // default to objc_msgSend().
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002748 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2749 // May need to use objc_msgSend_stret() as well.
2750 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroffd9803712009-04-29 16:37:50 +00002751 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2752 QualType resultType = mDecl->getResultType();
Douglas Gregor8385a062010-04-26 21:31:17 +00002753 if (resultType->isRecordType())
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002754 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002755 else if (resultType->isRealFloatingType())
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002756 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002757 }
Mike Stump11289f42009-09-09 15:08:12 +00002758
Steve Naroff574440f2007-10-24 22:48:43 +00002759 // Synthesize a call to objc_msgSend().
2760 llvm::SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor9a129192010-04-21 00:45:42 +00002761 switch (Exp->getReceiverKind()) {
2762 case ObjCMessageExpr::SuperClass: {
2763 MsgSendFlavor = MsgSendSuperFunctionDecl;
2764 if (MsgSendStretFlavor)
2765 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2766 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002767
Douglas Gregor9a129192010-04-21 00:45:42 +00002768 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00002769
Douglas Gregor9a129192010-04-21 00:45:42 +00002770 llvm::SmallVector<Expr*, 4> InitExprs;
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002771
Douglas Gregor9a129192010-04-21 00:45:42 +00002772 // set the receiver to self, the first argument to all methods.
2773 InitExprs.push_back(
2774 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002775 CK_BitCast,
Douglas Gregor9a129192010-04-21 00:45:42 +00002776 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall7decc9e2010-11-18 06:31:45 +00002777 Context->getObjCIdType(),
2778 VK_RValue,
2779 SourceLocation()))
Douglas Gregor9a129192010-04-21 00:45:42 +00002780 ); // set the 'receiver'.
Mike Stump11289f42009-09-09 15:08:12 +00002781
Douglas Gregor9a129192010-04-21 00:45:42 +00002782 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2783 llvm::SmallVector<Expr*, 8> ClsExprs;
2784 QualType argType = Context->getPointerType(Context->CharTy);
2785 ClsExprs.push_back(StringLiteral::Create(*Context,
2786 ClassDecl->getIdentifier()->getNameStart(),
2787 ClassDecl->getIdentifier()->getLength(),
2788 false, argType, SourceLocation()));
2789 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2790 &ClsExprs[0],
2791 ClsExprs.size(),
2792 StartLoc,
2793 EndLoc);
2794 // (Class)objc_getClass("CurrentClass")
2795 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2796 Context->getObjCClassType(),
John McCallf608deb2010-11-15 09:46:46 +00002797 CK_BitCast, Cls);
Douglas Gregor9a129192010-04-21 00:45:42 +00002798 ClsExprs.clear();
2799 ClsExprs.push_back(ArgExpr);
2800 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2801 &ClsExprs[0], ClsExprs.size(),
2802 StartLoc, EndLoc);
2803
2804 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2805 // To turn off a warning, type-cast to 'id'
2806 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2807 NoTypeInfoCStyleCastExpr(Context,
2808 Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002809 CK_BitCast, Cls));
Douglas Gregor9a129192010-04-21 00:45:42 +00002810 // struct objc_super
2811 QualType superType = getSuperStructType();
2812 Expr *SuperRep;
Steve Naroffd9803712009-04-29 16:37:50 +00002813
Douglas Gregor9a129192010-04-21 00:45:42 +00002814 if (LangOpts.Microsoft) {
2815 SynthSuperContructorFunctionDecl();
2816 // Simulate a contructor call...
2817 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCall7decc9e2010-11-18 06:31:45 +00002818 superType, VK_LValue,
2819 SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002820 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2821 InitExprs.size(),
John McCall7decc9e2010-11-18 06:31:45 +00002822 superType, VK_LValue,
2823 SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002824 // The code for super is a little tricky to prevent collision with
2825 // the structure definition in the header. The rewriter has it's own
2826 // internal definition (__rw_objc_super) that is uses. This is why
2827 // we need the cast below. For example:
2828 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2829 //
John McCalle3027922010-08-25 11:45:40 +00002830 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002831 Context->getPointerType(SuperRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002832 VK_RValue, OK_Ordinary,
2833 SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002834 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2835 Context->getPointerType(superType),
John McCallf608deb2010-11-15 09:46:46 +00002836 CK_BitCast, SuperRep);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002837 } else {
Douglas Gregor9a129192010-04-21 00:45:42 +00002838 // (struct objc_super) { <exprs from above> }
2839 InitListExpr *ILE =
2840 new (Context) InitListExpr(*Context, SourceLocation(),
2841 &InitExprs[0], InitExprs.size(),
2842 SourceLocation());
2843 TypeSourceInfo *superTInfo
2844 = Context->getTrivialTypeSourceInfo(superType);
2845 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCall7decc9e2010-11-18 06:31:45 +00002846 superType, VK_LValue,
2847 ILE, false);
Douglas Gregor9a129192010-04-21 00:45:42 +00002848 // struct objc_super *
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());
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002853 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002854 MsgExprs.push_back(SuperRep);
2855 break;
Steve Naroffe7f18192007-11-14 23:54:14 +00002856 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002857
2858 case ObjCMessageExpr::Class: {
2859 llvm::SmallVector<Expr*, 8> ClsExprs;
2860 QualType argType = Context->getPointerType(Context->CharTy);
2861 ObjCInterfaceDecl *Class
John McCall96fa4842010-05-17 21:00:27 +00002862 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor9a129192010-04-21 00:45:42 +00002863 IdentifierInfo *clsName = Class->getIdentifier();
2864 ClsExprs.push_back(StringLiteral::Create(*Context,
2865 clsName->getNameStart(),
2866 clsName->getLength(),
2867 false, argType,
2868 SourceLocation()));
2869 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2870 &ClsExprs[0],
2871 ClsExprs.size(),
2872 StartLoc, EndLoc);
2873 MsgExprs.push_back(Cls);
2874 break;
2875 }
2876
2877 case ObjCMessageExpr::SuperInstance:{
2878 MsgSendFlavor = MsgSendSuperFunctionDecl;
2879 if (MsgSendStretFlavor)
2880 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2881 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2882 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2883 llvm::SmallVector<Expr*, 4> InitExprs;
2884
2885 InitExprs.push_back(
2886 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002887 CK_BitCast,
Douglas Gregor9a129192010-04-21 00:45:42 +00002888 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall7decc9e2010-11-18 06:31:45 +00002889 Context->getObjCIdType(),
2890 VK_RValue, SourceLocation()))
Douglas Gregor9a129192010-04-21 00:45:42 +00002891 ); // set the 'receiver'.
2892
2893 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2894 llvm::SmallVector<Expr*, 8> ClsExprs;
2895 QualType argType = Context->getPointerType(Context->CharTy);
2896 ClsExprs.push_back(StringLiteral::Create(*Context,
2897 ClassDecl->getIdentifier()->getNameStart(),
2898 ClassDecl->getIdentifier()->getLength(),
2899 false, argType, SourceLocation()));
2900 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2901 &ClsExprs[0],
2902 ClsExprs.size(),
2903 StartLoc, EndLoc);
2904 // (Class)objc_getClass("CurrentClass")
2905 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2906 Context->getObjCClassType(),
John McCallf608deb2010-11-15 09:46:46 +00002907 CK_BitCast, Cls);
Douglas Gregor9a129192010-04-21 00:45:42 +00002908 ClsExprs.clear();
2909 ClsExprs.push_back(ArgExpr);
2910 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2911 &ClsExprs[0], ClsExprs.size(),
2912 StartLoc, EndLoc);
2913
2914 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2915 // To turn off a warning, type-cast to 'id'
2916 InitExprs.push_back(
2917 // set 'super class', using class_getSuperclass().
2918 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002919 CK_BitCast, Cls));
Douglas Gregor9a129192010-04-21 00:45:42 +00002920 // struct objc_super
2921 QualType superType = getSuperStructType();
2922 Expr *SuperRep;
2923
2924 if (LangOpts.Microsoft) {
2925 SynthSuperContructorFunctionDecl();
2926 // Simulate a contructor call...
2927 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCall7decc9e2010-11-18 06:31:45 +00002928 superType, VK_LValue,
2929 SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002930 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2931 InitExprs.size(),
John McCall7decc9e2010-11-18 06:31:45 +00002932 superType, VK_LValue, SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002933 // The code for super is a little tricky to prevent collision with
2934 // the structure definition in the header. The rewriter has it's own
2935 // internal definition (__rw_objc_super) that is uses. This is why
2936 // we need the cast below. For example:
2937 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2938 //
John McCalle3027922010-08-25 11:45:40 +00002939 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002940 Context->getPointerType(SuperRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002941 VK_RValue, OK_Ordinary,
Douglas Gregor9a129192010-04-21 00:45:42 +00002942 SourceLocation());
2943 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2944 Context->getPointerType(superType),
John McCallf608deb2010-11-15 09:46:46 +00002945 CK_BitCast, SuperRep);
Douglas Gregor9a129192010-04-21 00:45:42 +00002946 } else {
2947 // (struct objc_super) { <exprs from above> }
2948 InitListExpr *ILE =
2949 new (Context) InitListExpr(*Context, SourceLocation(),
2950 &InitExprs[0], InitExprs.size(),
2951 SourceLocation());
2952 TypeSourceInfo *superTInfo
2953 = Context->getTrivialTypeSourceInfo(superType);
2954 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCall7decc9e2010-11-18 06:31:45 +00002955 superType, VK_RValue, ILE,
2956 false);
Douglas Gregor9a129192010-04-21 00:45:42 +00002957 }
2958 MsgExprs.push_back(SuperRep);
2959 break;
2960 }
2961
2962 case ObjCMessageExpr::Instance: {
2963 // Remove all type-casts because it may contain objc-style types; e.g.
2964 // Foo<Proto> *.
2965 Expr *recExpr = Exp->getInstanceReceiver();
2966 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2967 recExpr = CE->getSubExpr();
2968 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002969 CK_BitCast, recExpr);
Douglas Gregor9a129192010-04-21 00:45:42 +00002970 MsgExprs.push_back(recExpr);
2971 break;
2972 }
2973 }
2974
Steve Naroffa397efd2007-11-03 11:27:19 +00002975 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff574440f2007-10-24 22:48:43 +00002976 llvm::SmallVector<Expr*, 8> SelExprs;
2977 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002978 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002979 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002980 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002981 false, argType, SourceLocation()));
Steve Naroff574440f2007-10-24 22:48:43 +00002982 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002983 &SelExprs[0], SelExprs.size(),
2984 StartLoc,
2985 EndLoc);
Steve Naroff574440f2007-10-24 22:48:43 +00002986 MsgExprs.push_back(SelExp);
Mike Stump11289f42009-09-09 15:08:12 +00002987
Steve Naroff574440f2007-10-24 22:48:43 +00002988 // Now push any user supplied arguments.
2989 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroffe7f18192007-11-14 23:54:14 +00002990 Expr *userExpr = Exp->getArg(i);
Steve Narofff60782b2007-11-15 02:58:25 +00002991 // Make all implicit casts explicit...ICE comes in handy:-)
2992 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2993 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregore200adc2008-10-27 19:41:14 +00002994 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002995 ? Context->getObjCIdType()
Douglas Gregore200adc2008-10-27 19:41:14 +00002996 : ICE->getType();
Fariborz Jahanian19c62402010-05-25 15:56:08 +00002997 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00002998 (void)convertBlockPointerToFunctionPointer(type);
John McCallf608deb2010-11-15 09:46:46 +00002999 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00003000 userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00003001 }
3002 // Make id<P...> cast into an 'id' cast.
Douglas Gregorf19b2312008-10-28 15:36:24 +00003003 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003004 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregorf19b2312008-10-28 15:36:24 +00003005 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00003006 userExpr = CE->getSubExpr();
John McCall97513962010-01-15 18:39:57 +00003007 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00003008 CK_BitCast, userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00003009 }
Mike Stump11289f42009-09-09 15:08:12 +00003010 }
Steve Naroffe7f18192007-11-14 23:54:14 +00003011 MsgExprs.push_back(userExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00003012 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3013 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003014 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00003015 //Exp->setArg(i, 0);
Steve Naroff574440f2007-10-24 22:48:43 +00003016 }
Steve Narofff36987c2007-11-04 22:37:50 +00003017 // Generate the funky cast.
3018 CastExpr *cast;
3019 llvm::SmallVector<QualType, 8> ArgTypes;
3020 QualType returnType;
Mike Stump11289f42009-09-09 15:08:12 +00003021
Steve Narofff36987c2007-11-04 22:37:50 +00003022 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff44864e42007-11-15 10:43:57 +00003023 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3024 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3025 else
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003026 ArgTypes.push_back(Context->getObjCIdType());
3027 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattnera4997152009-02-20 18:43:26 +00003028 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Narofff36987c2007-11-04 22:37:50 +00003029 // Push any user argument types.
Chris Lattnera4997152009-02-20 18:43:26 +00003030 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3031 E = OMD->param_end(); PI != E; ++PI) {
3032 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump11289f42009-09-09 15:08:12 +00003033 ? Context->getObjCIdType()
Chris Lattnera4997152009-02-20 18:43:26 +00003034 : (*PI)->getType();
Steve Naroff52c65fa2008-10-29 14:49:46 +00003035 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00003036 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff98eb8d12007-11-05 14:36:37 +00003037 ArgTypes.push_back(t);
3038 }
Chris Lattnera4997152009-02-20 18:43:26 +00003039 returnType = OMD->getResultType()->isObjCQualifiedIdType()
3040 ? Context->getObjCIdType() : OMD->getResultType();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00003041 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Narofff36987c2007-11-04 22:37:50 +00003042 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003043 returnType = Context->getObjCIdType();
Steve Narofff36987c2007-11-04 22:37:50 +00003044 }
3045 // Get the type, we will need to reference it in a couple spots.
Steve Naroff7fa2f042007-11-15 10:28:18 +00003046 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003047
Steve Narofff36987c2007-11-04 22:37:50 +00003048 // Create a reference to the objc_msgSend() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003049 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
John McCall7decc9e2010-11-18 06:31:45 +00003050 VK_LValue, SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00003051
Mike Stump11289f42009-09-09 15:08:12 +00003052 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Narofff36987c2007-11-04 22:37:50 +00003053 // If we don't do this cast, we get the following bizarre warning/note:
3054 // xx.m:13: warning: function called through a non-compatible type
3055 // xx.m:13: note: if this code is reached, the program will abort
John McCall97513962010-01-15 18:39:57 +00003056 cast = NoTypeInfoCStyleCastExpr(Context,
3057 Context->getPointerType(Context->VoidTy),
John McCallf608deb2010-11-15 09:46:46 +00003058 CK_BitCast, DRE);
Mike Stump11289f42009-09-09 15:08:12 +00003059
Steve Narofff36987c2007-11-04 22:37:50 +00003060 // Now do the "normal" pointer to function cast.
John McCalldb40c7f2010-12-14 08:05:40 +00003061 QualType castType =
3062 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3063 // If we don't have a method decl, force a variadic cast.
3064 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Narofff36987c2007-11-04 22:37:50 +00003065 castType = Context->getPointerType(castType);
John McCallf608deb2010-11-15 09:46:46 +00003066 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00003067 cast);
Steve Narofff36987c2007-11-04 22:37:50 +00003068
3069 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00003070 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump11289f42009-09-09 15:08:12 +00003071
John McCall9dd450b2009-09-21 23:43:11 +00003072 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003073 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00003074 MsgExprs.size(),
John McCall7decc9e2010-11-18 06:31:45 +00003075 FT->getResultType(), VK_RValue,
3076 EndLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003077 Stmt *ReplacingStmt = CE;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003078 if (MsgSendStretFlavor) {
3079 // We have the method which returns a struct/union. Must also generate
3080 // call to objc_msgSend_stret and hang both varieties on a conditional
3081 // expression which dictate which one to envoke depending on size of
3082 // method's return type.
Mike Stump11289f42009-09-09 15:08:12 +00003083
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003084 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003085 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
John McCall7decc9e2010-11-18 06:31:45 +00003086 VK_LValue, SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003087 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall97513962010-01-15 18:39:57 +00003088 cast = NoTypeInfoCStyleCastExpr(Context,
3089 Context->getPointerType(Context->VoidTy),
John McCallf608deb2010-11-15 09:46:46 +00003090 CK_BitCast, STDRE);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003091 // Now do the "normal" pointer to function cast.
John McCalldb40c7f2010-12-14 08:05:40 +00003092 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3093 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003094 castType = Context->getPointerType(castType);
John McCallf608deb2010-11-15 09:46:46 +00003095 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00003096 cast);
Mike Stump11289f42009-09-09 15:08:12 +00003097
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003098 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00003099 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00003100
John McCall9dd450b2009-09-21 23:43:11 +00003101 FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003102 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00003103 MsgExprs.size(),
John McCall7decc9e2010-11-18 06:31:45 +00003104 FT->getResultType(), VK_RValue,
3105 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00003106
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003107 // Build sizeof(returnType)
Mike Stump11289f42009-09-09 15:08:12 +00003108 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCallbcd03502009-12-07 02:54:59 +00003109 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl6f282892008-11-11 17:56:53 +00003110 Context->getSizeType(),
3111 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003112 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3113 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3114 // For X86 it is more complicated and some kind of target specific routine
3115 // is needed to decide what to do.
Mike Stump11289f42009-09-09 15:08:12 +00003116 unsigned IntSize =
Chris Lattner37e05872008-03-05 18:54:05 +00003117 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00003118 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3119 llvm::APInt(IntSize, 8),
3120 Context->IntTy,
3121 SourceLocation());
John McCall7decc9e2010-11-18 06:31:45 +00003122 BinaryOperator *lessThanExpr =
3123 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3124 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003125 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump11289f42009-09-09 15:08:12 +00003126 ConditionalOperator *CondExpr =
Douglas Gregor7e112b02009-08-26 14:37:04 +00003127 new (Context) ConditionalOperator(lessThanExpr,
3128 SourceLocation(), CE,
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00003129 SourceLocation(), STCE, (Expr*)0,
John McCall4bc41ae2010-11-18 19:01:18 +00003130 returnType, VK_RValue, OK_Ordinary);
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00003131 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3132 CondExpr);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003133 }
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003134 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003135 return ReplacingStmt;
3136}
3137
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003138Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00003139 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3140 Exp->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003141
Steve Naroff574440f2007-10-24 22:48:43 +00003142 // Now do the actual rewrite.
Chris Lattner2e0d2602008-01-31 19:37:57 +00003143 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00003144
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003145 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003146 return ReplacingStmt;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00003147}
3148
Steve Naroffd9803712009-04-29 16:37:50 +00003149// typedef struct objc_object Protocol;
3150QualType RewriteObjC::getProtocolType() {
3151 if (!ProtocolTypeDecl) {
John McCallbcd03502009-12-07 02:54:59 +00003152 TypeSourceInfo *TInfo
3153 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroffd9803712009-04-29 16:37:50 +00003154 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00003155 SourceLocation(),
Steve Naroffd9803712009-04-29 16:37:50 +00003156 &Context->Idents.get("Protocol"),
John McCallbcd03502009-12-07 02:54:59 +00003157 TInfo);
Steve Naroffd9803712009-04-29 16:37:50 +00003158 }
3159 return Context->getTypeDeclType(ProtocolTypeDecl);
3160}
3161
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00003162/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroffd9803712009-04-29 16:37:50 +00003163/// a synthesized/forward data reference (to the protocol's metadata).
3164/// The forward references (and metadata) are generated in
3165/// RewriteObjC::HandleTranslationUnit().
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003166Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroffd9803712009-04-29 16:37:50 +00003167 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3168 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump11289f42009-09-09 15:08:12 +00003169 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00003170 ID, getProtocolType(), 0,
John McCall8e7d6562010-08-26 03:08:43 +00003171 SC_Extern, SC_None);
John McCall7decc9e2010-11-18 06:31:45 +00003172 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), VK_LValue,
3173 SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00003174 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroffd9803712009-04-29 16:37:50 +00003175 Context->getPointerType(DRE->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00003176 VK_RValue, OK_Ordinary, SourceLocation());
John McCall97513962010-01-15 18:39:57 +00003177 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCallf608deb2010-11-15 09:46:46 +00003178 CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00003179 DerefExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00003180 ReplaceStmt(Exp, castExpr);
3181 ProtocolExprDecls.insert(Exp->getProtocol());
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003182 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00003183 return castExpr;
Mike Stump11289f42009-09-09 15:08:12 +00003184
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00003185}
3186
Mike Stump11289f42009-09-09 15:08:12 +00003187bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003188 const char *endBuf) {
3189 while (startBuf < endBuf) {
3190 if (*startBuf == '#') {
3191 // Skip whitespace.
3192 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3193 ;
3194 if (!strncmp(startBuf, "if", strlen("if")) ||
3195 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3196 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3197 !strncmp(startBuf, "define", strlen("define")) ||
3198 !strncmp(startBuf, "undef", strlen("undef")) ||
3199 !strncmp(startBuf, "else", strlen("else")) ||
3200 !strncmp(startBuf, "elif", strlen("elif")) ||
3201 !strncmp(startBuf, "endif", strlen("endif")) ||
3202 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3203 !strncmp(startBuf, "include", strlen("include")) ||
3204 !strncmp(startBuf, "import", strlen("import")) ||
3205 !strncmp(startBuf, "include_next", strlen("include_next")))
3206 return true;
3207 }
3208 startBuf++;
3209 }
3210 return false;
3211}
3212
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003213/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003214/// an objective-c class with ivars.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003215void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003216 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003217 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar56df9772010-08-17 22:39:59 +00003218 assert(CDecl->getName() != "" &&
Douglas Gregor77324f32008-11-17 14:58:09 +00003219 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00003220 // Do not synthesize more than once.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003221 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00003222 return;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003223 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003224 int NumIvars = CDecl->ivar_size();
Steve Naroffdde78982007-11-14 19:25:57 +00003225 SourceLocation LocStart = CDecl->getLocStart();
3226 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00003227
Steve Naroffdde78982007-11-14 19:25:57 +00003228 const char *startBuf = SM->getCharacterData(LocStart);
3229 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00003230
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003231 // If no ivars and no root or if its root, directly or indirectly,
3232 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003233 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3234 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner184e65d2009-04-14 23:22:57 +00003235 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003236 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003237 return;
3238 }
Mike Stump11289f42009-09-09 15:08:12 +00003239
3240 // FIXME: This has potential of causing problem. If
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003241 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003242 Result += "\nstruct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003243 Result += CDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00003244 if (LangOpts.Microsoft)
3245 Result += "_IMPL";
Steve Naroffdc5b6b22008-03-12 00:25:36 +00003246
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003247 if (NumIvars > 0) {
Steve Naroffdde78982007-11-14 19:25:57 +00003248 const char *cursor = strchr(startBuf, '{');
Mike Stump11289f42009-09-09 15:08:12 +00003249 assert((cursor && endBuf)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003250 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003251 // If the buffer contains preprocessor directives, we do more fine-grained
3252 // rewrites. This is intended to fix code that looks like (which occurs in
3253 // NSURL.h, for example):
3254 //
3255 // #ifdef XYZ
3256 // @interface Foo : NSObject
3257 // #else
3258 // @interface FooBar : NSObject
3259 // #endif
3260 // {
3261 // int i;
3262 // }
3263 // @end
3264 //
3265 // This clause is segregated to avoid breaking the common case.
3266 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump11289f42009-09-09 15:08:12 +00003267 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003268 CDecl->getClassLoc();
3269 const char *endHeader = SM->getCharacterData(L);
Chris Lattner184e65d2009-04-14 23:22:57 +00003270 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003271
Chris Lattnerf5b77512009-02-20 18:18:36 +00003272 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003273 // advance to the end of the referenced protocols.
3274 while (endHeader < cursor && *endHeader != '>') endHeader++;
3275 endHeader++;
3276 }
3277 // rewrite the original header
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003278 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003279 } else {
3280 // rewrite the original header *without* disturbing the '{'
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003281 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003282 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003283 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroffdde78982007-11-14 19:25:57 +00003284 Result = "\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003285 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003286 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003287 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003288 Result += "_IVARS;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003289
Steve Naroffdde78982007-11-14 19:25:57 +00003290 // insert the super class structure definition.
Chris Lattner1780a852008-01-31 19:42:41 +00003291 SourceLocation OnePastCurly =
3292 LocStart.getFileLocWithOffset(cursor-startBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003293 InsertText(OnePastCurly, Result);
Steve Naroffdde78982007-11-14 19:25:57 +00003294 }
3295 cursor++; // past '{'
Mike Stump11289f42009-09-09 15:08:12 +00003296
Steve Naroffdde78982007-11-14 19:25:57 +00003297 // Now comment out any visibility specifiers.
3298 while (cursor < endBuf) {
3299 if (*cursor == '@') {
3300 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner174a8252007-11-14 22:57:51 +00003301 // Skip whitespace.
3302 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3303 /*scan*/;
3304
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003305 // FIXME: presence of @public, etc. inside comment results in
3306 // this transformation as well, which is still correct c-code.
Steve Naroffdde78982007-11-14 19:25:57 +00003307 if (!strncmp(cursor, "public", strlen("public")) ||
3308 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffaf91b9a2008-04-04 22:34:24 +00003309 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003310 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003311 InsertText(atLoc, "// ");
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003312 }
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003313 // FIXME: If there are cases where '<' is used in ivar declaration part
3314 // of user code, then scan the ivar list and use needToScanForQualifiers
3315 // for type checking.
3316 else if (*cursor == '<') {
3317 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003318 InsertText(atLoc, "/* ");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003319 cursor = strchr(cursor, '>');
3320 cursor++;
3321 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003322 InsertText(atLoc, " */");
Steve Naroff295570a2008-10-30 12:09:33 +00003323 } else if (*cursor == '^') { // rewrite block specifier.
3324 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003325 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003326 }
Steve Naroffdde78982007-11-14 19:25:57 +00003327 cursor++;
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003328 }
Steve Naroffdde78982007-11-14 19:25:57 +00003329 // Don't forget to add a ';'!!
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003330 InsertText(LocEnd.getFileLocWithOffset(1), ";");
Steve Naroffdde78982007-11-14 19:25:57 +00003331 } else { // we don't have any instance variables - insert super struct.
Chris Lattner184e65d2009-04-14 23:22:57 +00003332 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroffdde78982007-11-14 19:25:57 +00003333 Result += " {\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003334 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003335 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003336 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003337 Result += "_IVARS;\n};\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003338 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003339 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003340 // Mark this struct as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003341 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff13e74872008-05-06 18:26:51 +00003342 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003343}
3344
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003345// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003346/// class methods.
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003347template<typename MethodIterator>
3348void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3349 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +00003350 bool IsInstanceMethod,
Daniel Dunbar56df9772010-08-17 22:39:59 +00003351 llvm::StringRef prefix,
3352 llvm::StringRef ClassName,
Chris Lattner211f8b82007-10-25 17:07:24 +00003353 std::string &Result) {
Chris Lattner31bc07e2007-12-12 07:46:12 +00003354 if (MethodBegin == MethodEnd) return;
Mike Stump11289f42009-09-09 15:08:12 +00003355
Chris Lattner31bc07e2007-12-12 07:46:12 +00003356 if (!objc_impl_method) {
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003357 /* struct _objc_method {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003358 SEL _cmd;
3359 char *method_types;
3360 void *_imp;
3361 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003362 */
Chris Lattner211f8b82007-10-25 17:07:24 +00003363 Result += "\nstruct _objc_method {\n";
3364 Result += "\tSEL _cmd;\n";
3365 Result += "\tchar *method_types;\n";
3366 Result += "\tvoid *_imp;\n";
3367 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003368
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003369 objc_impl_method = true;
Fariborz Jahanian74a1cfa2007-10-19 00:36:46 +00003370 }
Mike Stump11289f42009-09-09 15:08:12 +00003371
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003372 // Build _objc_method_list for class's methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003373
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003374 /* struct {
3375 struct _objc_method_list *next_method;
3376 int method_count;
3377 struct _objc_method method_list[];
3378 }
3379 */
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003380 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003381 Result += "\nstatic struct {\n";
3382 Result += "\tstruct _objc_method_list *next_method;\n";
3383 Result += "\tint method_count;\n";
3384 Result += "\tstruct _objc_method method_list[";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003385 Result += utostr(NumMethods);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003386 Result += "];\n} _OBJC_";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003387 Result += prefix;
3388 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3389 Result += "_METHODS_";
3390 Result += ClassName;
Steve Naroffb327e492008-03-12 17:18:30 +00003391 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003392 Result += IsInstanceMethod ? "inst" : "cls";
3393 Result += "_meth\")))= ";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003394 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003395
Chris Lattner31bc07e2007-12-12 07:46:12 +00003396 Result += "\t,{{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003397 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattner31bc07e2007-12-12 07:46:12 +00003398 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003399 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattner31bc07e2007-12-12 07:46:12 +00003400 Result += "\", \"";
3401 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003402 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003403 Result += MethodInternalNames[*MethodBegin];
3404 Result += "}\n";
3405 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3406 Result += "\t ,{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003407 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003408 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003409 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003410 Result += "\", \"";
3411 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003412 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003413 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanian56338352007-11-13 21:02:00 +00003414 Result += "}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003415 }
Chris Lattner31bc07e2007-12-12 07:46:12 +00003416 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003417}
3418
Steve Naroffd9803712009-04-29 16:37:50 +00003419/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner390d39a2008-07-21 21:32:27 +00003420void RewriteObjC::
Daniel Dunbar56df9772010-08-17 22:39:59 +00003421RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, llvm::StringRef prefix,
3422 llvm::StringRef ClassName, std::string &Result) {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003423 static bool objc_protocol_methods = false;
Steve Naroffd9803712009-04-29 16:37:50 +00003424
3425 // Output struct protocol_methods holder of method selector and type.
3426 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3427 /* struct protocol_methods {
3428 SEL _cmd;
3429 char *method_types;
3430 }
3431 */
3432 Result += "\nstruct _protocol_methods {\n";
3433 Result += "\tstruct objc_selector *_cmd;\n";
3434 Result += "\tchar *method_types;\n";
3435 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003436
Steve Naroffd9803712009-04-29 16:37:50 +00003437 objc_protocol_methods = true;
3438 }
3439 // Do not synthesize the protocol more than once.
3440 if (ObjCSynthesizedProtocols.count(PDecl))
3441 return;
Mike Stump11289f42009-09-09 15:08:12 +00003442
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003443 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3444 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3445 PDecl->instmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003446 /* struct _objc_protocol_method_list {
3447 int protocol_method_count;
3448 struct protocol_methods protocols[];
3449 }
Steve Naroff251084d2008-03-12 01:06:30 +00003450 */
Steve Naroffd9803712009-04-29 16:37:50 +00003451 Result += "\nstatic struct {\n";
3452 Result += "\tint protocol_method_count;\n";
3453 Result += "\tstruct _protocol_methods protocol_methods[";
3454 Result += utostr(NumMethods);
3455 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3456 Result += PDecl->getNameAsString();
3457 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3458 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003459
Steve Naroffd9803712009-04-29 16:37:50 +00003460 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003461 for (ObjCProtocolDecl::instmeth_iterator
3462 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003463 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003464 if (I == PDecl->instmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003465 Result += "\t ,{{(struct objc_selector *)\"";
3466 else
3467 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar56df9772010-08-17 22:39:59 +00003468 Result += (*I)->getSelector().getAsString();
Steve Naroffd9803712009-04-29 16:37:50 +00003469 std::string MethodTypeString;
3470 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3471 Result += "\", \"";
3472 Result += MethodTypeString;
3473 Result += "\"}\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003474 }
Steve Naroffd9803712009-04-29 16:37:50 +00003475 Result += "\t }\n};\n";
3476 }
Mike Stump11289f42009-09-09 15:08:12 +00003477
Steve Naroffd9803712009-04-29 16:37:50 +00003478 // Output class methods declared in this protocol.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003479 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3480 PDecl->classmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003481 if (NumMethods > 0) {
3482 /* struct _objc_protocol_method_list {
3483 int protocol_method_count;
3484 struct protocol_methods protocols[];
3485 }
3486 */
3487 Result += "\nstatic struct {\n";
3488 Result += "\tint protocol_method_count;\n";
3489 Result += "\tstruct _protocol_methods protocol_methods[";
3490 Result += utostr(NumMethods);
3491 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3492 Result += PDecl->getNameAsString();
3493 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3494 "{\n\t";
3495 Result += utostr(NumMethods);
3496 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003497
Steve Naroffd9803712009-04-29 16:37:50 +00003498 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003499 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003500 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003501 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003502 if (I == PDecl->classmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003503 Result += "\t ,{{(struct objc_selector *)\"";
3504 else
3505 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar56df9772010-08-17 22:39:59 +00003506 Result += (*I)->getSelector().getAsString();
Steve Naroffd9803712009-04-29 16:37:50 +00003507 std::string MethodTypeString;
3508 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3509 Result += "\", \"";
3510 Result += MethodTypeString;
3511 Result += "\"}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003512 }
Steve Naroffd9803712009-04-29 16:37:50 +00003513 Result += "\t }\n};\n";
3514 }
3515
3516 // Output:
3517 /* struct _objc_protocol {
3518 // Objective-C 1.0 extensions
3519 struct _objc_protocol_extension *isa;
3520 char *protocol_name;
3521 struct _objc_protocol **protocol_list;
3522 struct _objc_protocol_method_list *instance_methods;
3523 struct _objc_protocol_method_list *class_methods;
Mike Stump11289f42009-09-09 15:08:12 +00003524 };
Steve Naroffd9803712009-04-29 16:37:50 +00003525 */
3526 static bool objc_protocol = false;
3527 if (!objc_protocol) {
3528 Result += "\nstruct _objc_protocol {\n";
3529 Result += "\tstruct _objc_protocol_extension *isa;\n";
3530 Result += "\tchar *protocol_name;\n";
3531 Result += "\tstruct _objc_protocol **protocol_list;\n";
3532 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3533 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003534 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003535
Steve Naroffd9803712009-04-29 16:37:50 +00003536 objc_protocol = true;
Chris Lattner388f6e92008-07-21 21:33:21 +00003537 }
Mike Stump11289f42009-09-09 15:08:12 +00003538
Steve Naroffd9803712009-04-29 16:37:50 +00003539 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3540 Result += PDecl->getNameAsString();
3541 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3542 "{\n\t0, \"";
3543 Result += PDecl->getNameAsString();
3544 Result += "\", 0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003545 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003546 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3547 Result += PDecl->getNameAsString();
3548 Result += ", ";
3549 }
3550 else
3551 Result += "0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003552 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003553 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3554 Result += PDecl->getNameAsString();
3555 Result += "\n";
3556 }
3557 else
3558 Result += "0\n";
3559 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003560
Steve Naroffd9803712009-04-29 16:37:50 +00003561 // Mark this protocol as having been generated.
3562 if (!ObjCSynthesizedProtocols.insert(PDecl))
3563 assert(false && "protocol already synthesized");
3564
3565}
3566
3567void RewriteObjC::
3568RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
Daniel Dunbar56df9772010-08-17 22:39:59 +00003569 llvm::StringRef prefix, llvm::StringRef ClassName,
Steve Naroffd9803712009-04-29 16:37:50 +00003570 std::string &Result) {
3571 if (Protocols.empty()) return;
Mike Stump11289f42009-09-09 15:08:12 +00003572
Steve Naroffd9803712009-04-29 16:37:50 +00003573 for (unsigned i = 0; i != Protocols.size(); i++)
3574 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3575
Chris Lattner388f6e92008-07-21 21:33:21 +00003576 // Output the top lovel protocol meta-data for the class.
3577 /* struct _objc_protocol_list {
3578 struct _objc_protocol_list *next;
3579 int protocol_count;
3580 struct _objc_protocol *class_protocols[];
3581 }
3582 */
3583 Result += "\nstatic struct {\n";
3584 Result += "\tstruct _objc_protocol_list *next;\n";
3585 Result += "\tint protocol_count;\n";
3586 Result += "\tstruct _objc_protocol *class_protocols[";
3587 Result += utostr(Protocols.size());
3588 Result += "];\n} _OBJC_";
3589 Result += prefix;
3590 Result += "_PROTOCOLS_";
3591 Result += ClassName;
3592 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3593 "{\n\t0, ";
3594 Result += utostr(Protocols.size());
3595 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003596
Chris Lattner388f6e92008-07-21 21:33:21 +00003597 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003598 Result += Protocols[0]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003599 Result += " \n";
Mike Stump11289f42009-09-09 15:08:12 +00003600
Chris Lattner388f6e92008-07-21 21:33:21 +00003601 for (unsigned i = 1; i != Protocols.size(); i++) {
3602 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003603 Result += Protocols[i]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003604 Result += "\n";
3605 }
3606 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003607}
3608
Steve Naroffd9803712009-04-29 16:37:50 +00003609
Mike Stump11289f42009-09-09 15:08:12 +00003610/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003611/// implementation.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003612void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003613 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003614 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003615 // Find category declaration for this implementation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003616 ObjCCategoryDecl *CDecl;
Mike Stump11289f42009-09-09 15:08:12 +00003617 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003618 CDecl = CDecl->getNextClassCategory())
3619 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3620 break;
Mike Stump11289f42009-09-09 15:08:12 +00003621
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003622 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003623 FullCategoryName += '_';
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003624 FullCategoryName += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003625
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003626 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003627 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003628 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003629
3630 // If any of our property implementations have associated getters or
3631 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003632 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3633 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003634 Prop != PropEnd; ++Prop) {
3635 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3636 continue;
3637 if (!(*Prop)->getPropertyIvarDecl())
3638 continue;
3639 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3640 if (!PD)
3641 continue;
3642 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3643 InstanceMethods.push_back(Getter);
3644 if (PD->isReadOnly())
3645 continue;
3646 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3647 InstanceMethods.push_back(Setter);
3648 }
3649 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003650 true, "CATEGORY_", FullCategoryName.c_str(),
3651 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003652
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003653 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003654 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003655 false, "CATEGORY_", FullCategoryName.c_str(),
3656 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003657
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003658 // Protocols referenced in class declaration?
Fariborz Jahanian989e0392007-11-13 22:09:49 +00003659 // Null CDecl is case of a category implementation with no category interface
3660 if (CDecl)
Steve Naroffd9803712009-04-29 16:37:50 +00003661 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Daniel Dunbar56df9772010-08-17 22:39:59 +00003662 FullCategoryName, Result);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003663 /* struct _objc_category {
3664 char *category_name;
3665 char *class_name;
3666 struct _objc_method_list *instance_methods;
3667 struct _objc_method_list *class_methods;
3668 struct _objc_protocol_list *protocols;
3669 // Objective-C 1.0 extensions
3670 uint32_t size; // sizeof (struct _objc_category)
Mike Stump11289f42009-09-09 15:08:12 +00003671 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003672 // @property decl.
Mike Stump11289f42009-09-09 15:08:12 +00003673 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003674 */
Mike Stump11289f42009-09-09 15:08:12 +00003675
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003676 static bool objc_category = false;
3677 if (!objc_category) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003678 Result += "\nstruct _objc_category {\n";
3679 Result += "\tchar *category_name;\n";
3680 Result += "\tchar *class_name;\n";
3681 Result += "\tstruct _objc_method_list *instance_methods;\n";
3682 Result += "\tstruct _objc_method_list *class_methods;\n";
3683 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003684 Result += "\tunsigned int size;\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003685 Result += "\tstruct _objc_property_list *instance_properties;\n";
3686 Result += "};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003687 objc_category = true;
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003688 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003689 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3690 Result += FullCategoryName;
Steve Naroffb327e492008-03-12 17:18:30 +00003691 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003692 Result += IDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003693 Result += "\"\n\t, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003694 Result += ClassDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003695 Result += "\"\n";
Mike Stump11289f42009-09-09 15:08:12 +00003696
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003697 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003698 Result += "\t, (struct _objc_method_list *)"
3699 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3700 Result += FullCategoryName;
3701 Result += "\n";
3702 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003703 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003704 Result += "\t, 0\n";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003705 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003706 Result += "\t, (struct _objc_method_list *)"
3707 "&_OBJC_CATEGORY_CLASS_METHODS_";
3708 Result += FullCategoryName;
3709 Result += "\n";
3710 }
3711 else
3712 Result += "\t, 0\n";
Mike Stump11289f42009-09-09 15:08:12 +00003713
Chris Lattnerf5b77512009-02-20 18:18:36 +00003714 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump11289f42009-09-09 15:08:12 +00003715 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003716 Result += FullCategoryName;
3717 Result += "\n";
3718 }
3719 else
3720 Result += "\t, 0\n";
3721 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003722}
3723
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003724/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3725/// ivar offset.
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00003726void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003727 std::string &Result) {
Steve Naroffde7d0f62008-07-16 18:22:22 +00003728 if (ivar->isBitField()) {
3729 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3730 // place all bitfields at offset 0.
3731 Result += "0";
3732 } else {
3733 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00003734 Result += ivar->getContainingInterface()->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003735 if (LangOpts.Microsoft)
3736 Result += "_IMPL";
3737 Result += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003738 Result += ivar->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003739 Result += ")";
3740 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003741}
3742
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003743//===----------------------------------------------------------------------===//
3744// Meta Data Emission
3745//===----------------------------------------------------------------------===//
3746
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003747void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003748 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003749 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00003750
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003751 // Explictly declared @interface's are already synthesized.
Steve Naroffaac654a2009-04-20 20:09:33 +00003752 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump11289f42009-09-09 15:08:12 +00003753 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003754 // produce correct synthesis as yet.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003755 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003756 }
Mike Stump11289f42009-09-09 15:08:12 +00003757
Chris Lattner30d23e82007-12-12 07:56:42 +00003758 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003759 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump11289f42009-09-09 15:08:12 +00003760 ? IDecl->ivar_size()
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003761 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003762 if (NumIvars > 0) {
3763 static bool objc_ivar = false;
3764 if (!objc_ivar) {
3765 /* struct _objc_ivar {
3766 char *ivar_name;
3767 char *ivar_type;
3768 int ivar_offset;
Mike Stump11289f42009-09-09 15:08:12 +00003769 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003770 */
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003771 Result += "\nstruct _objc_ivar {\n";
3772 Result += "\tchar *ivar_name;\n";
3773 Result += "\tchar *ivar_type;\n";
3774 Result += "\tint ivar_offset;\n";
3775 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003776
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003777 objc_ivar = true;
3778 }
3779
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003780 /* struct {
3781 int ivar_count;
3782 struct _objc_ivar ivar_list[nIvars];
Mike Stump11289f42009-09-09 15:08:12 +00003783 };
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003784 */
Mike Stump11289f42009-09-09 15:08:12 +00003785 Result += "\nstatic struct {\n";
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003786 Result += "\tint ivar_count;\n";
3787 Result += "\tstruct _objc_ivar ivar_list[";
3788 Result += utostr(NumIvars);
3789 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003790 Result += IDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003791 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003792 "{\n\t";
3793 Result += utostr(NumIvars);
3794 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003795
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003796 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor5f662052009-04-23 03:23:08 +00003797 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003798 if (!IDecl->ivar_empty()) {
Fariborz Jahanianaef66222010-02-19 00:31:17 +00003799 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003800 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor5f662052009-04-23 03:23:08 +00003801 IV != IVEnd; ++IV)
3802 IVars.push_back(*IV);
Fariborz Jahanianaef66222010-02-19 00:31:17 +00003803 IVI = IDecl->ivar_begin();
3804 IVE = IDecl->ivar_end();
Chris Lattner30d23e82007-12-12 07:56:42 +00003805 } else {
3806 IVI = CDecl->ivar_begin();
3807 IVE = CDecl->ivar_end();
3808 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003809 Result += "\t,{{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003810 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003811 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003812 std::string TmpString, StrEncoding;
3813 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3814 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003815 Result += StrEncoding;
3816 Result += "\", ";
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00003817 SynthesizeIvarOffsetComputation(*IVI, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003818 Result += "}\n";
Chris Lattner30d23e82007-12-12 07:56:42 +00003819 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003820 Result += "\t ,{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003821 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003822 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003823 std::string TmpString, StrEncoding;
3824 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3825 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003826 Result += StrEncoding;
3827 Result += "\", ";
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00003828 SynthesizeIvarOffsetComputation((*IVI), Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003829 Result += "}\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003830 }
Mike Stump11289f42009-09-09 15:08:12 +00003831
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003832 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003833 }
Mike Stump11289f42009-09-09 15:08:12 +00003834
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003835 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003836 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003837 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003838
3839 // If any of our property implementations have associated getters or
3840 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003841 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3842 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003843 Prop != PropEnd; ++Prop) {
3844 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3845 continue;
3846 if (!(*Prop)->getPropertyIvarDecl())
3847 continue;
3848 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3849 if (!PD)
3850 continue;
3851 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +00003852 if (!Getter->isDefined())
3853 InstanceMethods.push_back(Getter);
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003854 if (PD->isReadOnly())
3855 continue;
3856 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +00003857 if (!Setter->isDefined())
3858 InstanceMethods.push_back(Setter);
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003859 }
3860 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Daniel Dunbar56df9772010-08-17 22:39:59 +00003861 true, "", IDecl->getName(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003862
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003863 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003864 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Daniel Dunbar56df9772010-08-17 22:39:59 +00003865 false, "", IDecl->getName(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003866
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003867 // Protocols referenced in class declaration?
Steve Naroffd9803712009-04-29 16:37:50 +00003868 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
Daniel Dunbar56df9772010-08-17 22:39:59 +00003869 "CLASS", CDecl->getName(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003870
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003871 // Declaration of class/meta-class metadata
3872 /* struct _objc_class {
3873 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003874 const char *super_class_name;
3875 char *name;
3876 long version;
3877 long info;
3878 long instance_size;
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003879 struct _objc_ivar_list *ivars;
3880 struct _objc_method_list *methods;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003881 struct objc_cache *cache;
3882 struct objc_protocol_list *protocols;
3883 const char *ivar_layout;
3884 struct _objc_class_ext *ext;
Mike Stump11289f42009-09-09 15:08:12 +00003885 };
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003886 */
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003887 static bool objc_class = false;
3888 if (!objc_class) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003889 Result += "\nstruct _objc_class {\n";
3890 Result += "\tstruct _objc_class *isa;\n";
3891 Result += "\tconst char *super_class_name;\n";
3892 Result += "\tchar *name;\n";
3893 Result += "\tlong version;\n";
3894 Result += "\tlong info;\n";
3895 Result += "\tlong instance_size;\n";
3896 Result += "\tstruct _objc_ivar_list *ivars;\n";
3897 Result += "\tstruct _objc_method_list *methods;\n";
3898 Result += "\tstruct objc_cache *cache;\n";
3899 Result += "\tstruct _objc_protocol_list *protocols;\n";
3900 Result += "\tconst char *ivar_layout;\n";
3901 Result += "\tstruct _objc_class_ext *ext;\n";
3902 Result += "};\n";
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003903 objc_class = true;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003904 }
Mike Stump11289f42009-09-09 15:08:12 +00003905
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003906 // Meta-class metadata generation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003907 ObjCInterfaceDecl *RootClass = 0;
3908 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003909 while (SuperClass) {
3910 RootClass = SuperClass;
3911 SuperClass = SuperClass->getSuperClass();
3912 }
3913 SuperClass = CDecl->getSuperClass();
Mike Stump11289f42009-09-09 15:08:12 +00003914
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003915 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003916 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003917 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003918 "{\n\t(struct _objc_class *)\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003919 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003920 Result += "\"";
3921
3922 if (SuperClass) {
3923 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003924 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003925 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003926 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003927 Result += "\"";
3928 }
3929 else {
3930 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003931 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003932 Result += "\"";
3933 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003934 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003935 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003936 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003937 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff0b844f02008-03-11 18:14:26 +00003938 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003939 Result += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003940 Result += "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003941 }
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003942 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003943 Result += ", 0\n";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003944 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003945 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003946 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003947 Result += ",0,0\n";
3948 }
Fariborz Jahanian486f7182007-10-24 20:54:23 +00003949 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003950 Result += "\t,0,0,0,0\n";
3951 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003952
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003953 // class metadata generation.
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003954 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003955 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003956 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003957 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003958 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003959 if (SuperClass) {
3960 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003961 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003962 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003963 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003964 Result += "\"";
3965 }
3966 else {
3967 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003968 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003969 Result += "\"";
3970 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003971 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003972 Result += ", 0,1";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003973 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003974 Result += ",0";
3975 else {
3976 // class has size. Must synthesize its size.
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00003977 Result += ",sizeof(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003978 Result += CDecl->getNameAsString();
Steve Naroff14a07462008-03-10 23:33:22 +00003979 if (LangOpts.Microsoft)
3980 Result += "_IMPL";
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003981 Result += ")";
3982 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003983 if (NumIvars > 0) {
Steve Naroff17978c42008-03-11 17:37:02 +00003984 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003985 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003986 Result += "\n\t";
3987 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003988 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003989 Result += ",0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003990 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003991 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003992 Result += CDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003993 Result += ", 0\n\t";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003994 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003995 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003996 Result += ",0,0";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003997 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003998 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003999 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004000 Result += ", 0,0\n";
4001 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00004002 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004003 Result += ",0,0,0\n";
4004 Result += "};\n";
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00004005}
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00004006
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00004007/// RewriteImplementations - This routine rewrites all method implementations
4008/// and emits meta-data.
4009
Steve Narofff8cfd162008-11-13 20:07:04 +00004010void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004011 int ClsDefCount = ClassImplementation.size();
4012 int CatDefCount = CategoryImplementation.size();
Mike Stump11289f42009-09-09 15:08:12 +00004013
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00004014 // Rewrite implemented methods
4015 for (int i = 0; i < ClsDefCount; i++)
4016 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump11289f42009-09-09 15:08:12 +00004017
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00004018 for (int i = 0; i < CatDefCount; i++)
4019 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofff8cfd162008-11-13 20:07:04 +00004020}
Mike Stump11289f42009-09-09 15:08:12 +00004021
Steve Narofff8cfd162008-11-13 20:07:04 +00004022void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
4023 int ClsDefCount = ClassImplementation.size();
4024 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00004025
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00004026 // For each implemented class, write out all its meta data.
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00004027 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004028 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump11289f42009-09-09 15:08:12 +00004029
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00004030 // For each implemented category, write out all its meta data.
4031 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004032 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroffd9803712009-04-29 16:37:50 +00004033
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004034 // Write objc_symtab metadata
4035 /*
4036 struct _objc_symtab
4037 {
4038 long sel_ref_cnt;
4039 SEL *refs;
4040 short cls_def_cnt;
4041 short cat_def_cnt;
4042 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump11289f42009-09-09 15:08:12 +00004043 };
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004044 */
Mike Stump11289f42009-09-09 15:08:12 +00004045
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004046 Result += "\nstruct _objc_symtab {\n";
4047 Result += "\tlong sel_ref_cnt;\n";
4048 Result += "\tSEL *refs;\n";
4049 Result += "\tshort cls_def_cnt;\n";
4050 Result += "\tshort cat_def_cnt;\n";
4051 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
4052 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00004053
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004054 Result += "static struct _objc_symtab "
Steve Naroffb327e492008-03-12 17:18:30 +00004055 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00004056 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004057 + ", " + utostr(CatDefCount) + "\n";
4058 for (int i = 0; i < ClsDefCount; i++) {
4059 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004060 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004061 Result += "\n";
4062 }
Mike Stump11289f42009-09-09 15:08:12 +00004063
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004064 for (int i = 0; i < CatDefCount; i++) {
4065 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004066 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004067 Result += "_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004068 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004069 Result += "\n";
4070 }
Mike Stump11289f42009-09-09 15:08:12 +00004071
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004072 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00004073
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004074 // Write objc_module metadata
Mike Stump11289f42009-09-09 15:08:12 +00004075
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004076 /*
4077 struct _objc_module {
4078 long version;
4079 long size;
4080 const char *name;
4081 struct _objc_symtab *symtab;
4082 }
4083 */
Mike Stump11289f42009-09-09 15:08:12 +00004084
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004085 Result += "\nstruct _objc_module {\n";
4086 Result += "\tlong version;\n";
4087 Result += "\tlong size;\n";
4088 Result += "\tconst char *name;\n";
4089 Result += "\tstruct _objc_symtab *symtab;\n";
4090 Result += "};\n\n";
4091 Result += "static struct _objc_module "
Steve Naroffb327e492008-03-12 17:18:30 +00004092 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00004093 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00004094 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004095 Result += "};\n\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00004096
4097 if (LangOpts.Microsoft) {
Steve Naroffd9803712009-04-29 16:37:50 +00004098 if (ProtocolExprDecls.size()) {
4099 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
4100 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump11289f42009-09-09 15:08:12 +00004101 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00004102 E = ProtocolExprDecls.end(); I != E; ++I) {
4103 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
4104 Result += (*I)->getNameAsString();
4105 Result += " = &_OBJC_PROTOCOL_";
4106 Result += (*I)->getNameAsString();
4107 Result += ";\n";
4108 }
4109 Result += "#pragma data_seg(pop)\n\n";
4110 }
Steve Naroff945a3b12008-03-10 20:43:59 +00004111 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffcab93d52008-05-07 00:06:16 +00004112 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00004113 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
4114 Result += "&_OBJC_MODULES;\n";
4115 Result += "#pragma data_seg(pop)\n\n";
4116 }
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004117}
Chris Lattnera7c19fe2007-10-16 22:36:42 +00004118
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004119void RewriteObjC::RewriteByRefString(std::string &ResultStr,
4120 const std::string &Name,
Fariborz Jahanianee504a02011-01-27 23:18:15 +00004121 ValueDecl *VD, bool def) {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004122 assert(BlockByRefDeclNo.count(VD) &&
4123 "RewriteByRefString: ByRef decl missing");
Fariborz Jahanianee504a02011-01-27 23:18:15 +00004124 if (def)
4125 ResultStr += "struct ";
4126 ResultStr += "__Block_byref_" + Name +
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004127 "_" + utostr(BlockByRefDeclNo[VD]) ;
4128}
4129
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004130static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4131 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4132 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4133 return false;
4134}
4135
Steve Naroff677ab3a2008-10-27 17:20:55 +00004136std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Daniel Dunbar56df9772010-08-17 22:39:59 +00004137 llvm::StringRef funcName,
Steve Naroff677ab3a2008-10-27 17:20:55 +00004138 std::string Tag) {
4139 const FunctionType *AFT = CE->getFunctionType();
4140 QualType RT = AFT->getResultType();
4141 std::string StructRef = "struct " + Tag;
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00004142 std::string S = "static " + RT.getAsString(Context->PrintingPolicy) + " __" +
Daniel Dunbar56df9772010-08-17 22:39:59 +00004143 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00004144
Steve Naroff677ab3a2008-10-27 17:20:55 +00004145 BlockDecl *BD = CE->getBlockDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004146
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004147 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump11289f42009-09-09 15:08:12 +00004148 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Narofff26a1d42009-02-02 17:19:26 +00004149 // block (to reference imported block decl refs).
4150 S += "(" + StructRef + " *__cself)";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004151 } else if (BD->param_empty()) {
4152 S += "(" + StructRef + " *__cself)";
4153 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004154 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004155 assert(FT && "SynthesizeBlockFunc: No function proto");
4156 S += '(';
4157 // first add the implicit argument.
4158 S += StructRef + " *__cself, ";
4159 std::string ParamStr;
4160 for (BlockDecl::param_iterator AI = BD->param_begin(),
4161 E = BD->param_end(); AI != E; ++AI) {
4162 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004163 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004164 QualType QT = (*AI)->getType();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00004165 if (convertBlockPointerToFunctionPointer(QT))
4166 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004167 else
4168 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004169 S += ParamStr;
4170 }
4171 if (FT->isVariadic()) {
4172 if (!BD->param_empty()) S += ", ";
4173 S += "...";
4174 }
4175 S += ')';
4176 }
4177 S += " {\n";
Mike Stump11289f42009-09-09 15:08:12 +00004178
Steve Naroff677ab3a2008-10-27 17:20:55 +00004179 // Create local declarations to avoid rewriting all closure decl ref exprs.
4180 // First, emit a declaration for all "by ref" decls.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004181 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004182 E = BlockByRefDecls.end(); I != E; ++I) {
4183 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004184 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004185 std::string TypeString;
4186 RewriteByRefString(TypeString, Name, (*I));
4187 TypeString += " *";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004188 Name = TypeString + Name;
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004189 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump11289f42009-09-09 15:08:12 +00004190 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004191 // Next, emit a declaration for all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004192 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004193 E = BlockByCopyDecls.end(); I != E; ++I) {
4194 S += " ";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004195 // Handle nested closure invocation. For example:
4196 //
4197 // void (^myImportedClosure)(void);
4198 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004199 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004200 // void (^anotherClosure)(void);
4201 // anotherClosure = ^(void) {
4202 // myImportedClosure(); // import and invoke the closure
4203 // };
4204 //
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00004205 if (isTopLevelBlockPointerType((*I)->getType())) {
4206 RewriteBlockPointerTypeVariable(S, (*I));
4207 S += " = (";
4208 RewriteBlockPointerType(S, (*I)->getType());
4209 S += ")";
4210 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4211 }
4212 else {
Fariborz Jahanianb6a68c02010-02-16 17:26:03 +00004213 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004214 QualType QT = (*I)->getType();
4215 if (HasLocalVariableExternalStorage(*I))
4216 QT = Context->getPointerType(QT);
4217 QT.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00004218 S += Name + " = __cself->" +
4219 (*I)->getNameAsString() + "; // bound by copy\n";
4220 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004221 }
4222 std::string RewrittenStr = RewrittenBlockExprs[CE];
4223 const char *cstr = RewrittenStr.c_str();
4224 while (*cstr++ != '{') ;
4225 S += cstr;
4226 S += "\n";
4227 return S;
4228}
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00004229
Steve Naroff677ab3a2008-10-27 17:20:55 +00004230std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Daniel Dunbar56df9772010-08-17 22:39:59 +00004231 llvm::StringRef funcName,
Steve Naroff677ab3a2008-10-27 17:20:55 +00004232 std::string Tag) {
4233 std::string StructRef = "struct " + Tag;
4234 std::string S = "static void __";
Mike Stump11289f42009-09-09 15:08:12 +00004235
Steve Naroff677ab3a2008-10-27 17:20:55 +00004236 S += funcName;
4237 S += "_block_copy_" + utostr(i);
4238 S += "(" + StructRef;
4239 S += "*dst, " + StructRef;
4240 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00004241 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004242 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00004243 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004244 S += (*I)->getNameAsString();
Steve Naroff5ac4eac2008-12-11 20:51:38 +00004245 S += ", (void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004246 S += (*I)->getNameAsString();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004247 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004248 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00004249 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004250 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004251 }
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00004252 S += "}\n";
4253
Steve Naroff677ab3a2008-10-27 17:20:55 +00004254 S += "\nstatic void __";
4255 S += funcName;
4256 S += "_block_dispose_" + utostr(i);
4257 S += "(" + StructRef;
4258 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00004259 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004260 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00004261 S += "_Block_object_dispose((void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004262 S += (*I)->getNameAsString();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004263 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004264 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00004265 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004266 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004267 }
Mike Stump11289f42009-09-09 15:08:12 +00004268 S += "}\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004269 return S;
4270}
4271
Steve Naroff30484702009-12-06 21:14:13 +00004272std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4273 std::string Desc) {
Steve Naroff295570a2008-10-30 12:09:33 +00004274 std::string S = "\nstruct " + Tag;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004275 std::string Constructor = " " + Tag;
Mike Stump11289f42009-09-09 15:08:12 +00004276
Steve Naroff677ab3a2008-10-27 17:20:55 +00004277 S += " {\n struct __block_impl impl;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004278 S += " struct " + Desc;
4279 S += "* Desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00004280
Steve Naroff30484702009-12-06 21:14:13 +00004281 Constructor += "(void *fp, "; // Invoke function pointer.
4282 Constructor += "struct " + Desc; // Descriptor pointer.
4283 Constructor += " *desc";
Mike Stump11289f42009-09-09 15:08:12 +00004284
Steve Naroff677ab3a2008-10-27 17:20:55 +00004285 if (BlockDeclRefs.size()) {
4286 // Output all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004287 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004288 E = BlockByCopyDecls.end(); I != E; ++I) {
4289 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004290 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004291 std::string ArgName = "_" + FieldName;
4292 // Handle nested closure invocation. For example:
4293 //
4294 // void (^myImportedBlock)(void);
4295 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004296 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004297 // void (^anotherBlock)(void);
4298 // anotherBlock = ^(void) {
4299 // myImportedBlock(); // import and invoke the closure
4300 // };
4301 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00004302 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004303 S += "struct __block_impl *";
4304 Constructor += ", void *" + ArgName;
4305 } else {
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004306 QualType QT = (*I)->getType();
4307 if (HasLocalVariableExternalStorage(*I))
4308 QT = Context->getPointerType(QT);
4309 QT.getAsStringInternal(FieldName, Context->PrintingPolicy);
4310 QT.getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004311 Constructor += ", " + ArgName;
4312 }
4313 S += FieldName + ";\n";
4314 }
4315 // Output all "by ref" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004316 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004317 E = BlockByRefDecls.end(); I != E; ++I) {
4318 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004319 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004320 std::string ArgName = "_" + FieldName;
4321 // Handle nested closure invocation. For example:
4322 //
4323 // void (^myImportedBlock)(void);
4324 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004325 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004326 // void (^anotherBlock)(void);
4327 // anotherBlock = ^(void) {
4328 // myImportedBlock(); // import and invoke the closure
4329 // };
4330 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00004331 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004332 S += "struct __block_impl *";
4333 Constructor += ", void *" + ArgName;
4334 } else {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004335 std::string TypeString;
4336 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004337 TypeString += " *";
4338 FieldName = TypeString + FieldName;
4339 ArgName = TypeString + ArgName;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004340 Constructor += ", " + ArgName;
4341 }
4342 S += FieldName + "; // by ref\n";
4343 }
4344 // Finish writing the constructor.
Fariborz Jahaniane6a4e392010-07-28 23:27:30 +00004345 Constructor += ", int flags=0)";
4346 // Initialize all "by copy" arguments.
4347 bool firsTime = true;
4348 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4349 E = BlockByCopyDecls.end(); I != E; ++I) {
4350 std::string Name = (*I)->getNameAsString();
4351 if (firsTime) {
4352 Constructor += " : ";
4353 firsTime = false;
4354 }
4355 else
4356 Constructor += ", ";
4357 if (isTopLevelBlockPointerType((*I)->getType()))
4358 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4359 else
4360 Constructor += Name + "(_" + Name + ")";
4361 }
4362 // Initialize all "by ref" arguments.
4363 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4364 E = BlockByRefDecls.end(); I != E; ++I) {
4365 std::string Name = (*I)->getNameAsString();
4366 if (firsTime) {
4367 Constructor += " : ";
4368 firsTime = false;
4369 }
4370 else
4371 Constructor += ", ";
4372 if (isTopLevelBlockPointerType((*I)->getType()))
4373 Constructor += Name + "((struct __block_impl *)_"
4374 + Name + "->__forwarding)";
4375 else
4376 Constructor += Name + "(_" + Name + "->__forwarding)";
4377 }
4378
4379 Constructor += " {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00004380 if (GlobalVarDecl)
4381 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4382 else
4383 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004384 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00004385
Steve Naroff30484702009-12-06 21:14:13 +00004386 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004387 } else {
4388 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004389 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00004390 if (GlobalVarDecl)
4391 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4392 else
4393 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004394 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4395 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004396 }
4397 Constructor += " ";
4398 Constructor += "}\n";
4399 S += Constructor;
4400 S += "};\n";
4401 return S;
4402}
4403
Steve Naroff30484702009-12-06 21:14:13 +00004404std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4405 std::string ImplTag, int i,
Daniel Dunbar56df9772010-08-17 22:39:59 +00004406 llvm::StringRef FunName,
Steve Naroff30484702009-12-06 21:14:13 +00004407 unsigned hasCopy) {
4408 std::string S = "\nstatic struct " + DescTag;
4409
4410 S += " {\n unsigned long reserved;\n";
4411 S += " unsigned long Block_size;\n";
4412 if (hasCopy) {
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004413 S += " void (*copy)(struct ";
4414 S += ImplTag; S += "*, struct ";
4415 S += ImplTag; S += "*);\n";
4416
4417 S += " void (*dispose)(struct ";
4418 S += ImplTag; S += "*);\n";
Steve Naroff30484702009-12-06 21:14:13 +00004419 }
4420 S += "} ";
4421
4422 S += DescTag + "_DATA = { 0, sizeof(struct ";
4423 S += ImplTag + ")";
4424 if (hasCopy) {
Daniel Dunbar56df9772010-08-17 22:39:59 +00004425 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4426 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff30484702009-12-06 21:14:13 +00004427 }
4428 S += "};\n";
4429 return S;
4430}
4431
Steve Naroff677ab3a2008-10-27 17:20:55 +00004432void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Daniel Dunbar56df9772010-08-17 22:39:59 +00004433 llvm::StringRef FunName) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004434 // Insert declaration for the function in which block literal is used.
Fariborz Jahanian5c26eee2010-01-15 18:14:52 +00004435 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004436 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00004437 bool RewriteSC = (GlobalVarDecl &&
4438 !Blocks.empty() &&
John McCall8e7d6562010-08-26 03:08:43 +00004439 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00004440 GlobalVarDecl->getType().getCVRQualifiers());
4441 if (RewriteSC) {
4442 std::string SC(" void __");
4443 SC += GlobalVarDecl->getNameAsString();
4444 SC += "() {}";
4445 InsertText(FunLocStart, SC);
4446 }
4447
Steve Naroff677ab3a2008-10-27 17:20:55 +00004448 // Insert closures that were part of the function.
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004449 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4450 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004451 // Need to copy-in the inner copied-in variables not actually used in this
4452 // block.
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004453 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4454 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
4455 ValueDecl *VD = Exp->getDecl();
4456 BlockDeclRefs.push_back(Exp);
4457 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4458 BlockByCopyDeclsPtrSet.insert(VD);
4459 BlockByCopyDecls.push_back(VD);
4460 }
4461 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4462 BlockByRefDeclsPtrSet.insert(VD);
4463 BlockByRefDecls.push_back(VD);
4464 }
Fariborz Jahanianfc8315f2010-10-05 18:05:06 +00004465 // imported objects in the inner blocks not used in the outer
4466 // blocks must be copied/disposed in the outer block as well.
4467 if (Exp->isByRef() ||
4468 VD->getType()->isObjCObjectPointerType() ||
4469 VD->getType()->isBlockPointerType())
4470 ImportedBlockDecls.insert(VD);
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004471 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004472
Daniel Dunbar56df9772010-08-17 22:39:59 +00004473 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4474 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump11289f42009-09-09 15:08:12 +00004475
Steve Naroff30484702009-12-06 21:14:13 +00004476 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004477
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004478 InsertText(FunLocStart, CI);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004479
Steve Naroff30484702009-12-06 21:14:13 +00004480 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump11289f42009-09-09 15:08:12 +00004481
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004482 InsertText(FunLocStart, CF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004483
4484 if (ImportedBlockDecls.size()) {
Steve Naroff30484702009-12-06 21:14:13 +00004485 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004486 InsertText(FunLocStart, HF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004487 }
Steve Naroff30484702009-12-06 21:14:13 +00004488 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4489 ImportedBlockDecls.size() > 0);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004490 InsertText(FunLocStart, BD);
Mike Stump11289f42009-09-09 15:08:12 +00004491
Steve Naroff677ab3a2008-10-27 17:20:55 +00004492 BlockDeclRefs.clear();
4493 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004494 BlockByRefDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004495 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004496 BlockByCopyDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004497 ImportedBlockDecls.clear();
4498 }
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00004499 if (RewriteSC) {
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004500 // Must insert any 'const/volatile/static here. Since it has been
4501 // removed as result of rewriting of block literals.
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004502 std::string SC;
John McCall8e7d6562010-08-26 03:08:43 +00004503 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004504 SC = "static ";
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004505 if (GlobalVarDecl->getType().isConstQualified())
4506 SC += "const ";
4507 if (GlobalVarDecl->getType().isVolatileQualified())
4508 SC += "volatile ";
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00004509 if (GlobalVarDecl->getType().isRestrictQualified())
4510 SC += "restrict ";
4511 InsertText(FunLocStart, SC);
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004512 }
4513
Steve Naroff677ab3a2008-10-27 17:20:55 +00004514 Blocks.clear();
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004515 InnerDeclRefsCount.clear();
4516 InnerDeclRefs.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004517 RewrittenBlockExprs.clear();
4518}
4519
4520void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4521 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Daniel Dunbar56df9772010-08-17 22:39:59 +00004522 llvm::StringRef FuncName = FD->getName();
Mike Stump11289f42009-09-09 15:08:12 +00004523
Steve Naroff677ab3a2008-10-27 17:20:55 +00004524 SynthesizeBlockLiterals(FunLocStart, FuncName);
4525}
4526
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004527static void BuildUniqueMethodName(std::string &Name,
4528 ObjCMethodDecl *MD) {
4529 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar56df9772010-08-17 22:39:59 +00004530 Name = IFace->getName();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004531 Name += "__" + MD->getSelector().getAsString();
4532 // Convert colons to underscores.
4533 std::string::size_type loc = 0;
4534 while ((loc = Name.find(":", loc)) != std::string::npos)
4535 Name.replace(loc, 1, "_");
4536}
4537
Steve Naroff677ab3a2008-10-27 17:20:55 +00004538void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff295570a2008-10-30 12:09:33 +00004539 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4540 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianb5f99c32010-01-29 01:55:49 +00004541 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004542 std::string FuncName;
4543 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar56df9772010-08-17 22:39:59 +00004544 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004545}
4546
4547void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4548 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4549 CI != E; ++CI)
4550 if (*CI) {
4551 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4552 GetBlockDeclRefExprs(CBE->getBody());
4553 else
4554 GetBlockDeclRefExprs(*CI);
4555 }
4556 // Handle specific things.
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004557 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004558 // FIXME: Handle enums.
4559 if (!isa<FunctionDecl>(CDRE->getDecl()))
4560 BlockDeclRefs.push_back(CDRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004561 }
4562 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4563 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
4564 BlockDeclRefExpr *BDRE =
John McCall351762c2011-02-07 10:33:21 +00004565 new (Context)BlockDeclRefExpr(cast<VarDecl>(DRE->getDecl()),
4566 DRE->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00004567 VK_LValue, DRE->getLocation(), false);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004568 BlockDeclRefs.push_back(BDRE);
4569 }
4570
Steve Naroff677ab3a2008-10-27 17:20:55 +00004571 return;
4572}
4573
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004574void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4575 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004576 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004577 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4578 CI != E; ++CI)
4579 if (*CI) {
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004580 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4581 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004582 GetInnerBlockDeclRefExprs(CBE->getBody(),
4583 InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004584 InnerContexts);
4585 }
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004586 else
4587 GetInnerBlockDeclRefExprs(*CI,
4588 InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004589 InnerContexts);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004590
4591 }
4592 // Handle specific things.
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004593 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004594 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004595 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004596 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004597 }
4598 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4599 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4600 if (Var->isFunctionOrMethodVarDecl())
4601 ImportedLocalExternalDecls.insert(Var);
4602 }
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004603
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004604 return;
4605}
4606
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004607/// convertFunctionTypeOfBlocks - This routine converts a function type
4608/// whose result type may be a block pointer or whose argument type(s)
4609/// might be block pointers to an equivalent funtion type replacing
4610/// all block pointers to function pointers.
4611QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4612 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4613 // FTP will be null for closures that don't take arguments.
4614 // Generate a funky cast.
4615 llvm::SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004616 QualType Res = FT->getResultType();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00004617 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004618
4619 if (FTP) {
4620 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4621 E = FTP->arg_type_end(); I && (I != E); ++I) {
4622 QualType t = *I;
4623 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00004624 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004625 HasBlockType = true;
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004626 ArgTypes.push_back(t);
4627 }
4628 }
4629 QualType FuncType;
4630 // FIXME. Does this work if block takes no argument but has a return type
4631 // which is of block type?
4632 if (HasBlockType)
John McCalldb40c7f2010-12-14 08:05:40 +00004633 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004634 else FuncType = QualType(FT, 0);
4635 return FuncType;
4636}
4637
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004638Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004639 // Navigate to relevant type information.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004640 const BlockPointerType *CPT = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004641
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004642 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004643 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004644 } else if (const BlockDeclRefExpr *CDRE =
4645 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004646 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004647 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004648 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004649 }
4650 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4651 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4652 }
4653 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4654 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4655 else if (const ConditionalOperator *CEXPR =
4656 dyn_cast<ConditionalOperator>(BlockExp)) {
4657 Expr *LHSExp = CEXPR->getLHS();
4658 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4659 Expr *RHSExp = CEXPR->getRHS();
4660 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4661 Expr *CONDExp = CEXPR->getCond();
4662 ConditionalOperator *CondExpr =
4663 new (Context) ConditionalOperator(CONDExp,
4664 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00004665 SourceLocation(), cast<Expr>(RHSStmt),
4666 (Expr*)0,
John McCall4bc41ae2010-11-18 19:01:18 +00004667 Exp->getType(), VK_RValue, OK_Ordinary);
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004668 return CondExpr;
Fariborz Jahanian6ab7ed42009-12-18 01:15:21 +00004669 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4670 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004671 } else {
4672 assert(1 && "RewriteBlockClass: Bad type");
4673 }
4674 assert(CPT && "RewriteBlockClass: Bad type");
John McCall9dd450b2009-09-21 23:43:11 +00004675 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004676 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004677 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004678 // FTP will be null for closures that don't take arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004679
Abramo Bagnara6150c882010-05-11 21:36:43 +00004680 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Steve Naroff350b6652008-10-30 10:07:53 +00004681 SourceLocation(),
4682 &Context->Idents.get("__block_impl"));
4683 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff677ab3a2008-10-27 17:20:55 +00004684
Steve Naroff350b6652008-10-30 10:07:53 +00004685 // Generate a funky cast.
4686 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00004687
Steve Naroff350b6652008-10-30 10:07:53 +00004688 // Push the block argument type.
4689 ArgTypes.push_back(PtrBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004690 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004691 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff350b6652008-10-30 10:07:53 +00004692 E = FTP->arg_type_end(); I && (I != E); ++I) {
4693 QualType t = *I;
4694 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian90d2e572010-11-05 18:34:46 +00004695 if (!convertBlockPointerToFunctionPointer(t))
4696 convertToUnqualifiedObjCType(t);
Steve Naroff350b6652008-10-30 10:07:53 +00004697 ArgTypes.push_back(t);
4698 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004699 }
Steve Naroff350b6652008-10-30 10:07:53 +00004700 // Now do the pointer to function cast.
John McCalldb40c7f2010-12-14 08:05:40 +00004701 QualType PtrToFuncCastType
4702 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
Mike Stump11289f42009-09-09 15:08:12 +00004703
Steve Naroff350b6652008-10-30 10:07:53 +00004704 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump11289f42009-09-09 15:08:12 +00004705
John McCall97513962010-01-15 18:39:57 +00004706 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCallf608deb2010-11-15 09:46:46 +00004707 CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00004708 const_cast<Expr*>(BlockExp));
Steve Naroff350b6652008-10-30 10:07:53 +00004709 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00004710 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4711 BlkCast);
Steve Naroff350b6652008-10-30 10:07:53 +00004712 //PE->dump();
Mike Stump11289f42009-09-09 15:08:12 +00004713
Douglas Gregor91f84212008-12-11 16:49:14 +00004714 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004715 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004716 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek5a201952009-02-07 01:47:29 +00004717 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
John McCall7decc9e2010-11-18 06:31:45 +00004718 FD->getType(), VK_LValue,
4719 OK_Ordinary);
Mike Stump11289f42009-09-09 15:08:12 +00004720
Fariborz Jahanian90d2e572010-11-05 18:34:46 +00004721
John McCall97513962010-01-15 18:39:57 +00004722 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCallf608deb2010-11-15 09:46:46 +00004723 CK_BitCast, ME);
Ted Kremenek5a201952009-02-07 01:47:29 +00004724 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump11289f42009-09-09 15:08:12 +00004725
Steve Naroff350b6652008-10-30 10:07:53 +00004726 llvm::SmallVector<Expr*, 8> BlkExprs;
4727 // Add the implicit argument.
4728 BlkExprs.push_back(BlkCast);
4729 // Add the user arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004730 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004731 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00004732 BlkExprs.push_back(*I);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004733 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004734 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4735 BlkExprs.size(),
John McCall7decc9e2010-11-18 06:31:45 +00004736 Exp->getType(), VK_RValue,
4737 SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004738 return CE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004739}
4740
Steve Naroffd9803712009-04-29 16:37:50 +00004741// We need to return the rewritten expression to handle cases where the
4742// BlockDeclRefExpr is embedded in another expression being rewritten.
4743// For example:
4744//
4745// int main() {
4746// __block Foo *f;
4747// __block int i;
Mike Stump11289f42009-09-09 15:08:12 +00004748//
Steve Naroffd9803712009-04-29 16:37:50 +00004749// void (^myblock)() = ^() {
4750// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4751// i = 77;
4752// };
4753//}
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004754Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanian25c07fa2009-12-23 19:26:34 +00004755 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004756 // for each DeclRefExp where BYREFVAR is name of the variable.
4757 ValueDecl *VD;
4758 bool isArrow = true;
4759 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4760 VD = BDRE->getDecl();
4761 else {
4762 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4763 isArrow = false;
4764 }
4765
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004766 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4767 &Context->Idents.get("__forwarding"),
4768 Context->VoidPtrTy, 0,
4769 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004770 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4771 FD, SourceLocation(),
John McCall7decc9e2010-11-18 06:31:45 +00004772 FD->getType(), VK_LValue,
4773 OK_Ordinary);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004774
Daniel Dunbar56df9772010-08-17 22:39:59 +00004775 llvm::StringRef Name = VD->getName();
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004776 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4777 &Context->Idents.get(Name),
4778 Context->VoidPtrTy, 0,
4779 /*BitWidth=*/0, /*Mutable=*/true);
4780 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
John McCall7decc9e2010-11-18 06:31:45 +00004781 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004782
4783
4784
Steve Narofff26a1d42009-02-02 17:19:26 +00004785 // Need parens to enforce precedence.
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004786 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4787 ME);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004788 ReplaceStmt(DeclRefExp, PE);
Steve Naroffd9803712009-04-29 16:37:50 +00004789 return PE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004790}
4791
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004792// Rewrites the imported local variable V with external storage
4793// (static, extern, etc.) as *V
4794//
4795Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4796 ValueDecl *VD = DRE->getDecl();
4797 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4798 if (!ImportedLocalExternalDecls.count(Var))
4799 return DRE;
John McCall7decc9e2010-11-18 06:31:45 +00004800 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4801 VK_LValue, OK_Ordinary,
4802 DRE->getLocation());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004803 // Need parens to enforce precedence.
4804 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4805 Exp);
4806 ReplaceStmt(DRE, PE);
4807 return PE;
4808}
4809
Steve Naroffc989a7b2008-11-03 23:29:32 +00004810void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4811 SourceLocation LocStart = CE->getLParenLoc();
4812 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofff4b992a2008-10-28 20:29:00 +00004813
4814 // Need to avoid trying to rewrite synthesized casts.
4815 if (LocStart.isInvalid())
4816 return;
Steve Naroff3e7ced12008-11-03 11:20:24 +00004817 // Need to avoid trying to rewrite casts contained in macros.
4818 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4819 return;
Mike Stump11289f42009-09-09 15:08:12 +00004820
Steve Naroff677ab3a2008-10-27 17:20:55 +00004821 const char *startBuf = SM->getCharacterData(LocStart);
4822 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004823 QualType QT = CE->getType();
4824 const Type* TypePtr = QT->getAs<Type>();
4825 if (isa<TypeOfExprType>(TypePtr)) {
4826 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4827 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4828 std::string TypeAsString = "(";
Fariborz Jahanianf5067912010-02-18 01:20:22 +00004829 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004830 TypeAsString += ")";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004831 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004832 return;
4833 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004834 // advance the location to startArgList.
4835 const char *argPtr = startBuf;
Mike Stump11289f42009-09-09 15:08:12 +00004836
Steve Naroff677ab3a2008-10-27 17:20:55 +00004837 while (*argPtr++ && (argPtr < endBuf)) {
4838 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004839 case '^':
4840 // Replace the '^' with '*'.
4841 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004842 ReplaceText(LocStart, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00004843 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004844 }
4845 }
4846 return;
4847}
4848
4849void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4850 SourceLocation DeclLoc = FD->getLocation();
4851 unsigned parenCount = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004852
Steve Naroff677ab3a2008-10-27 17:20:55 +00004853 // We have 1 or more arguments that have closure pointers.
4854 const char *startBuf = SM->getCharacterData(DeclLoc);
4855 const char *startArgList = strchr(startBuf, '(');
Mike Stump11289f42009-09-09 15:08:12 +00004856
Steve Naroff677ab3a2008-10-27 17:20:55 +00004857 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004858
Steve Naroff677ab3a2008-10-27 17:20:55 +00004859 parenCount++;
4860 // advance the location to startArgList.
4861 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4862 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump11289f42009-09-09 15:08:12 +00004863
Steve Naroff677ab3a2008-10-27 17:20:55 +00004864 const char *argPtr = startArgList;
Mike Stump11289f42009-09-09 15:08:12 +00004865
Steve Naroff677ab3a2008-10-27 17:20:55 +00004866 while (*argPtr++ && parenCount) {
4867 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004868 case '^':
4869 // Replace the '^' with '*'.
4870 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004871 ReplaceText(DeclLoc, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00004872 break;
4873 case '(':
4874 parenCount++;
4875 break;
4876 case ')':
4877 parenCount--;
4878 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004879 }
4880 }
4881 return;
4882}
4883
4884bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004885 const FunctionProtoType *FTP;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004886 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004887 if (PT) {
John McCall9dd450b2009-09-21 23:43:11 +00004888 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004889 } else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004890 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004891 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall9dd450b2009-09-21 23:43:11 +00004892 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004893 }
4894 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004895 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004896 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +00004897 if (isTopLevelBlockPointerType(*I))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004898 return true;
4899 }
4900 return false;
4901}
4902
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004903bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4904 const FunctionProtoType *FTP;
4905 const PointerType *PT = QT->getAs<PointerType>();
4906 if (PT) {
4907 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4908 } else {
4909 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4910 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4911 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4912 }
4913 if (FTP) {
4914 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Fariborz Jahanian733dde62010-11-03 23:50:34 +00004915 E = FTP->arg_type_end(); I != E; ++I) {
4916 if ((*I)->isObjCQualifiedIdType())
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004917 return true;
Fariborz Jahanian733dde62010-11-03 23:50:34 +00004918 if ((*I)->isObjCObjectPointerType() &&
4919 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4920 return true;
4921 }
4922
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004923 }
4924 return false;
4925}
4926
Ted Kremenek5a201952009-02-07 01:47:29 +00004927void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4928 const char *&RParen) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004929 const char *argPtr = strchr(Name, '(');
4930 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004931
Steve Naroff677ab3a2008-10-27 17:20:55 +00004932 LParen = argPtr; // output the start.
4933 argPtr++; // skip past the left paren.
4934 unsigned parenCount = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004935
Steve Naroff677ab3a2008-10-27 17:20:55 +00004936 while (*argPtr && parenCount) {
4937 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004938 case '(': parenCount++; break;
4939 case ')': parenCount--; break;
4940 default: break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004941 }
4942 if (parenCount) argPtr++;
4943 }
4944 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4945 RParen = argPtr; // output the end
4946}
4947
4948void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4949 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4950 RewriteBlockPointerFunctionArgs(FD);
4951 return;
Mike Stump11289f42009-09-09 15:08:12 +00004952 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004953 // Handle Variables and Typedefs.
4954 SourceLocation DeclLoc = ND->getLocation();
4955 QualType DeclT;
4956 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4957 DeclT = VD->getType();
4958 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4959 DeclT = TDD->getUnderlyingType();
4960 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4961 DeclT = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004962 else
Steve Naroff677ab3a2008-10-27 17:20:55 +00004963 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump11289f42009-09-09 15:08:12 +00004964
Steve Naroff677ab3a2008-10-27 17:20:55 +00004965 const char *startBuf = SM->getCharacterData(DeclLoc);
4966 const char *endBuf = startBuf;
4967 // scan backward (from the decl location) for the end of the previous decl.
4968 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4969 startBuf--;
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004970 SourceLocation Start = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4971 std::string buf;
4972 unsigned OrigLength=0;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004973 // *startBuf != '^' if we are dealing with a pointer to function that
4974 // may take block argument types (which will be handled below).
4975 if (*startBuf == '^') {
4976 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004977 buf = '*';
4978 startBuf++;
4979 OrigLength++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004980 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004981 while (*startBuf != ')') {
4982 buf += *startBuf;
4983 startBuf++;
4984 OrigLength++;
4985 }
4986 buf += ')';
4987 OrigLength++;
4988
4989 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4990 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004991 // Replace the '^' with '*' for arguments.
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004992 // Replace id<P> with id/*<>*/
Steve Naroff677ab3a2008-10-27 17:20:55 +00004993 DeclLoc = ND->getLocation();
4994 startBuf = SM->getCharacterData(DeclLoc);
4995 const char *argListBegin, *argListEnd;
4996 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4997 while (argListBegin < argListEnd) {
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004998 if (*argListBegin == '^')
4999 buf += '*';
5000 else if (*argListBegin == '<') {
5001 buf += "/*";
5002 buf += *argListBegin++;
5003 OrigLength++;;
5004 while (*argListBegin != '>') {
5005 buf += *argListBegin++;
5006 OrigLength++;
5007 }
5008 buf += *argListBegin;
5009 buf += "*/";
Steve Naroff677ab3a2008-10-27 17:20:55 +00005010 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00005011 else
5012 buf += *argListBegin;
Steve Naroff677ab3a2008-10-27 17:20:55 +00005013 argListBegin++;
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00005014 OrigLength++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00005015 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00005016 buf += ')';
5017 OrigLength++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00005018 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00005019 ReplaceText(Start, OrigLength, buf);
5020
Steve Naroff677ab3a2008-10-27 17:20:55 +00005021 return;
5022}
5023
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005024
5025/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5026/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5027/// struct Block_byref_id_object *src) {
5028/// _Block_object_assign (&_dest->object, _src->object,
5029/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5030/// [|BLOCK_FIELD_IS_WEAK]) // object
5031/// _Block_object_assign(&_dest->object, _src->object,
5032/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5033/// [|BLOCK_FIELD_IS_WEAK]) // block
5034/// }
5035/// And:
5036/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5037/// _Block_object_dispose(_src->object,
5038/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5039/// [|BLOCK_FIELD_IS_WEAK]) // object
5040/// _Block_object_dispose(_src->object,
5041/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5042/// [|BLOCK_FIELD_IS_WEAK]) // block
5043/// }
5044
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005045std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5046 int flag) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005047 std::string S;
Benjamin Kramere056cea2010-01-10 19:57:50 +00005048 if (CopyDestroyCache.count(flag))
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005049 return S;
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005050 CopyDestroyCache.insert(flag);
5051 S = "static void __Block_byref_id_object_copy_";
5052 S += utostr(flag);
5053 S += "(void *dst, void *src) {\n";
5054
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005055 // offset into the object pointer is computed as:
5056 // void * + void* + int + int + void* + void *
5057 unsigned IntSize =
5058 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5059 unsigned VoidPtrSize =
5060 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5061
5062 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
5063 S += " _Block_object_assign((char*)dst + ";
5064 S += utostr(offset);
5065 S += ", *(void * *) ((char*)src + ";
5066 S += utostr(offset);
5067 S += "), ";
5068 S += utostr(flag);
5069 S += ");\n}\n";
5070
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005071 S += "static void __Block_byref_id_object_dispose_";
5072 S += utostr(flag);
5073 S += "(void *src) {\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005074 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5075 S += utostr(offset);
5076 S += "), ";
5077 S += utostr(flag);
5078 S += ");\n}\n";
5079 return S;
5080}
5081
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005082/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5083/// the declaration into:
5084/// struct __Block_byref_ND {
5085/// void *__isa; // NULL for everything except __weak pointers
5086/// struct __Block_byref_ND *__forwarding;
5087/// int32_t __flags;
5088/// int32_t __size;
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005089/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5090/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005091/// typex ND;
5092/// };
5093///
5094/// It then replaces declaration of ND variable with:
5095/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5096/// __size=sizeof(struct __Block_byref_ND),
5097/// ND=initializer-if-any};
5098///
5099///
5100void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005101 // Insert declaration for the function in which block literal is
5102 // used.
5103 if (CurFunctionDeclToDeclareForBlock)
5104 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00005105 int flag = 0;
5106 int isa = 0;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005107 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahanian6005bd82010-02-26 22:49:11 +00005108 if (DeclLoc.isInvalid())
5109 // If type location is missing, it is because of missing type (a warning).
5110 // Use variable's location which is good for this case.
5111 DeclLoc = ND->getLocation();
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005112 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian92368a12009-12-30 20:38:08 +00005113 SourceLocation X = ND->getLocEnd();
5114 X = SM->getInstantiationLoc(X);
5115 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005116 std::string Name(ND->getNameAsString());
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005117 std::string ByrefType;
Fariborz Jahanianee504a02011-01-27 23:18:15 +00005118 RewriteByRefString(ByrefType, Name, ND, true);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005119 ByrefType += " {\n";
5120 ByrefType += " void *__isa;\n";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005121 RewriteByRefString(ByrefType, Name, ND);
5122 ByrefType += " *__forwarding;\n";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005123 ByrefType += " int __flags;\n";
5124 ByrefType += " int __size;\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005125 // Add void *__Block_byref_id_object_copy;
5126 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005127 QualType Ty = ND->getType();
5128 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
5129 if (HasCopyAndDispose) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005130 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5131 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005132 }
5133
5134 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005135 ByrefType += " " + Name + ";\n";
5136 ByrefType += "};\n";
5137 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00005138 SourceLocation FunLocStart;
5139 if (CurFunctionDef)
5140 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
5141 else {
5142 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5143 FunLocStart = CurMethodDef->getLocStart();
5144 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005145 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00005146 if (Ty.isObjCGCWeak()) {
5147 flag |= BLOCK_FIELD_IS_WEAK;
5148 isa = 1;
5149 }
5150
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005151 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005152 flag = BLOCK_BYREF_CALLER;
5153 QualType Ty = ND->getType();
5154 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5155 if (Ty->isBlockPointerType())
5156 flag |= BLOCK_FIELD_IS_BLOCK;
5157 else
5158 flag |= BLOCK_FIELD_IS_OBJECT;
5159 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005160 if (!HF.empty())
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005161 InsertText(FunLocStart, HF);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005162 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005163
5164 // struct __Block_byref_ND ND =
5165 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5166 // initializer-if-any};
5167 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanianf7945432010-01-05 18:15:57 +00005168 unsigned flags = 0;
5169 if (HasCopyAndDispose)
5170 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005171 Name = ND->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005172 ByrefType.clear();
5173 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005174 std::string ForwardingCastType("(");
5175 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005176 if (!hasInit) {
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00005177 ByrefType += " " + Name + " = {(void*)";
5178 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005179 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005180 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005181 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005182 ByrefType += "sizeof(";
5183 RewriteByRefString(ByrefType, Name, ND);
5184 ByrefType += ")";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005185 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005186 ByrefType += ", __Block_byref_id_object_copy_";
5187 ByrefType += utostr(flag);
5188 ByrefType += ", __Block_byref_id_object_dispose_";
5189 ByrefType += utostr(flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005190 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005191 ByrefType += "};\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005192 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(), ByrefType);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005193 }
5194 else {
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00005195 SourceLocation startLoc;
5196 Expr *E = ND->getInit();
5197 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5198 startLoc = ECE->getLParenLoc();
5199 else
5200 startLoc = E->getLocStart();
Fariborz Jahanianb8646ed2010-01-05 23:06:29 +00005201 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00005202 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005203 ByrefType += " " + Name;
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00005204 ByrefType += " = {(void*)";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00005205 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005206 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005207 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005208 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005209 ByrefType += "sizeof(";
5210 RewriteByRefString(ByrefType, Name, ND);
5211 ByrefType += "), ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005212 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005213 ByrefType += "__Block_byref_id_object_copy_";
5214 ByrefType += utostr(flag);
5215 ByrefType += ", __Block_byref_id_object_dispose_";
5216 ByrefType += utostr(flag);
5217 ByrefType += ", ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005218 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005219 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroff13468372009-12-23 17:24:33 +00005220
5221 // Complete the newly synthesized compound expression by inserting a right
5222 // curly brace before the end of the declaration.
5223 // FIXME: This approach avoids rewriting the initializer expression. It
5224 // also assumes there is only one declarator. For example, the following
5225 // isn't currently supported by this routine (in general):
5226 //
5227 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
5228 //
Fariborz Jahanian34c85982010-07-21 17:36:39 +00005229 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5230 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroff13468372009-12-23 17:24:33 +00005231 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
5232 SourceLocation semiLoc =
Fariborz Jahanian34c85982010-07-21 17:36:39 +00005233 startLoc.getFileLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroff13468372009-12-23 17:24:33 +00005234
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005235 InsertText(semiLoc, "}");
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005236 }
Fariborz Jahanian81203462009-12-22 00:48:54 +00005237 return;
5238}
5239
Mike Stump11289f42009-09-09 15:08:12 +00005240void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00005241 // Add initializers for any closure decl refs.
5242 GetBlockDeclRefExprs(Exp->getBody());
5243 if (BlockDeclRefs.size()) {
5244 // Unique all "by copy" declarations.
5245 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005246 if (!BlockDeclRefs[i]->isByRef()) {
5247 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5248 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5249 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5250 }
5251 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00005252 // Unique all "by ref" declarations.
5253 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5254 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005255 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5256 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5257 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5258 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00005259 }
5260 // Find any imported blocks...they will need special attention.
5261 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00005262 if (BlockDeclRefs[i]->isByRef() ||
5263 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian9bbc1482010-02-26 21:46:27 +00005264 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff677ab3a2008-10-27 17:20:55 +00005265 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff677ab3a2008-10-27 17:20:55 +00005266 }
5267}
5268
Daniel Dunbar56df9772010-08-17 22:39:59 +00005269FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(llvm::StringRef name) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005270 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005271 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump11289f42009-09-09 15:08:12 +00005272 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
John McCall8e7d6562010-08-26 03:08:43 +00005273 ID, FType, 0, SC_Extern,
5274 SC_None, false, false);
Steve Narofff4b992a2008-10-28 20:29:00 +00005275}
5276
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005277Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
5278 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005279 Blocks.push_back(Exp);
5280
5281 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005282
5283 // Add inner imported variables now used in current block.
5284 int countOfInnerDecls = 0;
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00005285 if (!InnerBlockDeclRefs.empty()) {
5286 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5287 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
5288 ValueDecl *VD = Exp->getDecl();
5289 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005290 // We need to save the copied-in variables in nested
5291 // blocks because it is needed at the end for some of the API generations.
5292 // See SynthesizeBlockLiterals routine.
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00005293 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5294 BlockDeclRefs.push_back(Exp);
5295 BlockByCopyDeclsPtrSet.insert(VD);
5296 BlockByCopyDecls.push_back(VD);
5297 }
5298 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
5299 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5300 BlockDeclRefs.push_back(Exp);
5301 BlockByRefDeclsPtrSet.insert(VD);
5302 BlockByRefDecls.push_back(VD);
5303 }
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005304 }
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00005305 // Find any imported blocks...they will need special attention.
5306 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5307 if (InnerBlockDeclRefs[i]->isByRef() ||
5308 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5309 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5310 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005311 }
5312 InnerDeclRefsCount.push_back(countOfInnerDecls);
5313
Steve Narofff4b992a2008-10-28 20:29:00 +00005314 std::string FuncName;
Mike Stump11289f42009-09-09 15:08:12 +00005315
Steve Narofff4b992a2008-10-28 20:29:00 +00005316 if (CurFunctionDef)
Chris Lattnere4b95692008-11-24 03:33:13 +00005317 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00005318 else if (CurMethodDef)
5319 BuildUniqueMethodName(FuncName, CurMethodDef);
5320 else if (GlobalVarDecl)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005321 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +00005322
Steve Narofff4b992a2008-10-28 20:29:00 +00005323 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump11289f42009-09-09 15:08:12 +00005324
Steve Narofff4b992a2008-10-28 20:29:00 +00005325 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
5326 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump11289f42009-09-09 15:08:12 +00005327
Steve Narofff4b992a2008-10-28 20:29:00 +00005328 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian19c62402010-05-25 15:56:08 +00005329 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5330 QualType FType = Context->getPointerType(BFT);
Steve Narofff4b992a2008-10-28 20:29:00 +00005331
5332 FunctionDecl *FD;
5333 Expr *NewRep;
Mike Stump11289f42009-09-09 15:08:12 +00005334
Steve Narofff4b992a2008-10-28 20:29:00 +00005335 // Simulate a contructor call...
Daniel Dunbar56df9772010-08-17 22:39:59 +00005336 FD = SynthBlockInitFunctionDecl(Tag);
John McCall7decc9e2010-11-18 06:31:45 +00005337 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, VK_RValue,
5338 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00005339
Steve Narofff4b992a2008-10-28 20:29:00 +00005340 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00005341
Steve Naroffe2514232008-10-29 21:23:59 +00005342 // Initialize the block function.
Daniel Dunbar56df9772010-08-17 22:39:59 +00005343 FD = SynthBlockInitFunctionDecl(Func);
John McCall7decc9e2010-11-18 06:31:45 +00005344 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
Ted Kremenek5a201952009-02-07 01:47:29 +00005345 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00005346 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCallf608deb2010-11-15 09:46:46 +00005347 CK_BitCast, Arg);
Mike Stump11289f42009-09-09 15:08:12 +00005348 InitExprs.push_back(castExpr);
5349
Steve Naroff30484702009-12-06 21:14:13 +00005350 // Initialize the block descriptor.
5351 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump11289f42009-09-09 15:08:12 +00005352
Steve Naroff30484702009-12-06 21:14:13 +00005353 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
5354 &Context->Idents.get(DescData.c_str()),
5355 Context->VoidPtrTy, 0,
John McCall8e7d6562010-08-26 03:08:43 +00005356 SC_Static, SC_None);
John McCall7decc9e2010-11-18 06:31:45 +00005357 UnaryOperator *DescRefExpr =
5358 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD,
5359 Context->VoidPtrTy,
5360 VK_LValue,
5361 SourceLocation()),
5362 UO_AddrOf,
5363 Context->getPointerType(Context->VoidPtrTy),
5364 VK_RValue, OK_Ordinary,
5365 SourceLocation());
Steve Naroff30484702009-12-06 21:14:13 +00005366 InitExprs.push_back(DescRefExpr);
5367
Steve Narofff4b992a2008-10-28 20:29:00 +00005368 // Add initializers for any closure decl refs.
5369 if (BlockDeclRefs.size()) {
Steve Naroffe2514232008-10-29 21:23:59 +00005370 Expr *Exp;
Steve Narofff4b992a2008-10-28 20:29:00 +00005371 // Output all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005372 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00005373 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005374 if (isObjCType((*I)->getType())) {
Steve Naroffe2514232008-10-29 21:23:59 +00005375 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar56df9772010-08-17 22:39:59 +00005376 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall7decc9e2010-11-18 06:31:45 +00005377 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5378 SourceLocation());
Fariborz Jahanian36680dd2010-05-24 18:32:56 +00005379 if (HasLocalVariableExternalStorage(*I)) {
5380 QualType QT = (*I)->getType();
5381 QT = Context->getPointerType(QT);
John McCall7decc9e2010-11-18 06:31:45 +00005382 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5383 OK_Ordinary, SourceLocation());
Fariborz Jahanian36680dd2010-05-24 18:32:56 +00005384 }
Steve Naroffa5c0db82008-12-11 21:05:33 +00005385 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar56df9772010-08-17 22:39:59 +00005386 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall7decc9e2010-11-18 06:31:45 +00005387 Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5388 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00005389 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCallf608deb2010-11-15 09:46:46 +00005390 CK_BitCast, Arg);
Steve Narofff4b992a2008-10-28 20:29:00 +00005391 } else {
Daniel Dunbar56df9772010-08-17 22:39:59 +00005392 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall7decc9e2010-11-18 06:31:45 +00005393 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5394 SourceLocation());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005395 if (HasLocalVariableExternalStorage(*I)) {
5396 QualType QT = (*I)->getType();
5397 QT = Context->getPointerType(QT);
John McCall7decc9e2010-11-18 06:31:45 +00005398 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5399 OK_Ordinary, SourceLocation());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005400 }
5401
Steve Narofff4b992a2008-10-28 20:29:00 +00005402 }
Mike Stump11289f42009-09-09 15:08:12 +00005403 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00005404 }
5405 // Output all "by ref" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005406 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00005407 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005408 ValueDecl *ND = (*I);
5409 std::string Name(ND->getNameAsString());
5410 std::string RecName;
Fariborz Jahanianee504a02011-01-27 23:18:15 +00005411 RewriteByRefString(RecName, Name, ND, true);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005412 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5413 + sizeof("struct"));
Abramo Bagnara6150c882010-05-11 21:36:43 +00005414 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005415 SourceLocation(), II);
5416 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5417 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5418
Daniel Dunbar56df9772010-08-17 22:39:59 +00005419 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall7decc9e2010-11-18 06:31:45 +00005420 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5421 SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00005422 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
John McCall7decc9e2010-11-18 06:31:45 +00005423 Context->getPointerType(Exp->getType()),
5424 VK_RValue, OK_Ordinary, SourceLocation());
John McCallf608deb2010-11-15 09:46:46 +00005425 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump11289f42009-09-09 15:08:12 +00005426 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00005427 }
5428 }
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00005429 if (ImportedBlockDecls.size()) {
5430 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5431 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff30484702009-12-06 21:14:13 +00005432 unsigned IntSize =
5433 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00005434 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5435 Context->IntTy, SourceLocation());
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00005436 InitExprs.push_back(FlagExp);
Steve Naroff30484702009-12-06 21:14:13 +00005437 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00005438 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
John McCall7decc9e2010-11-18 06:31:45 +00005439 FType, VK_LValue, SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00005440 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00005441 Context->getPointerType(NewRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00005442 VK_RValue, OK_Ordinary, SourceLocation());
John McCallf608deb2010-11-15 09:46:46 +00005443 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00005444 NewRep);
Steve Narofff4b992a2008-10-28 20:29:00 +00005445 BlockDeclRefs.clear();
5446 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005447 BlockByRefDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00005448 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005449 BlockByCopyDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00005450 ImportedBlockDecls.clear();
5451 return NewRep;
5452}
5453
5454//===----------------------------------------------------------------------===//
5455// Function Body / Expression rewriting
5456//===----------------------------------------------------------------------===//
5457
Steve Naroff4588d0f2008-12-04 16:24:46 +00005458// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
5459// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
5460// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
5461// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
5462// Since the rewriter isn't capable of rewriting rewritten code, it's important
5463// we get this right.
5464void RewriteObjC::CollectPropertySetters(Stmt *S) {
5465 // Perform a bottom up traversal of all children.
5466 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5467 CI != E; ++CI)
5468 if (*CI)
5469 CollectPropertySetters(*CI);
5470
5471 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
5472 if (BinOp->isAssignmentOp()) {
John McCallb7bd14f2010-12-02 01:19:52 +00005473 if (isa<ObjCPropertyRefExpr>(BinOp->getLHS()))
5474 PropSetters[BinOp->getLHS()] = BinOp;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005475 }
5476 }
5477}
5478
Steve Narofff4b992a2008-10-28 20:29:00 +00005479Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump11289f42009-09-09 15:08:12 +00005480 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00005481 isa<DoStmt>(S) || isa<ForStmt>(S))
5482 Stmts.push_back(S);
5483 else if (isa<ObjCForCollectionStmt>(S)) {
5484 Stmts.push_back(S);
Chris Lattnerb71980f2010-01-09 21:45:57 +00005485 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofff4b992a2008-10-28 20:29:00 +00005486 }
Mike Stump11289f42009-09-09 15:08:12 +00005487
Steve Narofff4b992a2008-10-28 20:29:00 +00005488 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005489
Steve Narofff4b992a2008-10-28 20:29:00 +00005490 // Perform a bottom up rewrite of all children.
5491 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5492 CI != E; ++CI)
5493 if (*CI) {
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00005494 Stmt *newStmt;
5495 Stmt *S = (*CI);
5496 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5497 Expr *OldBase = IvarRefExpr->getBase();
5498 bool replaced = false;
5499 newStmt = RewriteObjCNestedIvarRefExpr(S, replaced);
5500 if (replaced) {
5501 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
5502 ReplaceStmt(OldBase, IRE->getBase());
5503 else
5504 ReplaceStmt(S, newStmt);
5505 }
5506 }
5507 else
5508 newStmt = RewriteFunctionBodyOrGlobalInitializer(S);
Mike Stump11289f42009-09-09 15:08:12 +00005509 if (newStmt)
Steve Narofff4b992a2008-10-28 20:29:00 +00005510 *CI = newStmt;
Fariborz Jahanian163488f2010-10-08 21:12:22 +00005511 // If dealing with an assignment with LHS being a property reference
5512 // expression, the entire assignment tree is rewritten into a property
5513 // setter messaging. This involvs the RHS too. Do not attempt to rewrite
5514 // RHS again.
Fariborz Jahanianfef5d162010-10-11 22:21:03 +00005515 if (Expr *Exp = dyn_cast<Expr>(S))
John McCallb7bd14f2010-12-02 01:19:52 +00005516 if (isa<ObjCPropertyRefExpr>(Exp)) {
Fariborz Jahanianfef5d162010-10-11 22:21:03 +00005517 if (PropSetters[Exp]) {
5518 ++CI;
5519 continue;
5520 }
Fariborz Jahanian163488f2010-10-08 21:12:22 +00005521 }
Nick Lewycky508ef2c2010-10-31 21:07:24 +00005522 }
Mike Stump11289f42009-09-09 15:08:12 +00005523
Steve Narofff4b992a2008-10-28 20:29:00 +00005524 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005525 llvm::SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00005526 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5527 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005528 ImportedLocalExternalDecls.clear();
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005529 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00005530 InnerBlockDeclRefs, InnerContexts);
Steve Narofff4b992a2008-10-28 20:29:00 +00005531 // Rewrite the block body in place.
Fariborz Jahanian086a24a2010-11-08 18:37:50 +00005532 Stmt *SaveCurrentBody = CurrentBody;
5533 CurrentBody = BE->getBody();
5534 PropParentMap = 0;
Steve Narofff4b992a2008-10-28 20:29:00 +00005535 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanian086a24a2010-11-08 18:37:50 +00005536 CurrentBody = SaveCurrentBody;
5537 PropParentMap = 0;
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005538 ImportedLocalExternalDecls.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00005539 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenekdb2ef372010-01-07 18:00:35 +00005540 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroffd8907b72008-10-29 18:15:37 +00005541 RewrittenBlockExprs[BE] = Str;
Mike Stump11289f42009-09-09 15:08:12 +00005542
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005543 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5544
Steve Narofff4b992a2008-10-28 20:29:00 +00005545 //blockTranscribed->dump();
Steve Naroffd8907b72008-10-29 18:15:37 +00005546 ReplaceStmt(S, blockTranscribed);
Steve Narofff4b992a2008-10-28 20:29:00 +00005547 return blockTranscribed;
5548 }
5549 // Handle specific things.
5550 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5551 return RewriteAtEncode(AtEncode);
Mike Stump11289f42009-09-09 15:08:12 +00005552
John McCallb7bd14f2010-12-02 01:19:52 +00005553 if (isa<ObjCPropertyRefExpr>(S)) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00005554 Expr *PropOrImplicitRefExpr = dyn_cast<Expr>(S);
5555 assert(PropOrImplicitRefExpr && "Property or implicit setter/getter is null");
5556
5557 BinaryOperator *BinOp = PropSetters[PropOrImplicitRefExpr];
Steve Naroff4588d0f2008-12-04 16:24:46 +00005558 if (BinOp) {
5559 // Because the rewriter doesn't allow us to rewrite rewritten code,
5560 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroff08628db2008-12-09 12:56:34 +00005561 DisableReplaceStmt = true;
5562 // Save the source range. Even if we disable the replacement, the
5563 // rewritten node will have been inserted into the tree. If the synthesized
5564 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump11289f42009-09-09 15:08:12 +00005565 // self.errorHandler = handler ? handler :
Steve Naroff08628db2008-12-09 12:56:34 +00005566 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5567 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroff4588d0f2008-12-04 16:24:46 +00005568 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Fariborz Jahanian9c07e172010-10-14 23:31:39 +00005569 // Need to rewrite the ivar access expression if need be.
5570 if (isa<ObjCIvarRefExpr>(newStmt)) {
5571 bool replaced = false;
5572 newStmt = RewriteObjCNestedIvarRefExpr(newStmt, replaced);
5573 }
5574
Steve Naroff08628db2008-12-09 12:56:34 +00005575 DisableReplaceStmt = false;
Steve Naroff22216db2008-12-04 23:50:32 +00005576 //
5577 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
5578 // we changed the RHS of BinOp, the rewriter would fail (since it needs
5579 // to see the original expression). Consider this example:
5580 //
5581 // Foo *obj1, *obj2;
5582 //
5583 // obj1.i = [obj2 rrrr];
5584 //
5585 // 'BinOp' for the previous expression looks like:
5586 //
5587 // (BinaryOperator 0x231ccf0 'int' '='
5588 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5589 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5590 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5591 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5592 //
5593 // 'newStmt' represents the rewritten message expression. For example:
5594 //
5595 // (CallExpr 0x231d300 'id':'struct objc_object *'
5596 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5597 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5598 // (CStyleCastExpr 0x231d220 'void *'
5599 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5600 //
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00005601 // Note that 'newStmt' is passed to RewritePropertyOrImplicitSetter so that it
Steve Naroff22216db2008-12-04 23:50:32 +00005602 // can be used as the setter argument. ReplaceStmt() will still 'see'
5603 // the original RHS (since we haven't altered BinOp).
5604 //
Mike Stump11289f42009-09-09 15:08:12 +00005605 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff22216db2008-12-04 23:50:32 +00005606 // node. As a result, we now leak the original AST nodes.
5607 //
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00005608 return RewritePropertyOrImplicitSetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroff4588d0f2008-12-04 16:24:46 +00005609 } else {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00005610 return RewritePropertyOrImplicitGetter(PropOrImplicitRefExpr);
Steve Narofff326f402008-12-03 00:56:33 +00005611 }
5612 }
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00005613
Steve Narofff4b992a2008-10-28 20:29:00 +00005614 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5615 return RewriteAtSelector(AtSelector);
Mike Stump11289f42009-09-09 15:08:12 +00005616
Steve Narofff4b992a2008-10-28 20:29:00 +00005617 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5618 return RewriteObjCStringLiteral(AtString);
Mike Stump11289f42009-09-09 15:08:12 +00005619
Steve Narofff4b992a2008-10-28 20:29:00 +00005620 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00005621#if 0
Steve Narofff4b992a2008-10-28 20:29:00 +00005622 // Before we rewrite it, put the original message expression in a comment.
5623 SourceLocation startLoc = MessExpr->getLocStart();
5624 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00005625
Steve Narofff4b992a2008-10-28 20:29:00 +00005626 const char *startBuf = SM->getCharacterData(startLoc);
5627 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump11289f42009-09-09 15:08:12 +00005628
Steve Narofff4b992a2008-10-28 20:29:00 +00005629 std::string messString;
5630 messString += "// ";
5631 messString.append(startBuf, endBuf-startBuf+1);
5632 messString += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00005633
5634 // FIXME: Missing definition of
Steve Narofff4b992a2008-10-28 20:29:00 +00005635 // InsertText(clang::SourceLocation, char const*, unsigned int).
5636 // InsertText(startLoc, messString.c_str(), messString.size());
5637 // Tried this, but it didn't work either...
5638 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff4588d0f2008-12-04 16:24:46 +00005639#endif
Steve Narofff4b992a2008-10-28 20:29:00 +00005640 return RewriteMessageExpr(MessExpr);
5641 }
Mike Stump11289f42009-09-09 15:08:12 +00005642
Steve Narofff4b992a2008-10-28 20:29:00 +00005643 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5644 return RewriteObjCTryStmt(StmtTry);
5645
5646 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5647 return RewriteObjCSynchronizedStmt(StmtTry);
5648
5649 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5650 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump11289f42009-09-09 15:08:12 +00005651
Steve Narofff4b992a2008-10-28 20:29:00 +00005652 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5653 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump11289f42009-09-09 15:08:12 +00005654
5655 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofff4b992a2008-10-28 20:29:00 +00005656 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump11289f42009-09-09 15:08:12 +00005657 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofff4b992a2008-10-28 20:29:00 +00005658 OrigStmtRange.getEnd());
5659 if (BreakStmt *StmtBreakStmt =
5660 dyn_cast<BreakStmt>(S))
5661 return RewriteBreakStmt(StmtBreakStmt);
5662 if (ContinueStmt *StmtContinueStmt =
5663 dyn_cast<ContinueStmt>(S))
5664 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump11289f42009-09-09 15:08:12 +00005665
5666 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofff4b992a2008-10-28 20:29:00 +00005667 // and cast exprs.
5668 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5669 // FIXME: What we're doing here is modifying the type-specifier that
5670 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump11289f42009-09-09 15:08:12 +00005671 // a separate type-specifier that we can rewrite.
Steve Naroffe70a52a2009-12-05 15:55:59 +00005672 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5673 // the context of an ObjCForCollectionStmt. For example:
5674 // NSArray *someArray;
5675 // for (id <FooProtocol> index in someArray) ;
5676 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5677 // and it depends on the original text locations/positions.
Benjamin Krameracc5fa12009-12-05 22:16:51 +00005678 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroffe70a52a2009-12-05 15:55:59 +00005679 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump11289f42009-09-09 15:08:12 +00005680
Steve Narofff4b992a2008-10-28 20:29:00 +00005681 // Blocks rewrite rules.
5682 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5683 DI != DE; ++DI) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +00005684 Decl *SD = *DI;
Steve Narofff4b992a2008-10-28 20:29:00 +00005685 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005686 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005687 RewriteBlockPointerDecl(ND);
Mike Stump11289f42009-09-09 15:08:12 +00005688 else if (ND->getType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005689 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00005690 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005691 if (VD->hasAttr<BlocksAttr>()) {
5692 static unsigned uniqueByrefDeclCount = 0;
5693 assert(!BlockByRefDeclNo.count(ND) &&
5694 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5695 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005696 RewriteByRefVar(VD);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005697 }
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00005698 else
5699 RewriteTypeOfDecl(VD);
5700 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005701 }
5702 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005703 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005704 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005705 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005706 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5707 }
5708 }
5709 }
Mike Stump11289f42009-09-09 15:08:12 +00005710
Steve Narofff4b992a2008-10-28 20:29:00 +00005711 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5712 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump11289f42009-09-09 15:08:12 +00005713
5714 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00005715 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5716 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump11289f42009-09-09 15:08:12 +00005717 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5718 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005719 && "Statement stack mismatch");
5720 Stmts.pop_back();
5721 }
5722 // Handle blocks rewriting.
5723 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5724 if (BDRE->isByRef())
Steve Naroffd9803712009-04-29 16:37:50 +00005725 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofff4b992a2008-10-28 20:29:00 +00005726 }
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005727 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5728 ValueDecl *VD = DRE->getDecl();
5729 if (VD->hasAttr<BlocksAttr>())
5730 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005731 if (HasLocalVariableExternalStorage(VD))
5732 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005733 }
5734
Steve Narofff4b992a2008-10-28 20:29:00 +00005735 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff350b6652008-10-30 10:07:53 +00005736 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00005737 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00005738 ReplaceStmt(S, BlockCall);
5739 return BlockCall;
5740 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005741 }
Steve Naroffc989a7b2008-11-03 23:29:32 +00005742 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005743 RewriteCastExpr(CE);
5744 }
5745#if 0
5746 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005747 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5748 ICE->getSubExpr(),
5749 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00005750 // Get the new text.
5751 std::string SStr;
5752 llvm::raw_string_ostream Buf(SStr);
Eli Friedman0905f142009-05-30 05:19:26 +00005753 Replacement->printPretty(Buf, *Context);
Steve Narofff4b992a2008-10-28 20:29:00 +00005754 const std::string &Str = Buf.str();
5755
5756 printf("CAST = %s\n", &Str[0]);
5757 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5758 delete S;
5759 return Replacement;
5760 }
5761#endif
5762 // Return this stmt unmodified.
5763 return S;
5764}
5765
Steve Naroffe70a52a2009-12-05 15:55:59 +00005766void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5767 for (RecordDecl::field_iterator i = RD->field_begin(),
5768 e = RD->field_end(); i != e; ++i) {
5769 FieldDecl *FD = *i;
5770 if (isTopLevelBlockPointerType(FD->getType()))
5771 RewriteBlockPointerDecl(FD);
5772 if (FD->getType()->isObjCQualifiedIdType() ||
5773 FD->getType()->isObjCQualifiedInterfaceType())
5774 RewriteObjCQualifiedInterfaceTypes(FD);
5775 }
5776}
5777
Steve Narofff4b992a2008-10-28 20:29:00 +00005778/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5779/// main file of the input.
5780void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5781 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffb1368882008-12-17 00:20:22 +00005782 if (FD->isOverloadedOperator())
5783 return;
Mike Stump11289f42009-09-09 15:08:12 +00005784
Steve Narofff4b992a2008-10-28 20:29:00 +00005785 // Since function prototypes don't have ParmDecl's, we check the function
5786 // prototype. This enables us to rewrite function declarations and
5787 // definitions using the same code.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005788 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005789
Sebastian Redla7b98a72009-04-26 20:35:05 +00005790 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis568bc842010-07-07 11:31:34 +00005791 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005792 CurFunctionDef = FD;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005793 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005794 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005795 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005796 Body =
5797 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5798 FD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005799 CurrentBody = 0;
5800 if (PropParentMap) {
5801 delete PropParentMap;
5802 PropParentMap = 0;
5803 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005804 // This synthesizes and inserts the block "impl" struct, invoke function,
5805 // and any copy/dispose helper functions.
5806 InsertBlockLiteralsWithinFunction(FD);
5807 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005808 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005809 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005810 return;
5811 }
5812 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005813 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005814 CurMethodDef = MD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005815 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005816 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005817 Body =
5818 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5819 MD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005820 CurrentBody = 0;
5821 if (PropParentMap) {
5822 delete PropParentMap;
5823 PropParentMap = 0;
5824 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005825 InsertBlockLiteralsWithinMethod(MD);
5826 CurMethodDef = 0;
5827 }
5828 }
5829 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5830 ClassImplementation.push_back(CI);
5831 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5832 CategoryImplementation.push_back(CI);
5833 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5834 RewriteForwardClassDecl(CD);
5835 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5836 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroffa5c0db82008-12-11 21:05:33 +00005837 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005838 RewriteBlockPointerDecl(VD);
Steve Naroffd8907b72008-10-29 18:15:37 +00005839 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005840 CheckFunctionPointerDecl(VD->getType(), VD);
5841 if (VD->getInit()) {
Steve Naroffc989a7b2008-11-03 23:29:32 +00005842 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005843 RewriteCastExpr(CE);
5844 }
5845 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00005846 } else if (VD->getType()->isRecordType()) {
5847 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5848 if (RD->isDefinition())
5849 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005850 }
Steve Naroffd8907b72008-10-29 18:15:37 +00005851 if (VD->getInit()) {
5852 GlobalVarDecl = VD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005853 CollectPropertySetters(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005854 CurrentBody = VD->getInit();
Steve Naroffd8907b72008-10-29 18:15:37 +00005855 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005856 CurrentBody = 0;
5857 if (PropParentMap) {
5858 delete PropParentMap;
5859 PropParentMap = 0;
5860 }
Mike Stump11289f42009-09-09 15:08:12 +00005861 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Daniel Dunbar56df9772010-08-17 22:39:59 +00005862 VD->getName());
Steve Naroffd8907b72008-10-29 18:15:37 +00005863 GlobalVarDecl = 0;
5864
5865 // This is needed for blocks.
Steve Naroffc989a7b2008-11-03 23:29:32 +00005866 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroffd8907b72008-10-29 18:15:37 +00005867 RewriteCastExpr(CE);
5868 }
5869 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005870 return;
5871 }
5872 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005873 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005874 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005875 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005876 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5877 return;
5878 }
5879 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroffe70a52a2009-12-05 15:55:59 +00005880 if (RD->isDefinition())
5881 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005882 return;
5883 }
5884 // Nothing yet.
5885}
5886
Chris Lattnercf169832009-03-28 04:11:33 +00005887void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005888 if (Diags.hasErrorOccurred())
5889 return;
Mike Stump11289f42009-09-09 15:08:12 +00005890
Steve Narofff4b992a2008-10-28 20:29:00 +00005891 RewriteInclude();
Mike Stump11289f42009-09-09 15:08:12 +00005892
Steve Naroffd9803712009-04-29 16:37:50 +00005893 // Here's a great place to add any extra declarations that may be needed.
5894 // Write out meta data for each @protocol(<expr>).
Mike Stump11289f42009-09-09 15:08:12 +00005895 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00005896 E = ProtocolExprDecls.end(); I != E; ++I)
5897 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5898
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005899 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005900 if (ClassImplementation.size() || CategoryImplementation.size())
5901 RewriteImplementations();
Steve Naroffd9803712009-04-29 16:37:50 +00005902
Steve Narofff4b992a2008-10-28 20:29:00 +00005903 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5904 // we are done.
Mike Stump11289f42009-09-09 15:08:12 +00005905 if (const RewriteBuffer *RewriteBuf =
Steve Narofff4b992a2008-10-28 20:29:00 +00005906 Rewrite.getRewriteBufferFor(MainFileID)) {
5907 //printf("Changed:\n");
5908 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5909 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005910 llvm::errs() << "No changes\n";
Steve Narofff4b992a2008-10-28 20:29:00 +00005911 }
Steve Narofff8cfd162008-11-13 20:07:04 +00005912
Steve Naroffd9803712009-04-29 16:37:50 +00005913 if (ClassImplementation.size() || CategoryImplementation.size() ||
5914 ProtocolExprDecls.size()) {
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005915 // Rewrite Objective-c meta data*
5916 std::string ResultStr;
5917 SynthesizeMetaDataIntoBuffer(ResultStr);
5918 // Emit metadata.
5919 *OutFile << ResultStr;
5920 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005921 OutFile->flush();
5922}